@Test public void testFailureHandler() throws Exception { RoutingContext rc = mock(RoutingContext.class); Route currentRoute = mock(RouteImpl.class); when(currentRoute.getPath()).thenReturn("/blub"); when(rc.currentRoute()).thenReturn(currentRoute); ParsedHeaderValues headerValues = mock(ParsedHeaderValues.class); when(rc.parsedHeaders()).thenReturn(headerValues); HttpServerRequest request = mock(HttpServerRequest.class); when(request.query()).thenReturn("?blub"); when(request.method()).thenReturn(HttpMethod.GET); when(request.uri()).thenReturn(""); when(rc.request()).thenReturn(request); when(rc.normalisedPath()).thenReturn("/blub"); when(rc.queryParams()).thenReturn(new CaseInsensitiveHeaders()); storage.getRootRouter().handleFailure(rc); }
@Test public void testHandlerCase2() throws IOException { File uploadFolder = getUploadFolder(); try (Tx tx = tx()) { // Setup the schema & request prepareSchema(content(), null, "binaryField"); CaseInsensitiveHeaders attributes = new CaseInsensitiveHeaders(); attributes.add("language", "en"); attributes.add("version", "1.0"); InternalActionContext ac = mockContext(mockUpload("blub123")); // Assert initial condition assertFalse("Initially no upload folder should exist.", uploadFolder.exists()); // Invoke the request handler.handleUpdateField(ac, contentUuid(), "binaryField", attributes); // Assert result assertThat(uploadFolder).as("The upload folder should have been created").exists(); } }
@Test(expected = GenericRestException.class) public void testFileUploadWithNoUploadFile() throws Throwable { try (Tx tx = tx()) { // Setup the schema & request prepareSchema(content(), null, "binaryField"); FileUpload upload = mockUpload("blub123"); InternalActionContext ac = mockContext(upload); CaseInsensitiveHeaders attributes = new CaseInsensitiveHeaders(); attributes.add("language", "en"); attributes.add("version", "1.0"); // Delete the file on purpose in order to invoke an error new File(upload.uploadedFileName()).delete(); // Invoke the request handler.handleUpdateField(ac, contentUuid(), "binaryField", attributes); } }
public RestClientOptions(final JsonObject json) { super(json); final JsonObject jsonObjectGlobalRequestCacheOptions = json.getJsonObject("globalRequestCacheOptions"); if (jsonObjectGlobalRequestCacheOptions != null) { final RequestCacheOptions requestCacheOptions = new RequestCacheOptions(); final Integer ttlInMillis = jsonObjectGlobalRequestCacheOptions.getInteger("ttlInMillis"); final Boolean evictBefore = jsonObjectGlobalRequestCacheOptions.getBoolean("evictBefore"); if (jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes") != null) { final Set<Integer> cachedStatusCodes = jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes") .stream() .map(e -> (Integer) e) .collect(Collectors.toSet()); requestCacheOptions.withCachedStatusCodes(cachedStatusCodes); } if (ttlInMillis != null) { requestCacheOptions.withExpiresAfterWriteMillis(ttlInMillis); } if (evictBefore != null) { requestCacheOptions.withEvictBefore(evictBefore); } globalRequestCacheOptions = requestCacheOptions; } globalHeaders = new CaseInsensitiveHeaders(); globalRequestTimeoutInMillis = json.getLong("globalRequestTimeoutInMillis", DEFAULT_GLOBAL_REQUEST_TIMEOUT_IN_MILLIS); }
public MultiPart(List<EncodedPart> parts, String mode) { String boundary = Utils.generateBoundary(); headers = new CaseInsensitiveHeaders(); headers.set("Content-Type", "multipart/" + mode + "; boundary=\"" + boundary + "\""); StringBuilder sb = new StringBuilder(); for (EncodedPart part : parts) { sb.append("--"); sb.append(boundary); sb.append('\n'); sb.append(part.asString()); sb.append("\n\n"); } sb.append("--"); sb.append(boundary); sb.append("--"); part = sb.toString(); }
/** * copy object to another @link MailMessage object * * @param other object to copy */ public MailMessage(MailMessage other) { Objects.requireNonNull(other); this.bounceAddress = other.bounceAddress; this.from = other.from; this.to = copyList(other.to); this.cc = copyList(other.cc); this.bcc = copyList(other.bcc); this.subject = other.subject; this.text = other.text; this.html = other.html; if (other.attachment != null) { this.attachment = copyAttachments(other.attachment); } if (other.inlineAttachment != null) { this.inlineAttachment = copyAttachments(other.inlineAttachment); } if (other.headers != null) { headers = new CaseInsensitiveHeaders().addAll(other.headers); } }
@Test public void testFixedHeadersMultiple() { MailMessage message = new MailMessage(); final MultiMap headers = new CaseInsensitiveHeaders(); headers.add("Header", "value1"); headers.add("Header", "value2"); headers.add("Header2", "value3"); headers.add("Header", "value4"); message.setHeaders(headers); message.setFixedHeaders(true); message.setText("message text"); String mime = new MailEncoder(message, HOSTNAME).encode(); assertEquals("Header: value1\n" + "Header: value2\n" + "Header2: value3\n" + "Header: value4\n" + "\n" + "message text", TestUtils.conv2nl(mime)); }
@Test public void testExternalAuthProviderFails(TestContext context) throws Exception { AtomicInteger count = new AtomicInteger(); AuthProvider authProvider = (authInfo, resultHandler) -> { count.incrementAndGet(); resultHandler.handle(Future.failedFuture("not authenticated")); }; Async async = context.async(); server = createServer(context, new HttpTermOptions().setPort(8080)); server.authProvider(authProvider); server.termHandler(term -> { context.fail(); }); server.listen(context.asyncAssertSuccess(server -> { HttpClient client = vertx.createHttpClient(); client.websocket(8080, "localhost", basePath + "/shell/websocket", new CaseInsensitiveHeaders().add("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes())), ws -> { context.fail(); }, err -> { assertEquals(1, count.get()); async.complete(); }); })); }
@Test public void testDifferentCharset(TestContext context) throws Exception { Async async = context.async(); server = createServer(context, new HttpTermOptions().setPort(8080).setCharset("ISO_8859_1")); server.termHandler(term -> { term.write("\u20AC"); term.close(); }); server.listen(context.asyncAssertSuccess(server -> { HttpClient client = vertx.createHttpClient(); client.websocket(8080, "localhost", basePath + "/shell/websocket", new CaseInsensitiveHeaders().add("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes())), ws -> { ws.handler(buf -> { context.assertTrue(Arrays.equals(new byte[]{63}, buf.getBytes())); async.complete(); }); }, context::fail); })); }
@Test public void testKeymapFromFilesystem(TestContext context) throws Exception { URL url = TermServer.class.getResource(SSHTermOptions.DEFAULT_INPUTRC); File f = new File(url.toURI()); Async async = context.async(); server = createServer(context, new HttpTermOptions().setPort(8080).setIntputrc(f.getAbsolutePath())); server.termHandler(term -> { term.close(); async.complete(); }); server.listen(context.asyncAssertSuccess(server -> { HttpClient client = vertx.createHttpClient(); client.websocket(8080, "localhost", basePath + "/shell/websocket", new CaseInsensitiveHeaders().add("Authorization", "Basic " + Base64.getEncoder().encodeToString("paulo:anothersecret".getBytes())), ws -> { ws.handler(buf -> { }); }, context::fail); })); }
HttpRequestImpl(WebClientImpl client, HttpMethod method, String protocol, boolean ssl, int port, String host, String uri, BodyCodec<T> codec, WebClientOptions options) { this.client = client; this.method = method; this.protocol = protocol; this.codec = codec; this.port = port; this.host = host; this.uri = uri; this.ssl = ssl; this.followRedirects = options.isFollowRedirects(); this.options = options; if (options.isUserAgentEnabled()) { headers = new CaseInsensitiveHeaders().add(HttpHeaders.USER_AGENT, options.getUserAgent()); } }
@Test public void testAfterReceiveResponseNormal(@Mocked Invocation invocation, @Mocked HttpServletResponseEx responseEx, @Mocked Buffer bodyBuffer, @Mocked OperationMeta operationMeta, @Mocked ResponseMeta responseMeta, @Mocked RestOperationMeta swaggerRestOperation, @Mocked ProduceProcessor produceProcessor) throws Exception { MultiMap responseHeader = new CaseInsensitiveHeaders(); responseHeader.add("b", "bValue"); Object decodedResult = new Object(); new Expectations() { { responseEx.getHeader(HttpHeaders.CONTENT_TYPE); result = "json"; responseEx.getHeaderNames(); result = Arrays.asList("a", "b"); responseEx.getHeaders("b"); result = responseHeader.getAll("b"); swaggerRestOperation.findProduceProcessor("json"); result = produceProcessor; produceProcessor.decodeResponse(bodyBuffer, responseMeta.getJavaType()); result = decodedResult; invocation.getOperationMeta(); result = operationMeta; operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION); result = swaggerRestOperation; responseEx.getStatusType(); result = Status.OK; } }; Response response = filter.afterReceiveResponse(invocation, responseEx); Assert.assertSame(decodedResult, response.getResult()); Assert.assertEquals(1, response.getHeaders().getHeaderMap().size()); Assert.assertEquals(response.getHeaders().getHeader("b"), Arrays.asList("bValue")); }
@Override public MultiMap generate(RoutingContext context) { CaseInsensitiveHeaders headers = new CaseInsensitiveHeaders(); context.request().headers().entries().stream() .filter(entry -> entry.getKey().startsWith(headerPrefix)) .forEach(entry -> headers.set(entry.getKey().substring(headerPrefix.length()), entry.getValue())); return headers; }
private static HttpPart constructHttpPart(Document document, Buffer buffer, String mimeType) { HttpPart contentHttpPart = new HttpPart(); MultiMap headers = new CaseInsensitiveHeaders(); if (mimeType != null) { headers.add(HttpHeaders.CONTENT_TYPE, mimeType); } else { headers.add(HttpHeaders.CONTENT_TYPE, Format.JSON.getDefaultMimetype()); } headers.add(HttpHeaders.CONTENT_LENGTH, Integer.toString(buffer.length())); headers.add(HttpUtils.HEADER_CONTENT_DISPOSITION, computeContentDisposition(document, mimeType != null)); contentHttpPart.headers(headers).buffer(buffer); return contentHttpPart; }
public HttpPart(Buffer bodyBuffer) { this.buffer = Buffer.buffer(); List<String> headersList = new ArrayList<>(); // We need to extract headers and content from buffer RecordParser parser = RecordParser.newDelimited("\r\n", new Handler<Buffer>() { int pos = 0; boolean startContent = false; @Override public void handle(Buffer frame) { if (frame.length() == 0) { if (pos > 0) { startContent = true; } } else { if (!startContent) { headersList.add(frame.toString().trim()); } else { buffer.appendBuffer(frame); } } pos++; } }); parser.handle(bodyBuffer); this.headers = new CaseInsensitiveHeaders(); for (String header : headersList) { int offset = header.indexOf(":"); this.headers.add(header.substring(0, offset), header.substring(offset + 1).trim()); } this.contentType = HttpUtils.extractContentType(headers); this.contentDisposition = HttpUtils.extractContentDisposition(headers); }
public RestClientOptions(final RestClientOptions other) { super(other); globalRequestCacheOptions = other.globalRequestCacheOptions; globalHeaders = new CaseInsensitiveHeaders().addAll(other.getGlobalHeaders()); globalRequestTimeoutInMillis = other.getGlobalRequestTimeoutInMillis(); }
/** * create a copy of a MailAttachment object * * @param other object to be copied */ public MailAttachment(final MailAttachment other) { Objects.requireNonNull(other); this.data = other.data == null ? null : other.data.copy(); this.name = other.name; this.contentType = other.contentType; this.disposition = other.disposition; this.description = other.description; this.description = other.description; this.contentId = other.contentId; this.headers = other.headers == null ? null : new CaseInsensitiveHeaders().addAll(other.headers); }
/** * create the headers of the MIME message by combining the headers the user has supplied with the ones necessary for * the message * * @return MultiMap of final headers */ private MultiMap createHeaders(MultiMap additionalHeaders) { MultiMap headers = new CaseInsensitiveHeaders(); if (!message.isFixedHeaders()) { headers.set("MIME-Version", "1.0"); headers.set("Message-ID", Utils.generateMessageID(hostname)); headers.set("Date", Utils.generateDate()); if (message.getSubject() != null) { headers.set("Subject", Utils.encodeHeader(message.getSubject(), 9)); } if (message.getFrom() != null) { headers.set("From", Utils.encodeHeaderEmail(message.getFrom(), 6)); } if (message.getTo() != null) { headers.set("To", Utils.encodeEmailList(message.getTo(), 4)); } if (message.getCc() != null) { headers.set("Cc", Utils.encodeEmailList(message.getCc(), 4)); } headers.addAll(additionalHeaders); } // add the user-supplied headers as last step, this way it is possible // to supply a custom Message-ID for example. MultiMap headersToSet = message.getHeaders(); if (headersToSet != null) { for (String key : headersToSet.names()) { headers.remove(key); } headers.addAll(headersToSet); } messageID = headers.get("Message-ID"); return headers; }
static MultiMap jsonToMultiMap(final JsonObject jsonHeaders) { MultiMap headers = new CaseInsensitiveHeaders(); for (String key : jsonHeaders.getMap().keySet()) { headers.add(key, getKeyAsStringOrList(jsonHeaders, key)); } return headers; }
@Test public void testConstructorFromClassHeaders() { MailMessage message = new MailMessage(); message.setHeaders(new CaseInsensitiveHeaders()); MailMessage message2 = new MailMessage(message); // cannot use equals since CaseInsensitiveHeaders doesn't implement that assertEquals(message.toJson().encode(), message2.toJson().encode()); }
@Test public void testHeadersEmpty() { MailMessage mailMessage = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); mailMessage.setHeaders(headers); assertEquals(0, mailMessage.getHeaders().size()); assertEquals("{\"headers\":{}}", mailMessage.toJson().encode()); }
@Test public void testHeadersValue() { MailMessage mailMessage = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.add("Header", "value"); mailMessage.setHeaders(headers); assertEquals("{\"headers\":{\"Header\":[\"value\"]}}", mailMessage.toJson().encode()); }
@Test public void testHeadersMultipleKeys() { MailMessage mailMessage = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.add("Header", "value"); headers.add("Header2", "value2"); mailMessage.setHeaders(headers); assertEquals("{\"headers\":{\"Header\":[\"value\"],\"Header2\":[\"value2\"]}}", mailMessage.toJson().encode()); }
@Test public void testHeadersMultipleValues() { MailMessage mailMessage = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.add("Header", "value1"); headers.add("Header", "value2"); headers.add("Header2", "value3"); mailMessage.setHeaders(headers); assertEquals("{\"headers\":{\"Header\":[\"value1\",\"value2\"],\"Header2\":[\"value3\"]}}", mailMessage.toJson().encode()); }
@Test public void testHeaders() { MailMessage message = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.set("X-Header", "value"); message.setHeaders(headers); String mime = new MailEncoder(message, HOSTNAME).encode(); assertThat(mime, containsString("X-Header: value")); }
@Test public void testHeadersExist() { MailMessage message = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.set("mime-version", "2.1"); message.setHeaders(headers); String mime = new MailEncoder(message, HOSTNAME).encode().toLowerCase(Locale.ENGLISH); assertThat(mime, containsString("mime-version: 2.1")); assertThat(mime, not(containsString("mime-version: 1.0"))); }
@Test public void testFixedHeaders() { MailMessage message = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.set("X-Header", "value"); message.setHeaders(headers); message.setFixedHeaders(true); String mime = new MailEncoder(message, HOSTNAME).encode(); assertThat(mime, containsString("X-Header: value")); assertThat(mime, not(containsString("MIME-Version: 1.0"))); }
@Test public void testFixedHeadersExist() { MailMessage message = new MailMessage(); MultiMap headers = new CaseInsensitiveHeaders(); headers.set("Content-Type", "type"); message.setHeaders(headers); message.setFixedHeaders(true); String mime = new MailEncoder(message, HOSTNAME).encode(); assertThat(mime, containsString("Content-Type: type")); assertThat(mime, not(containsString("Content-Type: text/plain"))); }
@Test public void testFixedHeadersMessage() { MailMessage message = new MailMessage(); message.setHeaders(new CaseInsensitiveHeaders()); message.setFixedHeaders(true); message.setText("message text"); String mime = new MailEncoder(message, HOSTNAME).encode(); assertEquals("\nmessage text", TestUtils.conv2nl(mime)); }
@Test public void testAdditionalHeadersAttachment() { MailMessage message = new MailMessage(); MailAttachment attachment = new MailAttachment(); attachment.setData(Buffer.buffer("XXX")) .setHeaders(new CaseInsensitiveHeaders().add("X-Header", "value")); message.setAttachment(attachment); String mime = new MailEncoder(message, HOSTNAME).encode(); assertThat(mime, containsString("X-Header: value")); }
@Test public void testSecure(TestContext context) { Async async = context.async(); server = createServer(context, new HttpTermOptions().setAuthOptions( new ShiroAuthOptions(). setType(ShiroAuthRealmType.PROPERTIES). setConfig(new JsonObject().put("properties_path", "classpath:test-auth.properties"))).setPort(8080)); server.termHandler(term -> { term.write("hello"); }); server.listen(context.asyncAssertSuccess(server -> { HttpClient client = vertx.createHttpClient(); client.websocket(8080, "localhost", basePath + "/shell/websocket", ws -> { context.fail(); }, err -> { // Retry now with auth client.websocket(8080, "localhost", basePath + "/shell/websocket", new CaseInsensitiveHeaders().add("Authorization", "Basic " + Base64.getEncoder().encodeToString("tim:sausages".getBytes())), ws -> { ws.handler(buf -> { context.assertEquals("hello", buf.toString()); async.complete(); }); }, context::fail); }); })); }
@Test public void testBusTailVerbose(TestContext context) { String expected = "the_address:\nReply address: .*\nHeader header_name:\\[header_value\\]\nthe_message\n"; Pattern p = Pattern.compile(expected); assertBusTail(context, "bus-tail --verbose the_address", () -> { assertSend(context, "the_address", "the_message", new DeliveryOptions().setHeaders(new CaseInsensitiveHeaders()).addHeader("header_name", "header_value"), 50); }, s -> p.matcher(s).matches()); }
private HttpRequestImpl(HttpRequestImpl<T> other) { this.client = other.client; this.options = other.options; this.method = other.method; this.protocol = other.protocol; this.port = other.port; this.host = other.host; this.timeout = other.timeout; this.uri = other.uri; this.headers = other.headers != null ? new CaseInsensitiveHeaders().addAll(other.headers) : null; this.params = other.params != null ? new CaseInsensitiveHeaders().addAll(other.params) : null; this.codec = other.codec; this.followRedirects = other.followRedirects; }
/** * Instantiate a new Icon * * @param buffer buffer containing the image data for this icon. */ private Icon(Buffer buffer) { headers = new CaseInsensitiveHeaders(); body = buffer; headers.add(CONTENT_TYPE, "image/x-icon"); headers.add(CONTENT_LENGTH, Integer.toString(buffer.length())); headers.add(CACHE_CONTROL, "public, max-age=" + maxAgeSeconds); }
public void doWatch(String configCenter) throws URISyntaxException, UnsupportedEncodingException, InterruptedException { CountDownLatch waiter = new CountDownLatch(1); IpPort ipPort = NetUtils.parseIpPortFromURI(configCenter); String url = URIConst.REFRESH_ITEMS + "?dimensionsInfo=" + StringUtils.deleteWhitespace(URLEncoder.encode(serviceName, "UTF-8")); Map<String, String> headers = new HashMap<>(); headers.put("x-domain-name", tenantName); if (ConfigCenterConfig.INSTANCE.getToken() != null) { headers.put("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken()); } HttpClientWithContext vertxHttpClient = clientMgr.findThreadBindClientPool(); vertxHttpClient.runOnContext(client -> { Map<String, String> authHeaders = new HashMap<>(); authHeaderProviders.forEach(provider -> authHeaders.putAll(provider.getSignAuthHeaders( createSignRequest(null, configCenter + url, headers, null)))); client.websocket(refreshPort, ipPort.getHostOrIp(), url, new CaseInsensitiveHeaders().addAll(headers) .addAll(authHeaders), ws -> { ws.exceptionHandler(e -> { LOGGER.error("watch config read fail", e); stopHeartBeatThread(); isWatching = false; }); ws.closeHandler(v -> { LOGGER.warn("watching config connection is closed accidentally"); stopHeartBeatThread(); isWatching = false; }); ws.handler(action -> { LOGGER.info("watching config recieved {}", action); Map<String, Object> mAction = action.toJsonObject().getMap(); if ("CREATE".equals(mAction.get("action"))) { refreshConfig(configCenter); } else if ("MEMBER_CHANGE".equals(mAction.get("action"))) { refreshMembers(memberdis); } else { parseConfigUtils.refreshConfigItemsIncremental(mAction); } }); startHeartBeatThread(ws); isWatching = true; waiter.countDown(); }, e -> { LOGGER.error("watcher connect to config center {} failed: {}", serverUri, e.getMessage()); waiter.countDown(); }); }); waiter.await(); }
public static MultiMap getDefaultHeaders() { return new CaseInsensitiveHeaders().addAll(defaultHeaders()); }
@Override public MeshRequest<NodeResponse> updateNodeBinaryField(String projectName, String nodeUuid, String languageTag, String version, String fieldKey, Buffer fileData, String fileName, String contentType, ParameterProvider... parameters) { Vertx vertx = Mesh.vertx(); LocalActionContextImpl<NodeResponse> ac = createContext(NodeResponse.class); ac.setProject(projectName); MultiMap attributes = new CaseInsensitiveHeaders(); attributes.add("language", languageTag); attributes.add("version", version); Runnable task = () -> { File tmpFile = new File(System.getProperty("java.io.tmpdir"), UUIDUtil.randomUUID() + ".upload"); vertx.fileSystem().writeFileBlocking(tmpFile.getAbsolutePath(), fileData); ac.getFileUploads().add(new FileUpload() { @Override public String uploadedFileName() { return tmpFile.getAbsolutePath(); } @Override public long size() { return fileData.length(); } @Override public String name() { return fileName; } @Override public String fileName() { return fileName; } @Override public String contentType() { return contentType; } @Override public String contentTransferEncoding() { // TODO Auto-generated method stub return null; } @Override public String charSet() { // TODO Auto-generated method stub return null; } }); fieldAPIHandler.handleUpdateField(ac, nodeUuid, fieldKey, attributes); }; new Thread(task).start(); return new MeshLocalRequestImpl<>(ac.getFuture()); }
public RestClientOptions() { globalHeaders = new CaseInsensitiveHeaders(); }