public static final HttpResponse make200Response(Date date, String cacheControl) { HttpResponse response = HttpTestUtils.make200Response(); response.setHeader("Date", DateUtils.formatDate(date)); response.setHeader("Cache-Control", cacheControl); response.setHeader("Etag", "\"etag\""); return response; }
public static HttpResponse make200Response() { HttpResponse out = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); out.setHeader("Date", DateUtils.formatDate(new Date())); out.setHeader("Server", "MockOrigin/1.0"); out.setHeader("Content-Length", "128"); out.setEntity(makeBody(128)); return out; }
@Test public void entryWithMalformedDateIsStillUpdated() throws Exception { Header[] headers = {new BasicHeader("ETag", "\"old\""), new BasicHeader("Date", "bad-date")}; entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo, headers); response.setHeader("ETag", "\"new\""); response.setHeader("Date", formatDate(twoSecondsAgo)); HttpCacheEntry updated = impl.updateCacheEntry(null, entry, twoSecondsAgo, oneSecondAgo, response); assertEquals("\"new\"", updated.getFirstHeader("ETag").getValue()); }
@Test public void oldHeadersRetainedIfResponseOlderThanEntry() throws Exception { Header[] headers = { new BasicHeader("Date", formatDate(oneSecondAgo)), new BasicHeader("ETag", "\"new-etag\"") }; entry = HttpTestUtils.makeCacheEntry(twoSecondsAgo, now, headers); response.setHeader("Date", formatDate(tenSecondsAgo)); response.setHeader("ETag", "\"old-etag\""); HttpCacheEntry result = impl.updateCacheEntry("A", entry, new Date(), new Date(), response); assertEquals(2, result.getAllHeaders().length); headersContain(result.getAllHeaders(), "Date", formatDate(oneSecondAgo)); headersContain(result.getAllHeaders(), "ETag", "\"new-etag\""); }
@Test public void entry1xxWarningsAreRemovedOnUpdate() throws Exception { Header[] headers = { new BasicHeader("Warning", "110 fred \"Response is stale\""), new BasicHeader("ETag", "\"old\""), new BasicHeader("Date", formatDate(eightSecondsAgo)) }; entry = HttpTestUtils.makeCacheEntry(tenSecondsAgo, eightSecondsAgo, headers); response.setHeader("ETag", "\"new\""); response.setHeader("Date", formatDate(twoSecondsAgo)); HttpCacheEntry updated = impl.updateCacheEntry(null, entry, twoSecondsAgo, oneSecondAgo, response); assertEquals(0, updated.getHeaders("Warning").length); }
@Override public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { AbstractHttpEntity entity; String uri = request.getRequestLine().getUri(); int i = uri.indexOf(LIBRARY_URL); String sha1 = uri.substring(i + LIBRARY_URL.length()); if (sha1.indexOf("?") != -1) { sha1 = sha1.substring(0, sha1.indexOf("?")); } System.out.println("sha1:" + sha1); URN urn = new URNImpl(com.limegroup.gnutella.URN.createSHA1Urn(sha1)); if (libraryManager.getLibraryManagedList().contains(urn)) { FileDesc fileDesc = libraryManager.getLibraryManagedList().getFileDescsByURN(urn).get(0); entity = new NFileEntity(fileDesc.getFile(), "application/binary"); entity.setContentType("application/binary"); response.setHeader( "Content-disposition", "attachment; filename=\"" + fileDesc.getFileName() + "\";"); } else { entity = new NStringEntity("File not found: " + sha1); entity.setContentType("text/plain"); } response.setEntity(entity); }
@Override public void handler(HttpRequest request, HttpResponse response, HttpContext context) throws UnsupportedEncodingException, JSONException { String url = parseGetUrl(request); JSONObject result = new JSONObject(); String[] urlpart = url.split("/"); String classNameString = urlpart[1].toLowerCase(); String methodNameString = urlpart[2].toLowerCase(); Map<String, String> params = parseGetParamters(request); // 获取粘贴板内容 if (methodNameString.equals("get")) { String data = Clipboard.get(mContext); result.put("data", data); } // 设置粘贴板内容 if (methodNameString.equals("set")) { String text = params.get("text"); Clipboard.set(mContext, text); } result.put("code", "10000"); result.put("msg", "success"); StringEntity entity = new StringEntity(wrap_jsonp(result.toString(), params), Constants.ENCODING); response.setStatusCode(HttpStatus.SC_OK); response.setHeader("Content-Type", "application/javascript"); response.setEntity(entity); }
public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null."); } int status = response.getStatusLine().getStatusCode(); if ((status >= HttpStatus.SC_OK) && !response.containsHeader(HTTP.DATE_HEADER)) { String httpdate = DATE_GENERATOR.getCurrentDate(); response.setHeader(HTTP.DATE_HEADER, httpdate); } }
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { httpResponse.setHeader( "location", "http4://" + localServer.getInetAddress().getHostName() + ":" + localServer.getLocalPort() + "/someplaceelse"); httpResponse.setStatusCode(code); }
public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String creds = (String) context.getAttribute("creds"); if (creds == null || !creds.equals("test:test")) { response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); } else { response.setStatusCode(HttpStatus.SC_OK); StringEntity entity = new StringEntity("success", Consts.ASCII); response.setEntity(entity); response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); } }
private void prepareErrorResponse(final HttpResponse response, final PlatformException e) { final int errorCode = (e.getHttpStatus() != 0 ? e.getHttpStatus() : HttpStatus.SC_INTERNAL_SERVER_ERROR); final String errorMessage = e.getMessage(); ErrorMessage message = new ErrorMessage(errorCode, errorMessage); try { ByteArrayOutputStream baos = errorParser.writeInternal(message); response.setStatusCode(errorCode); response.setEntity(new ByteArrayEntity(baos.toByteArray(), ErrorParser.DEFAULT_CONTENT_TYPE)); response.setHeader( HttpHeader.CONTENT_TYPE.toString(), ErrorParser.DEFAULT_CONTENT_TYPE.toString()); } catch (JsonConverterException jce) { response.setStatusCode(errorCode); response.setEntity(new ByteArrayEntity(jce.getMessage().getBytes())); } }
@Test public void testResponseCopiesAllOriginalHeaders() throws Exception { byte[] buf = new byte[] {1, 2, 3}; HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); response.setEntity(new ByteArrayEntity(buf)); response.setHeader("Content-Encoding", "gzip"); impl = new SizeLimitedResponseReader(new HeapResourceFactory(), MAX_SIZE, request, response); impl.readResponse(); boolean tooLarge = impl.isLimitReached(); HttpResponse reconstructed = impl.getReconstructedResponse(); byte[] result = EntityUtils.toByteArray(reconstructed.getEntity()); Assert.assertFalse(tooLarge); Assert.assertArrayEquals(buf, result); Assert.assertEquals("gzip", reconstructed.getFirstHeader("Content-Encoding").getValue()); }
protected void setHeader(HttpResponse resp, String name, XMLGregorianCalendar value) { if (value != null && !resp.containsHeader(name)) { Date time = value.toGregorianCalendar().getTime(); resp.setHeader(name, dateformat.format(time)); } }
protected void setHeader(HttpResponse resp, String name, String value) { if (value != null && !resp.containsHeader(name)) { resp.setHeader(name, value); } }
private void prepareResponse(final HttpResponse httpResponse, final String contentType) { httpResponse.setStatusCode(HttpStatus.SC_OK); httpResponse.setHeader(HttpHeader.CONTENT_TYPE.toString(), contentType); }
/** * Send the passed in response message, asynchronously * * @param msgContext the message context to be sent * @throws AxisFault on error */ private void sendAsyncResponse(MessageContext msgContext) throws AxisFault { int contentLength = extractContentLength(msgContext); // remove unwanted HTTP headers (if any from the current message) removeUnwantedHeaders(msgContext); Map transportHeaders = (Map) msgContext.getProperty(MessageContext.TRANSPORT_HEADERS); ServerWorker worker = (ServerWorker) msgContext.getProperty(Constants.OUT_TRANSPORT_INFO); HttpResponse response = worker.getResponse(); OMOutputFormat format = NhttpUtil.getOMOutputFormat(msgContext); MessageFormatter messageFormatter = MessageFormatterDecoratorFactory.createMessageFormatterDecorator(msgContext); Boolean noEntityBody = (Boolean) msgContext.getProperty(NhttpConstants.NO_ENTITY_BODY); if (noEntityBody == null || Boolean.FALSE == noEntityBody) { response.setHeader( HTTP.CONTENT_TYPE, messageFormatter.getContentType(msgContext, format, msgContext.getSoapAction())); } else if (Boolean.TRUE == noEntityBody) { ((BasicHttpEntity) response.getEntity()).setChunked(false); ((BasicHttpEntity) response.getEntity()).setContentLength(0); // Since HTTP HEAD request doesn't contain message body content length of the is set to be 0. // To handle // content length 0 while serving head method, content length of the backend response is set // as the content // as synapse cannot calculate content length without providing message body. if (transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD) != null && NhttpConstants.HTTP_HEAD.equals( transportHeaders.get(NhttpConstants.HTTP_REQUEST_METHOD)) && transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN) != null) { ((BasicHttpEntity) response.getEntity()) .setContentLength( Long.parseLong( String.valueOf(transportHeaders.get(NhttpConstants.ORIGINAL_CONTENT_LEN)))); transportHeaders.remove(NhttpConstants.ORIGINAL_CONTENT_LEN); transportHeaders.remove(NhttpConstants.HTTP_REQUEST_METHOD); } } response.setStatusCode(determineHttpStatusCode(msgContext, response)); // Override the Standard Reason Phrase if (msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE) != null && !msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).equals("")) { response.setReasonPhrase( msgContext.getProperty(NhttpConstants.HTTP_REASON_PHRASE).toString()); } // set any transport headers if (transportHeaders != null && !transportHeaders.values().isEmpty()) { Iterator iter = transportHeaders.keySet().iterator(); while (iter.hasNext()) { Object header = iter.next(); Object value = transportHeaders.get(header); if (value != null && header instanceof String && value instanceof String) { response.addHeader((String) header, (String) value); String excessProp = NhttpConstants.EXCESS_TRANSPORT_HEADERS; Map map = (Map) msgContext.getProperty(excessProp); if (map != null && map.get(header) != null) { log.debug( "Number of excess values for " + header + " header is : " + ((Collection) (map.get(header))).size()); for (Iterator iterator = map.keySet().iterator(); iterator.hasNext(); ) { String key = (String) iterator.next(); for (String excessVal : (Collection<String>) map.get(key)) { if (header.equals(key)) { response.addHeader((String) header, (String) excessVal); } } } } } } } boolean forceContentLength = msgContext.isPropertyTrue(NhttpConstants.FORCE_HTTP_CONTENT_LENGTH); boolean forceContentLengthCopy = msgContext.isPropertyTrue(NhttpConstants.COPY_CONTENT_LENGTH_FROM_INCOMING); BasicHttpEntity entity = (BasicHttpEntity) response.getEntity(); MetricsCollector lstMetrics = worker.getServiceHandler().getMetrics(); try { if (forceContentLength) { entity.setChunked(false); if (forceContentLengthCopy && contentLength > 0) { entity.setContentLength(contentLength); } else { setStreamAsTempData(entity, messageFormatter, msgContext, format); } } worker.getServiceHandler().commitResponse(worker.getConn(), response); lstMetrics.reportResponseCode(response.getStatusLine().getStatusCode()); OutputStream out = worker.getOutputStream(); /* * if this is a dummy message to handle http 202 case with non-blocking IO * write an empty byte array as body */ if (msgContext.isPropertyTrue(NhttpConstants.SC_ACCEPTED) || Boolean.TRUE == noEntityBody) { out.write(new byte[0]); } else { if (forceContentLength) { if (forceContentLengthCopy && contentLength > 0) { messageFormatter.writeTo(msgContext, format, out, false); } else { writeMessageFromTempData(out, msgContext); } } else { messageFormatter.writeTo(msgContext, format, out, false); } } out.close(); if (lstMetrics != null) { lstMetrics.incrementMessagesSent(); } } catch (ProtocolException e) { log.error(e + " (Synapse may be trying to send an exact response more than once )"); } catch (HttpException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } handleException( "Unexpected HTTP protocol error sending response to : " + worker.getRemoteAddress(), e); } catch (ConnectionClosedException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } log.warn("Connection closed by client : " + worker.getRemoteAddress()); } catch (IllegalStateException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } log.warn("Connection closed by client : " + worker.getRemoteAddress()); } catch (IOException e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } handleException("IO Error sending response message to : " + worker.getRemoteAddress(), e); } catch (Exception e) { if (lstMetrics != null) { lstMetrics.incrementFaultsSending(); } handleException( "General Error sending response message to : " + worker.getRemoteAddress(), e); } InputStream is = worker.getIs(); if (is != null) { try { is.close(); } catch (IOException ignore) { } } }