List of usage examples for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED
int SC_NOT_MODIFIED
To view the source code for javax.servlet.http HttpServletResponse SC_NOT_MODIFIED.
Click Source Link
From source file:de.digitalcollections.streaming.euphoria.controller.StreamingController.java
/** * Create response for the request./*from w ww. ja v a 2s .c o m*/ * * @param id The id of requested content. * @param extension The (target) file extension/format of requested content. * @param request The request to be responded to. * @param response The response to the request. * @param head "true" if response body should be written (GET) or "false" if not (HEAD). * @throws IOException If something fails at I/O level. */ private void respond(String id, String extension, HttpServletRequest request, HttpServletResponse response, boolean head) throws IOException { logRequestHeaders(request); response.reset(); // try to get access to resource Resource resource; try { resource = getResource(id, extension); } catch (ResourceIOException ex) { LOGGER.warn("*** Response {}: Error referencing streaming resource with id {} and extension {}", HttpServletResponse.SC_NOT_FOUND, id, extension); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // get resource metadata ResourceInfo resourceInfo = new ResourceInfo(id, resource); if (resourceInfo.length <= 0) { LOGGER.warn("*** Response {}: Error streaming resource with id {} and extension {}: not found/no size", HttpServletResponse.SC_NOT_FOUND, id, extension); response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (preconditionFailed(request, resourceInfo)) { LOGGER.warn( "*** Response {}: Precondition If-Match/If-Unmodified-Since failed for resource with id {} and extension {}.", HttpServletResponse.SC_PRECONDITION_FAILED, id, extension); response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } setCacheHeaders(response, resourceInfo); if (notModified(request, resourceInfo)) { LOGGER.debug("*** Response {}: 'Not modified'-response for resource with id {} and extension {}.", HttpServletResponse.SC_NOT_MODIFIED, id, extension); response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } List<Range> ranges = getRanges(request, resourceInfo); if (ranges == null) { response.setHeader("Content-Range", "bytes */" + resourceInfo.length); LOGGER.warn("Response {}: Header Range for resource with id {} and extension {} not satisfiable", HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE, id, extension); response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } if (!ranges.isEmpty()) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); } else { ranges.add(new Range(0, resourceInfo.length - 1)); // Full content. } String contentType = setContentHeaders(request, response, resourceInfo, ranges); boolean acceptsGzip = false; // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } if (head) { return; } writeContent(response, resource, resourceInfo, ranges, contentType, acceptsGzip); LOGGER.debug("*** RESPONSE FINISHED ***"); }
From source file:io.fabric8.gateway.servlet.ProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails/*from w w w .j a v a2 s . co m*/ * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } LOG.trace("Response has data? {}", !noData); if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:com.google.gwt.dev.shell.GWTShellServlet.java
/** * Fetch a file and return it as the HTTP response, setting the cache-related * headers according to the name of the file (see * {@link #getCacheTime(String)}). This function honors If-Modified-Since to * minimize the impact of limiting caching of files for development. * // ww w . j a va 2 s . co m * @param request the HTTP request * @param response the HTTP response * @param logger a TreeLogger to use for debug output * @param partialPath the path within the module * @param moduleName the name of the module * @throws IOException */ @SuppressWarnings("deprecation") private void doGetPublicFile(HttpServletRequest request, HttpServletResponse response, TreeLogger logger, String partialPath, String moduleName) throws IOException { // Create a logger branch for this request. logger = logger.branch(TreeLogger.TRACE, "The development shell servlet received a request for '" + partialPath + "' in module '" + moduleName + ".gwt.xml' ", null); // Handle auto-generation of resources. if (shouldAutoGenerateResources()) { if (autoGenerateResources(request, response, logger, partialPath, moduleName)) { return; } } URL foundResource = null; try { // Look for the requested file on the public path. // ModuleDef moduleDef = getModuleDef(logger, moduleName); if (shouldAutoGenerateResources()) { Resource publicResource = moduleDef.findPublicFile(partialPath); if (publicResource != null) { foundResource = publicResource.getURL(); } if (foundResource == null) { // Look for public generated files File shellDir = getShellWorkDirs().getShellPublicGenDir(moduleDef); File requestedFile = new File(shellDir, partialPath); if (requestedFile.exists()) { try { foundResource = requestedFile.toURI().toURL(); } catch (MalformedURLException e) { // ignore since it was speculative anyway } } } } /* * If the user is coming from compiled web-mode, check the linker output * directory for the real bootstrap file. */ if (foundResource == null) { File moduleDir = getShellWorkDirs().getCompilerOutputDir(moduleDef); File requestedFile = new File(moduleDir, partialPath); if (requestedFile.exists()) { try { foundResource = requestedFile.toURI().toURL(); } catch (MalformedURLException e) { // ignore since it was speculative anyway } } } if (foundResource == null) { String msg; if ("gwt.js".equals(partialPath)) { msg = "Loading the old 'gwt.js' bootstrap script is no longer supported; please load '" + moduleName + ".nocache.js' directly"; } else { msg = "Resource not found: " + partialPath + "; " + "(could a file be missing from the public path or a <servlet> " + "tag misconfigured in module " + moduleName + ".gwt.xml ?)"; } logger.log(TreeLogger.WARN, msg, null); throw new UnableToCompleteException(); } } catch (UnableToCompleteException e) { sendErrorResponse(response, HttpServletResponse.SC_NOT_FOUND, "Cannot find resource '" + partialPath + "' in the public path of module '" + moduleName + "'"); return; } // Get the MIME type. String path = foundResource.toExternalForm(); String mimeType = null; try { mimeType = getServletContext().getMimeType(path); } catch (UnsupportedOperationException e) { // Certain minimalist servlet containers throw this. // Fall through to guess the type. } if (mimeType == null) { mimeType = guessMimeType(path); if (logger.isLoggable(TreeLogger.TRACE)) { logger.log(TreeLogger.TRACE, "Guessed MIME type '" + mimeType + "'", null); } } maybeIssueXhtmlWarning(logger, mimeType, partialPath); long cacheSeconds = getCacheTime(path); InputStream is = null; try { // Check for up-to-datedness. URLConnection conn = foundResource.openConnection(); long lastModified = conn.getLastModified(); if (isNotModified(request, lastModified)) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); setResponseCacheHeaders(response, cacheSeconds); return; } // Set up headers to really send it. response.setStatus(HttpServletResponse.SC_OK); long now = new Date().getTime(); response.setHeader(HttpHeaders.DATE, HttpHeaders.toInternetDateFormat(now)); response.setContentType(mimeType); String lastModifiedStr = HttpHeaders.toInternetDateFormat(lastModified); response.setHeader(HttpHeaders.LAST_MODIFIED, lastModifiedStr); // Expiration header. Either immediately stale (requiring an // "If-Modified-Since") or infinitely cacheable (not requiring even a // freshness check). setResponseCacheHeaders(response, cacheSeconds); // Content length. int contentLength = conn.getContentLength(); if (contentLength >= 0) { response.setHeader(HttpHeaders.CONTENT_LENGTH, Integer.toString(contentLength)); } // Send the bytes. is = conn.getInputStream(); streamOut(is, response.getOutputStream(), 1024 * 8); } finally { Utility.close(is); } }
From source file:org.brutusin.rpc.http.RpcServlet.java
/** * * @param reqEtag//from w w w .ja v a 2 s . com * @param req * @param resp * @param rpcResponse * @param cachingInfo * @throws IOException */ private void serviceJsonResponse(String reqEtag, HttpServletRequest req, HttpServletResponse resp, RpcResponse rpcResponse, CachingInfo cachingInfo) throws IOException { if (rpcResponse.getError() != null) { setStatusCode(rpcResponse.getError(), resp); } String json; try { json = JsonCodec.getInstance().transform(rpcResponse); } catch (Throwable th) { RpcResponse errorResponse = new RpcResponse(); errorResponse.setId(rpcResponse.getId()); errorResponse.setError(ErrorFactory.getError(th)); json = JsonCodec.getInstance().transform(errorResponse); cachingInfo = null; } resp.setContentType(JSON_CONTENT_TYPE); String eTag = null; if (cachingInfo != null) { if (json == null) { eTag = CryptoUtils.getHashMD5("null"); } else { eTag = CryptoUtils.getHashMD5(json); } } addCacheHeaders(req, resp, cachingInfo, eTag); if (reqEtag != null && reqEtag.equals(eTag)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } else { resp.getWriter().print(json); } }
From source file:org.protorabbit.servlet.ProtoRabbitServlet.java
void processResourceRequest(String id, WebContext wc, HttpServletRequest req, HttpServletResponse resp, boolean canGzip) throws IOException { OutputStream out = resp.getOutputStream(); int lastDot = id.lastIndexOf("."); int resourceType = Config.UNKNOWN; if (lastDot != -1) { String extension = id.substring(lastDot + 1, id.length()); if ("css".equals(extension)) { resourceType = Config.STYLE; } else if ("js".equals(extension)) { resourceType = Config.SCRIPT; }/*w w w .ja v a 2 s . co m*/ id = id.substring(0, lastDot); } String resourceId = id; String templateId = req.getParameter("tid"); if (templateId != null) { resourceId = templateId + "_" + resourceId; } boolean shouldGzip = false; ITemplate t = null; if (templateId != null) { t = jcfg.getTemplate(templateId, wc); wc.setTemplateId(templateId); } ResourceManager crm = jcfg.getCombinedResourceManager(); ICacheable cr = crm.getResource(resourceId, wc); boolean requiresUAHandling = false; boolean hasUATest = false; if (t != null) { if (resourceType == Config.SCRIPT) { hasUATest = t.hasUserAgentScriptDependencies(wc); if (hasUATest) { String uaTest = wc.getUAScriptTests().get(0); requiresUAHandling = wc.uaTest(uaTest); } } else if (resourceType == Config.STYLE) { hasUATest = t.hasUserAgentStyleDependencies(wc); if (hasUATest) { String uaTest = wc.getUAStyleTests().get(0); requiresUAHandling = wc.uaTest(uaTest); } } } // re-constitute the resource. This case will happen across server restarts // where a client may have a resource reference with a long cache time if ("protorabbit".equals(id)) { cr = crm.getResource("protorabbit", wc); if (cr == null) { StringBuffer buff = IOUtil.getClasspathResource(jcfg, Config.PROTORABBIT_CLIENT); if (buff != null) { String hash = IOUtil.generateHash(buff.toString()); cr = new CacheableResource("text/javascript", jcfg.getMaxAge(), hash); jcfg.getCombinedResourceManager().putResource("protorabbit", cr); cr.setContent(buff); } else { getLogger().severe("Unable to find protorabbit client script"); } } } else if ("episodes".equals(id)) { cr = crm.getResource("episodes", wc); if (cr == null) { StringBuffer buff = IOUtil.getClasspathResource(jcfg, Config.EPISODES_CLIENT); if (buff != null) { String hash = IOUtil.generateHash(buff.toString()); cr = new CacheableResource("text/javascript", jcfg.getMaxAge(), hash); jcfg.getCombinedResourceManager().putResource("episodes", cr); cr.setContent(buff); } else { getLogger().severe("Unable to find episodes client script"); } } } else if (cr == null && t != null && resourceId != null || requiresUAHandling || (cr != null && cr.getCacheContext().isExpired())) { getLogger().fine("Re-constituting " + id + " from template " + templateId); IProperty property = null; if ("styles".equals(id)) { List<ResourceURI> styles = t.getAllStyles(wc); crm.processStyles(styles, wc, out); cr = crm.getResource(resourceId, wc); } else if ("scripts".equals(id)) { List<ResourceURI> scripts = t.getAllScripts(wc); crm.processScripts(scripts, wc, false, out); cr = crm.getResource(resourceId, wc); } else if ("messages".equals(id)) { if (json == null) { SerializationFactory factory = new SerializationFactory(); json = factory.getInstance(); } List<IProperty> deferredProperties = new ArrayList<IProperty>(); t.getDeferProperties(deferredProperties, wc); JSONObject jo = (JSONObject) json.serialize(deferredProperties); String content = jo.toString(); cr = new CacheableResource("application/json", jcfg.getResourceTimeout(), resourceId); cr.setContent(new StringBuffer(content)); crm.putResource(resourceId, cr); // assume this is a request for a deferred resource that hasn't been created } else { if (t != null) { property = t.getPropertyById(id, wc); } if (property == null) { getLogger().severe("Unable to find property with id " + id + ((t != null) ? " in template " + t.getId() : " with no template.")); return; } } // now before we do the work set the cache header if (canGzip) { if ("scripts".equals(id) && t.gzipScripts(wc) != null && t.gzipScripts(wc) == true) { shouldGzip = true; resp.setHeader("Content-Type", "text/javascript"); } else if ("styles".equals(id) && t.gzipStyles(wc) != null && t.gzipStyles(wc) == true) { shouldGzip = true; resp.setHeader("Content-Type", "text/css"); } else if (property != null && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) { shouldGzip = true; resp.setHeader("Content-Type", "text/html"); } } // gzip needs to be set before we do anything else given a call to the RequestDispatcher will // stop all further headers if (shouldGzip) { resp.setHeader("Content-Encoding", "gzip"); resp.setHeader("Vary", "Accept-Encoding"); } if (property != null) { StringBuffer buff = null; IncludeFile inc = jcfg.getIncludeFileContent(property.getKey(), wc); if (inc != null) { buff = inc.getContent(); String hash = IOUtil.generateHash(buff.toString()); if (property.getId() != null) { resourceId = property.getId(); } else { resourceId = hash; } cr = new CacheableResource("text/html", inc.getTimeout(), hash); cr.setContent(buff); crm.putResource(templateId + "_" + resourceId, cr); } } else if ("styles".equals(id)) { if (cr == null) { cr = crm.getResource(resourceId, wc); } } else if ("scripts".equals(id)) { if (cr == null) { cr = crm.getResource(resourceId, wc); } } else if ("messages".equals(id)) { if (json == null) { SerializationFactory factory = new SerializationFactory(); json = factory.getInstance(); } List<IProperty> deferredProperties = new ArrayList<IProperty>(); t.getDeferProperties(deferredProperties, wc); JSONObject jo = (JSONObject) json.serialize(deferredProperties); String content = jo.toString(); cr = new CacheableResource("application/json", jcfg.getResourceTimeout(), resourceId); cr.setContent(new StringBuffer(content)); crm.putResource(resourceId, cr); // assume this is a request for a deferred resource that hasn't been created } } else if (cr == null) { getLogger().severe("Could not find resource " + id + " with template " + templateId); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (cr != null) { CacheContext cc = cr.getCacheContext(); if (cc.isExpired() || cr.getContent() == null || cr.getStatus() == ICacheable.INITIALIZED) { cr.refresh(wc); } // wait for the resource to load int tries = 0; while ((cr.getStatus() != 200) && tries < maxTries) { try { Thread.sleep(tryTimeout); } catch (InterruptedException e) { } tries += 1; } if (cr.getStatus() != 200) { resp.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT); return; } if (cr.getContentType() != null) { resp.setContentType(cr.getContentType()); } String etag = cr.getContentHash(); // get the If-None-Match header String ifNoneMatch = req.getHeader("If-None-Match"); if (etag != null && ifNoneMatch != null && ifNoneMatch.equals(etag)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); } long timeout = 0; if (t != null && t.getTimeout(wc) != null) { timeout = t.getTimeout(wc); } if (etag != null && t != null && timeout > 0 && !jcfg.profile()) { resp.setHeader("ETag", etag); resp.setHeader("Expires", cc.getExpires()); resp.setHeader("Cache-Control", "public,max-age=" + cc.getMaxAge()); } if (shouldGzip) { byte[] bytes = cr.getGZippedContent(); cr.incrementGzipAccessCount(); if (bytes != null) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); IOUtil.writeBinaryResource(bis, out); } } else { cr.incrementAccessCount(); out.write(cr.getContent().toString().getBytes()); } } long now = (new Date()).getTime(); if (now - lastCleanup > cleanupTimeout) { getLogger().info("Protorabbit cleaning up old Objects"); jcfg.getCombinedResourceManager().cleanup(maxAge); lastCleanup = now; } }
From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response * back to the client via the given {@link javax.servlet.http.HttpServletResponse} * * @param proxyDetails//from ww w . ja va2 s.co m * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied * response back to the client * @throws java.io.IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { httpMethodProxyRequest.setDoAuthentication(false); httpMethodProxyRequest.setFollowRedirects(false); // Create a default HttpClient HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest); // Execute the request int intProxyResponseCode = 500; try { intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); } catch (Exception e) { e.printStackTrace(); } // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + STRING_LOCATION_HEADER + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(stringLocation .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName)); return; } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (!ProxySupport.isHopByHopHeader(header.getName())) { if (ProxySupport.isSetCookieHeader(header)) { HttpProxyRule proxyRule = proxyDetails.getProxyRule(); String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(), proxyRule.getCookiePath(), proxyRule.getCookieDomain()); httpServletResponse.setHeader(header.getName(), setCookie); } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } } // check if we got data, that is either the Content-Length > 0 // or the response code != 204 int code = httpMethodProxyRequest.getStatusCode(); boolean noData = code == HttpStatus.SC_NO_CONTENT; if (!noData) { String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME); if (length != null && "0".equals(length.trim())) { noData = true; } } if (!noData) { // Send the content to the client InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream(); BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse); OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream(); int intNextByte; while ((intNextByte = bufferedInputStream.read()) != -1) { outputStreamClientResponse.write(intNextByte); } } }
From source file:org.codeartisans.proxilet.Proxilet.java
/** * Executes the {@link HttpMethod} passed in and sends the proxy response back to the client via the given * {@link HttpServletResponse}./*from w ww . j a v a 2s . c om*/ * * @param httpMethodProxyRequest An object representing the proxy request to be made * @param httpServletResponse An object by which we can send the proxied response back to the client * @throws IOException Can be thrown by the {@link HttpClient}.executeMethod * @throws ServletException Can be thrown to indicate that another error has occurred */ private void executeProxyRequest(HttpMethod httpMethodProxyRequest, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException { // Create a default HttpClient HttpClient httpClient; httpClient = createClientWithLogin(); httpMethodProxyRequest.setFollowRedirects(false); // Execute the request int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest); // String response = httpMethodProxyRequest.getResponseBodyAsString(); // Check if the proxy response is a redirect // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect // Hooray for open source software if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */ && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */ ) { String stringStatusCode = Integer.toString(intProxyResponseCode); String stringLocation = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue(); if (stringLocation == null) { throw new ServletException("Received status code: " + stringStatusCode + " but no " + HEADER_LOCATION + " header was found in the response"); } // Modify the redirect to go to this proxy servlet rather that the proxied host String stringMyHostName = httpServletRequest.getServerName(); if (httpServletRequest.getServerPort() != 80) { stringMyHostName += ":" + httpServletRequest.getServerPort(); } stringMyHostName += httpServletRequest.getContextPath(); if (followRedirects) { httpServletResponse .sendRedirect(stringLocation.replace(getProxyHostAndPort() + proxyPath, stringMyHostName)); return; } } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // We get a 304 whenever passed an 'If-Modified-Since' // header and the data on disk has not changed; server // responds w/ a 304 saying I'm not going to send the // body because the file has not changed. httpServletResponse.setIntHeader(HEADER_CONTENT_LENGTH, 0); httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } // Pass the response code back to the client httpServletResponse.setStatus(intProxyResponseCode); // Pass response headers back to the client Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders(); for (Header header : headerArrayResponse) { if (header.getName().equals("Transfer-Encoding") && header.getValue().equals("chunked") || header.getName().equals("Content-Encoding") && header.getValue().equals("gzip")) { // proxy servlet does not support chunked encoding } else { httpServletResponse.setHeader(header.getName(), header.getValue()); } } List<Header> responseHeaders = Arrays.asList(headerArrayResponse); // FIXME We should handle both String and bytes response in the same way: String response = null; byte[] bodyBytes = null; if (isBodyParameterGzipped(responseHeaders)) { LOGGER.trace("GZipped: true"); if (!followRedirects && intProxyResponseCode == HttpServletResponse.SC_MOVED_TEMPORARILY) { response = httpMethodProxyRequest.getResponseHeader(HEADER_LOCATION).getValue(); httpServletResponse.setStatus(HttpServletResponse.SC_OK); intProxyResponseCode = HttpServletResponse.SC_OK; httpServletResponse.setHeader(HEADER_LOCATION, response); httpServletResponse.setContentLength(response.length()); } else { bodyBytes = ungzip(httpMethodProxyRequest.getResponseBody()); httpServletResponse.setContentLength(bodyBytes.length); } } if (httpServletResponse.getContentType() != null && httpServletResponse.getContentType().contains("text")) { LOGGER.trace("Received status code: {} Response: {}", intProxyResponseCode, response); } else { LOGGER.trace("Received status code: {} [Response is not textual]", intProxyResponseCode); } // Send the content to the client if (response != null) { httpServletResponse.getWriter().write(response); } else if (bodyBytes != null) { httpServletResponse.getOutputStream().write(bodyBytes); } else { IOUtils.copy(httpMethodProxyRequest.getResponseBodyAsStream(), httpServletResponse.getOutputStream()); } }
From source file:org.geowebcache.GeoWebCacheDispatcher.java
/** * Writes a transparent, 8 bit PNG to avoid having clients like OpenLayers showing lots of pink * tiles//from www . j a v a 2 s . c o m */ private void writeEmpty(ConveyorTile tile, String message) { tile.servletResp.setHeader("geowebcache-message", message); TileLayer layer = tile.getLayer(); if (layer != null) { layer.setExpirationHeader(tile.servletResp, (int) tile.getTileIndex()[2]); if (layer.useETags()) { String ifNoneMatch = tile.servletReq.getHeader("If-None-Match"); if (ifNoneMatch != null && ifNoneMatch.equals("gwc-blank-tile")) { tile.servletResp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } else { tile.servletResp.setHeader("ETag", "gwc-blank-tile"); } } } writeFixedResponse(tile.servletResp, 200, ImageMime.png.getMimeType(), this.blankTile, CacheResult.OTHER); }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // initialize request attributes from caches if unset by a subclass by // this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); }/* ww w .j av a 2 s . c o m*/ if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // Make the Request // note: we won't transfer the protocol version because I'm not sure it // would truly be compatible String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest; // spec: RFC 2616, sec 4.3: either of these two headers signal that // there is a message body. System.out.println("proxyrequestURI" + proxyRequestUri); if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { proxyRequest = newProxyRequestWithEntity(method, proxyRequestUri, servletRequest); } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } proxyRequest.addHeader(org.apache.http.cookie.SM.COOKIE, cookieString); System.out.println("added cookie::" + cookieString); addBrowserHeader(proxyRequest); copyRequestHeaders(servletRequest, proxyRequest); //setXForwardedForHeader(servletRequest, proxyRequest); System.out.println("method" + method); System.out.println("final header showing"); for (Header header : proxyRequest.getAllHeaders()) { System.out.println(header.getName() + "::" + header.getValue() + "::"); } System.out.println("end final header"); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { System.out.println("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } System.out.println("targethost:" + getTargetHost(servletRequest)); System.out.println(proxyRequest.getRequestLine().toString()); proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest, proxyContext); // Process the response: // Pass the response code. This method with the "reason phrase" is // deprecated but it's the // only way to pass the reason along too. int statusCode = proxyResponse.getStatusLine().getStatusCode(); System.out.println(proxyResponse.getStatusLine().getStatusCode() + proxyResponse.getStatusLine().getReasonPhrase()); // noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); // Copying response headers to make sure SESSIONID or other Cookie // which comes from the remote // server will be saved in client when the proxied url was // redirected to another one. // See issue // [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51) copyResponseHeaders(proxyResponse, servletRequest, servletResponse); if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) { // 304 needs special handling. See: // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304 // Don't send body entity/content! servletResponse.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0); } else { // Send the content to the client copyResponseEntity(proxyResponse, servletResponse, proxyRequest, servletRequest); } } catch (Exception e) { // abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; // noinspection ConstantConditions if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } finally { // make sure the entire entity was consumed, so the connection is // released if (proxyResponse != null) consumeQuietly(proxyResponse.getEntity()); // Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }