List of usage examples for org.apache.http.entity ContentType TEXT_HTML
ContentType TEXT_HTML
To view the source code for org.apache.http.entity ContentType TEXT_HTML.
Click Source Link
From source file:com.epam.reportportal.service.ReportPortalErrorHandlerTest.java
@Test public void hasError() throws Exception { // given:/*from w w w. j a va2 s.c o m*/ LinkedListMultimap<String, String> validHeaders = LinkedListMultimap.create(); validHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); LinkedListMultimap<String, String> validHeaders2 = LinkedListMultimap.create(); validHeaders2.put(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8"); LinkedListMultimap<String, String> invalidHeaders1 = LinkedListMultimap.create(); invalidHeaders1.put(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_HTML.getMimeType()); LinkedListMultimap<String, String> invalidHeaders2 = LinkedListMultimap.create(); invalidHeaders2.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM.getMimeType()); // then: assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(500, validHeaders))); assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(404, validHeaders))); assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(200, invalidHeaders1))); assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(200, invalidHeaders2))); // and: assertFalse(reportPortalErrorHandler.hasError(createFakeResponse(200, validHeaders))); assertFalse(reportPortalErrorHandler.hasError(createFakeResponse(200, validHeaders2))); }
From source file:onl.area51.httpd.action.Actions.java
/** * Send a redirect/*from w w w. j av a 2 s . c o m*/ * * @param req Request * @param code HttpStatus, one of * {@link HttpStatus#SC_MOVED_PERMANENTLY}, {@link HttpStatus#SC_MOVED_TEMPORARILY}, {@link HttpStatus#SC_SEE_OTHER}, {@link HttpStatus#SC_USE_PROXY} * or {@link HttpStatus#SC_TEMPORARY_REDIRECT} * @param uri */ static void sendRedirect(Request req, int code, String uri) { HttpResponse response = req.getHttpResponse(); response.setStatusCode(code); response.addHeader("Location", uri); response.setEntity(new StringEntity( "<html><head><title>Moved</title></head><body><h1>Moved</h1><p>This page has moved to <a href=\"" + uri + "\">" + uri + "</a>.</p></body></html>", ContentType.TEXT_HTML)); }
From source file:io.undertow.servlet.test.security.basic.ServletCertAndDigestAuthTestCase.java
@Test public void testMultipartRequest() throws Exception { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 2000; i++) { sb.append("0123456789"); }// w w w . j a v a2 s . c om try (TestHttpClient client = new TestHttpClient()) { // create POST request MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("part1", new ByteArrayBody(sb.toString().getBytes(), "file.txt")); builder.addPart("part2", new StringBody("0123456789", ContentType.TEXT_HTML)); HttpEntity entity = builder.build(); client.setSSLContext(clientSSLContext); String url = DefaultServer.getDefaultServerSSLAddress() + BASE_PATH + "multipart"; HttpPost post = new HttpPost(url); post.setEntity(entity); post.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64 .encodeString(("user1" + ":" + "password1").getBytes(StandardCharsets.UTF_8), false)); HttpResponse result = client.execute(post); assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); } }
From source file:ste.web.http.velocity.VelocityHandler.java
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { String view = (String) context.getAttribute(ATTR_VIEW); if (view == null) { return;// w w w.ja v a2 s.co m } view = getViewPath(request.getRequestLine().getUri(), view); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Writer out = new OutputStreamWriter(baos); try { Template t = engine.getTemplate(view); t.merge(buildContext(request, (HttpSessionContext) context), out); out.flush(); } catch (ResourceNotFoundException e) { response.setStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "View " + view + " not found."); return; } catch (ParseErrorException e) { throw new HttpException("Parse error evaluating " + view + ": " + e, e); } catch (MethodInvocationException e) { throw new HttpException("Method invocation error evaluating " + view + ": " + e, e); } BasicHttpEntity body = (BasicHttpEntity) response.getEntity(); body.setContentLength(baos.size()); body.setContent(new ByteArrayInputStream(baos.toByteArray())); if ((body.getContentType() == null) || StringUtils.isBlank(body.getContentType().getValue())) { body.setContentType(ContentType.TEXT_HTML.getMimeType()); } }
From source file:onl.area51.httpd.action.Response.java
static Response create(Request request) { class State { private final String tag; private final boolean disableMini; private boolean body; public State(String tag, boolean disableMini) { this.tag = tag; this.disableMini = disableMini; }/*from w w w .ja v a2s .c om*/ @Override public String toString() { return tag; } } CharArrayWriter writer = new CharArrayWriter(); return new Response() { private ContentType contentType = ContentType.TEXT_HTML; private Deque<State> deque = new ArrayDeque<>(); private State state; @Override public Response exec(Action a) throws IOException, HttpException { if (a != null) { // Ensure we have finished the current tag startBody(); // Now preserve the stack & start a new one. // This means one action cannot affect the state of this one final Deque<State> orig = deque; deque = new ArrayDeque<>(); try { a.apply(request); } finally { endAll(); deque = orig; } } return this; } @Override public Response setContentType(ContentType contentType) { this.contentType = contentType; return this; } @Override public HttpEntity getEntity() throws IOException { while (!deque.isEmpty()) { end(); } return new StringEntity(writer.toString(), contentType); } private void startBody() { if (state != null && !state.body) { state.body = true; writer.append('>'); } } private void tagOnly() { if (state == null || state.body) { throw new IllegalStateException("Not in tag"); } } @Override public Response write(CharSequence seq, int s, int e) throws IOException { startBody(); writer.append(seq, s, e); return this; } @Override public Response write(char[] v, int s, int l) throws IOException { startBody(); writer.write(v, s, l); return this; } @Override public Response write(char v) throws IOException { startBody(); writer.write(v); return this; } @Override public Response begin(String t, boolean disableMini) throws IOException { startBody(); if (state != null) { deque.addLast(state); } state = new State(t, disableMini); writer.append('<'); writer.write(state.tag); return this; } @Override public Response end() throws IOException { if (state == null) { throw new IllegalStateException("end() called outside of tag"); } // elements like script mustn't be minified, i.e. <script/> is invalid must be <script></script> if (state.disableMini) { startBody(); } if (state.body) { writer.append('<'); writer.append('/'); writer.append(state.tag); writer.append('>'); } else { writer.append('/'); writer.append('>'); } state = deque.pollLast(); return this; } @Override public Response endAll() throws IOException { while (!deque.isEmpty()) { end(); } return this; } @Override public Response attr(String n, CharSequence seq) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.append(seq); writer.append('"'); return this; } @Override public Response attr(String n, CharSequence seq, int s, int e) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.append(seq, s, e); writer.append('"'); return this; } @Override public Response attr(String n, char[] v) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.write(v); writer.append('"'); return this; } @Override public Response attr(String n, char[] v, int s, int l) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.write(v, s, l); writer.append('"'); return this; } }; }
From source file:org.esigate.vars.DriverEsiWhenTest.java
@SuppressWarnings("static-method") @Test//from w w w. ja v a 2 s .c o m public void testEsiWhenCase1() throws IOException, HttpErrorPage { // Configuration Properties properties = new Properties(); properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/"); // Test case IncomingRequest request = TestUtils .createRequest("http://test.mydomain.fr/foobar/?test=esigate&test2=esigate2") .addHeader("Referer", "http://www.esigate.org") .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " + "AppleWebKit/536.30.1 (KHTML, like Gecko) " + "Version/6.0.5 Safari/536.30.1") .addHeader("Accept-Language", "da, en-gb;q=0.8, en;q=0.7") .addCookie(new BasicClientCookie("test-cookie", "test-cookie-value")) .addCookie(new BasicClientCookie("test-cookie2", "test-cookie-value2")).build(); final StringBuilder expected = new StringBuilder(); addExpression(expected, "!(1==1)", false); addExpression(expected, "!(a==a)", false); addExpression(expected, "!(a==b)", true); addExpression(expected, "1==1", true); addExpression(expected, "1==01", true); addExpression(expected, "10==01", false); addExpression(expected, "a==a", true); addExpression(expected, "a==b", false); addExpression(expected, "2>=1", true); addExpression(expected, "1>=1", true); addExpression(expected, "b>=a", true); addExpression(expected, "a>=b", false); addExpression(expected, "2>1", true); addExpression(expected, "b>a", true); addExpression(expected, "1>2", false); addExpression(expected, "a>b", false); addExpression(expected, "2<1", false); addExpression(expected, "b<a", false); addExpression(expected, "1<2", true); addExpression(expected, "2<=1", false); addExpression(expected, "1<=2", true); addExpression(expected, "$(HTTP_COOKIE{test-cookie})==test-cookie-value", true); addExpression(expected, "$(HTTP_COOKIE{'test-cookie'})==test-cookie-value", true); addExpression(expected, "$(HTTP_USER_AGENT{os})==MAC", true); addExpression(expected, "$(HTTP_USER_AGENT{os})=='MAC'", true); addExpression(expected, "$(HTTP_COOKIE{test-cookie})=='test-cookie-value'", true); addExpression(expected, "$(HTTP_COOKIE{test-cookie})!='test-cookie-not-this-value'", true); addExpression(expected, "$(HTTP_COOKIE{'test-cookie'})=='test-cookie-value'", true); addExpression(expected, "$(HTTP_COOKIE{'test-cookie'})!='test-cookie-not-this-value'", true); addExpression(expected, "$exists($(HTTP_COOKIE{test-cookie}))", true); addExpression(expected, "$exists($(HTTP_COOKIE{'test-cookie'}))", true); addExpression(expected, "$exists($(HTTP_COOKIE{fake-cookie}))", false); addExpression(expected, "$exists($(HTTP_COOKIE{'fake-cookie'}))", false); addExpression(expected, "$(HTTP_REFERER)==http://www.esigate.org", true); addExpression(expected, "$(HTTP_HOST)=='test.mydomain.fr'", true); addExpression(expected, "$(HTTP_HOST)==test.mydomain.fr", true); // Setup remote server (provider) response. IResponseHandler mockExecutor = new IResponseHandler() { @Override public HttpResponse execute(HttpRequest request) { StringBuilder content = new StringBuilder(); String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>"); for (String expr : expectedArray) { addExpression(content, expr.substring(0, expr.indexOf(": "))); } LOG.info("Backend response:\n" + content.toString()); return TestUtils.createHttpResponse() .entity(new StringEntity(content.toString(), ContentType.TEXT_HTML)).build(); } }; // Build driver and request. Driver driver = TestUtils.createMockDriver(properties, mockExecutor); CloseableHttpResponse response = TestUtils.driverProxy(driver, request, new EsiRenderer()); String entityContent = EntityUtils.toString(response.getEntity()); LOG.info("Esigate response: \n" + entityContent); String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>"); String[] resultArray = StringUtils.splitByWholeSeparator(entityContent, "<p>"); for (int i = 0; i < expectedArray.length; i++) { String varName = expectedArray[i].substring(0, expectedArray[i].indexOf(":")); Assert.assertEquals(varName, expectedArray[i], resultArray[i]); LOG.info("Success with variable {}", varName); } }
From source file:org.esigate.vars.DriverEsiVariablesTest.java
/** * 0000246: ESI variables are not available / replaced. http://www.esigate.org/mantisbt/view.php?id=246 * /* w ww . j a v a2 s .c o m*/ * @throws IOException * @throws HttpErrorPage */ @SuppressWarnings("static-method") @Test public void testEsiVariablesCase1() throws IOException, HttpErrorPage { // Reset Driverfactory (used for default driver with $(PROVIDER)) Properties factoryProperties = new Properties(); factoryProperties.put("tested." + Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/"); DriverFactory.configure(factoryProperties); // Configuration Properties properties = new Properties(); properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/"); // Test case IncomingRequest request = TestUtils .createRequest("http://test.mydomain.fr/foobar/?test=esigate&test2=esigate2") .addHeader("Referer", "http://www.esigate.org") .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 " + "(KHTML, like Gecko) Version/6.0.5 Safari/536.30.1") .addHeader("Accept-Language", "da, en-gb;q=0.8, en;q=0.7") .addCookie(new BasicClientCookie("test-cookie", "test-cookie-value")) .addCookie(new BasicClientCookie("test-cookie2", "test-cookie-value2")).build(); final StringBuilder expected = new StringBuilder(); addVariable(expected, "HTTP_ACCEPT_LANGUAGE", "da, en-gb;q=0.8, en;q=0.7"); addVariable(expected, "HTTP_ACCEPT_LANGUAGE{en}", "true"); addVariable(expected, "HTTP_ACCEPT_LANGUAGE{fr}", "false"); addVariable(expected, "QUERY_STRING{test}", "esigate"); addVariable(expected, "QUERY_STRING", "test=esigate&test2=esigate2"); addVariable(expected, "HTTP_REFERER", "http://www.esigate.org"); addVariable(expected, "PROVIDER{tested}", "http://localhost.mydomain.fr/"); addVariable(expected, "PROVIDER{missing}", ""); addVariable(expected, "PROVIDER", ""); addVariable(expected, "HTTP_HOST", "test.mydomain.fr"); addVariable(expected, "HTTP_USER_AGENT", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/536.30.1 (KHTML, like Gecko)" + " Version/6.0.5 Safari/536.30.1"); addVariable(expected, "HTTP_USER_AGENT{browser}", "MOZILLA"); addVariable(expected, "HTTP_USER_AGENT{os}", "MAC"); addVariable(expected, "HTTP_COOKIE{test-cookie}", "test-cookie-value"); addVariable(expected, "HTTP_COOKIE{'test-cookie'}", "test-cookie-value"); addVariable(expected, "HTTP_COOKIE{missing}", ""); addVariable(expected, "QUERY_STRING{missing}", ""); addVariable(expected, "HTTP_USER_AGENT{version}", "5.0"); addVariable(expected, "HTTP_HEADER{Accept-Language}", "da, en-gb;q=0.8, en;q=0.7"); addVariable(expected, "HTTP_COOKIE", "test-cookie=test-cookie-value; test-cookie2=test-cookie-value2"); addVariable(expected, "QUERY_STRING{missing}|default-value", "default-value"); addVariable(expected, "QUERY_STRING{missing}|'default value'", "default value"); // Setup remote server (provider) response. IResponseHandler mockExecutor = new IResponseHandler() { @Override public HttpResponse execute(HttpRequest request) { StringBuilder content = new StringBuilder(); content.append("<esi:vars>"); String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>"); for (String expr : expectedArray) { addVariable(content, expr.substring(0, expr.indexOf(":"))); } content.append("</esi:vars>"); LOG.info("Backend response:\n" + content.toString()); return TestUtils.createHttpResponse() .entity(new StringEntity(content.toString(), ContentType.TEXT_HTML)).build(); } }; // Build driver and request. Driver driver = TestUtils.createMockDriver(properties, mockExecutor); CloseableHttpResponse response = TestUtils.driverProxy(driver, request, new EsiRenderer()); String entityContent = EntityUtils.toString(response.getEntity()); LOG.info("Esigate response: \n" + entityContent); String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>"); String[] resultArray = StringUtils.splitByWholeSeparator(entityContent, "<p>"); for (int i = 0; i < expectedArray.length; i++) { String varName = expectedArray[i].substring(0, expectedArray[i].indexOf(":")); Assert.assertEquals(varName, expectedArray[i], resultArray[i]); LOG.info("Success with variable {}", varName); } }
From source file:tech.sirwellington.alchemy.http.HttpVerbImplTest.java
@Test public void testExecuteWhenContentTypeInvalid() throws IOException { List<ContentType> invalidContentTypes = Arrays.asList(ContentType.APPLICATION_ATOM_XML, ContentType.TEXT_HTML, ContentType.TEXT_XML, ContentType.APPLICATION_XML, ContentType.APPLICATION_OCTET_STREAM, ContentType.create(one(alphabeticString()))); ContentType invalidContentType = Lists.oneOf(invalidContentTypes); String string = one(alphanumericString()); entity = new StringEntity(string, invalidContentType); when(apacheResponse.getEntity()).thenReturn(entity); HttpResponse result = instance.execute(apacheClient, request); assertThat(result.bodyAsString(), is(string)); verify(apacheResponse).close();/* w w w . j a va 2s.c o m*/ }
From source file:ste.web.http.velocity.BugFreeVelocityHandler.java
@Test public void setContentTypeIfNotSetAlready() throws Exception { //// w ww . j a v a2 s . c o m // content-type not set yet // context.setAttribute(ATTR_VIEW, TEST_VIEW1); handler.handle(request, response, context); then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); then(response.getEntity().getContentType().getValue()).isEqualTo(mime(ContentType.TEXT_HTML)); // // content-type already set // ((BasicHttpEntity) response.getEntity()).setContentType(mime(ContentType.APPLICATION_OCTET_STREAM)); handler.handle(request, response, context); then(response.getStatusLine().getStatusCode()).isEqualTo(HttpStatus.SC_OK); then(response.getEntity().getContentType().getValue()) .isEqualTo(mime(ContentType.APPLICATION_OCTET_STREAM)); }
From source file:org.esigate.vars.DriverEsiVariablesTest.java
/** * 0000246: ESI variables are not available / replaced. http://www.esigate.org/mantisbt/view.php?id=246 * /* w ww .jav a 2 s. co m*/ * @throws IOException * @throws HttpErrorPage */ @SuppressWarnings("static-method") @Test public void testEsiVariablesCase2() throws IOException, HttpErrorPage { // Configuration Properties properties = new Properties(); properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost.mydomain.fr/"); // Test case IncomingRequest request = TestUtils.createRequest("http://test.mydomain.fr/foobar/") .addHeader("User-Agent", "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)").build(); final StringBuilder expected = new StringBuilder(); addVariable(expected, "HTTP_ACCEPT_LANGUAGE{en}", "false"); addVariable(expected, "HTTP_ACCEPT_LANGUAGE{fr}", "false"); addVariable(expected, "HTTP_HOST", "test.mydomain.fr"); addVariable(expected, "HTTP_USER_AGENT", "Mozilla/5.0 (Windows; U; MSIE 9.0; WIndows NT 9.0; en-US)"); addVariable(expected, "HTTP_USER_AGENT{browser}", "MSIE"); addVariable(expected, "HTTP_USER_AGENT{os}", "WIN"); addVariable(expected, "HTTP_ACCEPT_LANGUAGE", ""); addVariable(expected, "QUERY_STRING{test}", ""); addVariable(expected, "QUERY_STRING", ""); addVariable(expected, "HTTP_REFERER", ""); addVariable(expected, "HTTP_COOKIE{test-cookie}", ""); addVariable(expected, "HTTP_COOKIE", ""); addVariable(expected, "QUERY_STRING{missing}", ""); addVariable(expected, "HTTP_USER_AGENT{version}", "5.0"); // Setup remote server (provider) response. IResponseHandler mockExecutor = new IResponseHandler() { @Override public HttpResponse execute(HttpRequest request) { StringBuilder content = new StringBuilder(); content.append("<esi:vars>"); String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>"); for (String expr : expectedArray) { addVariable(content, expr.substring(0, expr.indexOf(": "))); } content.append("</esi:vars>"); LOG.info("Backend response:\n" + content.toString()); return TestUtils.createHttpResponse() .entity(new StringEntity(content.toString(), ContentType.TEXT_HTML)).build(); } }; // Build driver and request. Driver driver = TestUtils.createMockDriver(properties, mockExecutor); CloseableHttpResponse response = TestUtils.driverProxy(driver, request, new EsiRenderer()); String entityContent = EntityUtils.toString(response.getEntity()); LOG.info("Esigate response: \n" + entityContent); String[] expectedArray = StringUtils.splitByWholeSeparator(expected.toString(), "<p>"); String[] resultArray = StringUtils.splitByWholeSeparator(entityContent, "<p>"); for (int i = 0; i < expectedArray.length; i++) { String varName = expectedArray[i].substring(0, expectedArray[i].indexOf(":")); Assert.assertEquals(varName, expectedArray[i], resultArray[i]); LOG.info("Success with variable {}", varName); } }