List of usage examples for javax.servlet.http HttpServletRequest getHeaders
public Enumeration<String> getHeaders(String name);
Enumeration
of String
objects. From source file:org.josso.tc50.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * @param valveContext The valve _context used to invoke the next valve * in the current processing pipeline//from w ww . jav a 2 s .co m * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs */ public void invoke(Request request, Response response, ValveContext valveContext) throws IOException, javax.servlet.ServletException { if (debug >= 1) log("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); valveContext.invokeNext(request, response); return; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (debug >= 1) log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. // Check how to make chunked transfer encoding work. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (debug >= 1) log("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (debug >= 1) log("ReverseProxyValve finished."); return; }
From source file:org.josso.gl2.gateway.reverseproxy.ReverseProxyValve.java
/** * Intercepts Http request and redirects it to the configured SSO partner application. * * @param request The servlet request to be processed * @param response The servlet response to be created * @exception IOException if an input/output error occurs * @exception javax.servlet.ServletException if a servlet error occurs *///from w ww. ja v a 2 s . c o m public int invoke(Request request, Response response) throws IOException, ServletException { if (debug >= 1) log("ReverseProxyValve Acting."); ProxyContextConfig[] contexts = _rpc.getProxyContexts(); // Create an instance of HttpClient. HttpClient client = new HttpClient(); HttpServletRequest hsr = (HttpServletRequest) request.getRequest(); String uri = hsr.getRequestURI(); String uriContext = null; StringTokenizer st = new StringTokenizer(uri.substring(1), "/"); while (st.hasMoreTokens()) { String token = st.nextToken(); uriContext = "/" + token; break; } if (uriContext == null) uriContext = uri; // Obtain the target host from the String proxyForwardHost = null; String proxyForwardUri = null; for (int i = 0; i < contexts.length; i++) { if (contexts[i].getContext().equals(uriContext)) { log("Proxy context mapped to host/uri: " + contexts[i].getForwardHost() + contexts[i].getForwardUri()); proxyForwardHost = contexts[i].getForwardHost(); proxyForwardUri = contexts[i].getForwardUri(); break; } } if (proxyForwardHost == null) { log("URI '" + uri + "' can't be mapped to host"); //valveContext.invokeNext(request, response); return Valve.INVOKE_NEXT; } if (proxyForwardUri == null) { // trim the uri context before submitting the http request int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = uri.substring(uriTrailStartPos); } else { int uriTrailStartPos = uri.substring(1).indexOf("/") + 1; proxyForwardUri = proxyForwardUri + uri.substring(uriTrailStartPos); } // log ("Proxy request mapped to " + "http://" + proxyForwardHost + proxyForwardUri); HttpMethod method; // to be moved to a builder which instantiates and build concrete methods. if (hsr.getMethod().equals(METHOD_GET)) { // Create a method instance. HttpMethod getMethod = new GetMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = getMethod; } else if (hsr.getMethod().equals(METHOD_POST)) { // Create a method instance. PostMethod postMethod = new PostMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); postMethod.setRequestBody(hsr.getInputStream()); method = postMethod; } else if (hsr.getMethod().equals(METHOD_HEAD)) { // Create a method instance. HeadMethod headMethod = new HeadMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); method = headMethod; } else if (hsr.getMethod().equals(METHOD_PUT)) { method = new PutMethod(proxyForwardHost + proxyForwardUri + (hsr.getQueryString() != null ? ("?" + hsr.getQueryString()) : "")); } else throw new java.lang.UnsupportedOperationException("Unknown method : " + hsr.getMethod()); // copy incoming http headers to reverse proxy request Enumeration hne = hsr.getHeaderNames(); while (hne.hasMoreElements()) { String hn = (String) hne.nextElement(); // Map the received host header to the target host name // so that the configured virtual domain can // do the proper handling. if (hn.equalsIgnoreCase("host")) { method.addRequestHeader("Host", proxyForwardHost); continue; } Enumeration hvals = hsr.getHeaders(hn); while (hvals.hasMoreElements()) { String hv = (String) hvals.nextElement(); method.addRequestHeader(hn, hv); } } // Add Reverse-Proxy-Host header String reverseProxyHost = getReverseProxyHost(request); method.addRequestHeader(Constants.JOSSO_REVERSE_PROXY_HEADER, reverseProxyHost); if (debug >= 1) log("Sending " + Constants.JOSSO_REVERSE_PROXY_HEADER + " " + reverseProxyHost); // DO NOT follow redirects ! method.setFollowRedirects(false); // By default the httpclient uses HTTP v1.1. We are downgrading it // to v1.0 so that the target server doesn't set a reply using chunked // transfer encoding which doesn't seem to be handled properly. // Check how to make chunked transfer encoding work. client.getParams().setVersion(new HttpVersion(1, 0)); // Execute the method. int statusCode = -1; try { // execute the method. statusCode = client.executeMethod(method); } catch (HttpRecoverableException e) { log("A recoverable exception occurred " + e.getMessage()); } catch (IOException e) { log("Failed to connect."); e.printStackTrace(); } // Check that we didn't run out of retries. if (statusCode == -1) { log("Failed to recover from exception."); } // Read the response body. byte[] responseBody = method.getResponseBody(); // Release the connection. method.releaseConnection(); HttpServletResponse sres = (HttpServletResponse) response.getResponse(); // First thing to do is to copy status code to response, otherwise // catalina will do it as soon as we set a header or some other part of the response. sres.setStatus(method.getStatusCode()); // copy proxy response headers to client response Header[] responseHeaders = method.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header responseHeader = responseHeaders[i]; String name = responseHeader.getName(); String value = responseHeader.getValue(); // Adjust the URL in the Location, Content-Location and URI headers on HTTP redirect responses // This is essential to avoid by-passing the reverse proxy because of HTTP redirects on the // backend servers which stay behind the reverse proxy switch (method.getStatusCode()) { case HttpStatus.SC_MOVED_TEMPORARILY: case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_SEE_OTHER: case HttpStatus.SC_TEMPORARY_REDIRECT: if ("Location".equalsIgnoreCase(name) || "Content-Location".equalsIgnoreCase(name) || "URI".equalsIgnoreCase(name)) { // Check that this redirect must be adjusted. if (value.indexOf(proxyForwardHost) >= 0) { String trail = value.substring(proxyForwardHost.length()); value = getReverseProxyHost(request) + trail; if (debug >= 1) log("Adjusting redirect header to " + value); } } break; } //end of switch sres.addHeader(name, value); } // Sometimes this is null, when no body is returned ... if (responseBody != null && responseBody.length > 0) sres.getOutputStream().write(responseBody); sres.getOutputStream().flush(); if (debug >= 1) log("ReverseProxyValve finished."); return Valve.END_PIPELINE; }
From source file:org.wrml.server.WrmlServlet.java
/** * Build the WRML {@link Dimensions} object that, within the WRML runtime, will represent many of the same * "metadata" ideas that HTTP has delcared {@link org.wrml.model.rest.CommonHeader}s. * * @param request The {@link HttpServletRequest} that holds the metadata that is needed for the {@link Dimensions}. * @param method The requested interaction {@link Method}. * @param requestUri The requested resource's id ({@link URI}). * @param api The target REST API ({@link Api}). * @param acceptableMediaTypes The client-specified acceptable {@link MediaType}s. * @return The requested {@link Dimensions} of the desired response entity {@link Model}. *//* w w w.j a va 2s. c om*/ Dimensions buildDimensions(final HttpServletRequest request, final Method method, final URI requestUri, final Api api, final List<MediaType> acceptableMediaTypes) throws ServletException { // Determine the best possible schema URI for the response. final List<URI> acceptableSchemaUriList = getAcceptableResponseEntitySchemaUris(method, requestUri, acceptableMediaTypes); final URI responseModelSchemaUri; if (!acceptableSchemaUriList.isEmpty()) { responseModelSchemaUri = acceptableSchemaUriList.get(0); } else { if (!acceptableMediaTypes.isEmpty()) { throw new ServletException("A 406. The WRML REST API (" + api.getTitle() + ") doesn't define any acceptable representations of the resource identified by: " + requestUri); } if (method == Method.Get) { throw new ServletException("A 403? The WRML REST API (" + api.getTitle() + ") doesn't define any representation of the resource identified by: " + requestUri); } // The interaction may not return anything, (e.g. DELETE) responseModelSchemaUri = null; } final DimensionsBuilder dimensionsBuilder = new DimensionsBuilder(responseModelSchemaUri); if (responseModelSchemaUri != null && !acceptableMediaTypes.isEmpty()) { // It would make sense for this to be the first (and only) media type that a WRML client would pass in the Accept header. final MediaType mediaType = acceptableMediaTypes.get(0); if (mediaType.getFullType().equals(SystemMediaType.MEDIA_TYPE_STRING_WRML)) { // These are communicated to a WRML server as parameters to the WRML media type that is passed in the HTTP Accept header. final String includedSlotNamesStringValue = mediaType .getParameter(SystemMediaType.PARAMETER_NAME_INCLUDE); final List<String> includedSlotNames = dimensionsBuilder.getIncludedSlotNames(); includedSlotNames.addAll(parseMediaTypeParameterList(includedSlotNamesStringValue)); final String excludedSlotNamesStringValue = mediaType .getParameter(SystemMediaType.PARAMETER_NAME_EXCLUDE); final List<String> excludedSlotNames = dimensionsBuilder.getExcludedSlotNames(); excludedSlotNames.addAll(parseMediaTypeParameterList(excludedSlotNamesStringValue)); final String embeddedLinkSlotNamesStringValue = mediaType .getParameter(SystemMediaType.PARAMETER_NAME_EMBED); final List<String> embeddedLinkSlotNames = dimensionsBuilder.getEmbeddedLinkSlotNames(); embeddedLinkSlotNames.addAll(parseMediaTypeParameterList(embeddedLinkSlotNamesStringValue)); } } final Locale locale = request.getLocale(); dimensionsBuilder.setLocale(locale); final SortedMap<String, String> metadata = dimensionsBuilder.getMetadata(); final Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); final Enumeration<String> headerValues = request.getHeaders(headerName); final StringBuilder headerValueStringBuilder = new StringBuilder(); while (headerValues.hasMoreElements()) { final String partialHeaderValue = headerValues.nextElement(); headerValueStringBuilder.append(partialHeaderValue); if (headerValues.hasMoreElements()) { headerValueStringBuilder.append(", "); } } final String headerValue = headerValueStringBuilder.toString(); metadata.put(headerName, headerValue); final CommonHeader commonHeader = CommonHeader.fromString(headerName); if (commonHeader == null) { continue; } switch (commonHeader) { case REFERER: final URI referrerUri = URI.create(headerValue); dimensionsBuilder.setReferrerUri(referrerUri); break; default: break; } } final SortedMap<String, String> queryParameters = dimensionsBuilder.getQueryParameters(); final Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { final String parameterName = parameterNames.nextElement(); final String[] parameterValues = request.getParameterValues(parameterName); final String parameterValue = StringUtils.join(parameterValues, ", "); queryParameters.put(parameterName, parameterValue); } final Context context = getContext(); final ApiLoader apiLoader = context.getApiLoader(); final Dimensions dimensions = apiLoader.buildDocumentDimensions(method, requestUri, dimensionsBuilder); return dimensions; }
From source file:org.commoncrawl.service.listcrawler.ProxyServlet2.java
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {/*from w w w . ja v a 2s . c o m*/ final RequestDetails details = new RequestDetails(); String uri = request.getRequestURI(); if (request.getQueryString() != null) uri += "?" + request.getQueryString(); final URL url = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), uri); if (request.getServerName().equals("proxy")) { serviceProxyInternalRequest(req, res); return; } // context.log("URL="+url); details.url = url; // attempt cache load first ... CacheLoadRequest cacheLoad = new CacheLoadRequest(url); details.log.add("Executing Disk Load Request"); DiskCacheItem cacheItem = cacheLoad.executeRequest(); details.log.add("Disk Load Request Returned:" + cacheItem); // create metadata placeholder CrawlURLMetadata metadata = new CrawlURLMetadata(); NIOHttpHeaders headers = null; boolean revalidate = false; boolean cacheItemValid = true; if (cacheItem != null) { // get headers headers = buildHeaderFromHeaderItems(cacheItem.getHeaderItems()); // set last fetch time in metadata metadata.setLastFetchTimestamp(cacheItem.getFetchTime()); // parse headers HttpHeaderInfoExtractor.parseHeaders(headers, metadata); // ok now validate cache if (HttpCacheUtils.requiresValidation(metadata)) { details.log.add("CACHE Item Present But Needs Revalidation"); revalidate = true; } } // if no cache item or we to revalidate cache item .. if (cacheItem == null || revalidate) { NIOHttpConnection connection = new NIOHttpConnection(url, ProxyServer.getSingleton().getEventLoop().getSelector(), ProxyServer.getSingleton().getEventLoop().getResolver(), _cookieStore); NIOConnectionWrapper wrapper = new NIOConnectionWrapper(connection); // URLConnection connection = url.openConnection(); // connection.setAllowUserInteraction(false); // Set method /* HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection)connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } */ connection.setMethod(request.getMethod()); // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr) || lhdr.equals("cookie")) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.getRequestHeaders().set(hdr, val); // connection.addRequestProperty(hdr,val); details.log.add("req header: " + hdr + ": " + val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } String cookies = _cookieStore.GetCookies(url); if (cookies.length() != 0) { details.log.add("req injected-header: Cookie:" + cookies); connection.getRequestHeaders().set("Cookie", cookies); } // Proxy headers connection.getRequestHeaders().set("Via", "1.1 (jetty)"); // cache headers (if required) if (metadata.isFieldDirty(CrawlURLMetadata.Field_LASTMODIFIEDTIME)) { details.log.add("Sending If-Modified-Since"); connection.getRequestHeaders().set("If-Modified-Since", headers.findValue("Last-Modified")); } if (metadata.isFieldDirty(CrawlURLMetadata.Field_ETAG)) { details.log.add("Sending If-None-Match"); connection.getRequestHeaders().set("If-None-Match", metadata.getETag()); } if (!xForwardedFor) connection.getRequestHeaders().set("X-Forwarded-For", request.getRemoteAddr()); //connection.addRequestProperty("X-Forwarded-For",request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); /* if (cache_control!=null && (cache_control.indexOf("no-cache")>=0 || cache_control.indexOf("no-store")>=0)) connection.setUseCaches(false); */ // customize Connection try { // connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { //connection.setDoOutput(true); ByteArrayOutputStream stream = new ByteArrayOutputStream(); IO.copy(in, stream); wrapper.setUploadBuffer(stream.toByteArray()); } // Connect connection.open(); } catch (Exception e) { details.log.add(CCStringUtils.stringifyException(e)); } boolean connectionSucceeded = wrapper.waitForCompletion(); InputStream proxy_in = null; // handler status codes etc. int code = 500; if (connectionSucceeded) { // set last fetch time in metadata metadata.setLastFetchTimestamp(System.currentTimeMillis()); code = connection.getResponseHeaders().getHttpResponseCode(); if (revalidate && code != 304) { details.log.add("Item ReValidate FAILED"); cacheItemValid = false; } if (code != 304) { HttpHeaderInfoExtractor.parseHeaders(connection.getResponseHeaders(), metadata); response.setStatus(code, ""); details.log.add("response code:" + code); // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getResponseHeaders().getKey(h); String val = connection.getResponseHeaders().getValue(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) response.addHeader(hdr, val); details.log.add("response header:" + hdr + ": " + val); h++; hdr = connection.getResponseHeaders().getKey(h); val = connection.getResponseHeaders().getValue(h); } response.addHeader("Via", "1.1 (jetty)"); response.addHeader("cache-control", "no-cache,no-store"); response.addHeader("Connection", "close"); // IF RESULT IS CACHEABLE ... LifeTimeInfo lifeTimeInfo = HttpCacheUtils.getFreshnessLifetimeInMilliseconds(metadata); details.log.add("getFreshnessLifetime returned:" + lifeTimeInfo._lifetime); details.log.add("getFreshnessLifetime source:" + lifeTimeInfo._source); if (lifeTimeInfo._lifetime != 0) { details.log.add("item is cachable - issuing cache request"); // construct a disk cache item ... final DiskCacheItem cacheItemForWrite = new DiskCacheItem(); // populate cacheItemForWrite.setFetchTime(System.currentTimeMillis()); cacheItemForWrite.setResponseCode(code); // headers .. h = 0; hdr = connection.getResponseHeaders().getKey(h); val = connection.getResponseHeaders().getValue(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null) { if (!hdr.toLowerCase().equals("set-cookie")) { ArcFileHeaderItem item = new ArcFileHeaderItem(); item.setItemKey(hdr); item.setItemValue(val); cacheItemForWrite.getHeaderItems().add(item); } } h++; hdr = connection.getResponseHeaders().getKey(h); val = connection.getResponseHeaders().getValue(h); } if (connection.getContentBuffer().available() != 0) { // copy result to byte array //VERY INEFFICIENT ... BUT ONLY FOR TESTING ... ByteArrayOutputStream tempStream = new ByteArrayOutputStream(); IO.copy(new NIOBufferListInputStream(connection.getContentBuffer()), tempStream); // get the underlying buffer byte[] responseBuffer = tempStream.toByteArray(); // set it into the cache item ... cacheItemForWrite.setContent(new Buffer(responseBuffer)); // and now write out buffer IO.copy(new ByteArrayInputStream(responseBuffer), response.getOutputStream()); } // ok schedule a disk cache write ... _threadPool.execute(new Runnable() { @Override public void run() { LOG.info("Writing Cache Item for URL:" + url); File cacheFileName; try { cacheFileName = cachePathFromURL(url); try { FileOutputStream fileStream = new FileOutputStream(cacheFileName); try { DataOutputStream dataOutputStream = new DataOutputStream( fileStream); cacheItemForWrite.serialize(dataOutputStream, new BinaryProtocol()); } finally { fileStream.close(); } } catch (IOException e) { LOG.error(CCStringUtils.stringifyException(e)); } } catch (MalformedURLException e) { LOG.error(CCStringUtils.stringifyException(e)); } } }); } else { details.log.add("FRESHNESS LIFETIME == 0 - SKIPPING CACHE!"); // no cache direct copy case if (connection.getContentBuffer().available() != 0) { IO.copy(new NIOBufferListInputStream(connection.getContentBuffer()), response.getOutputStream()); } } } } else { response.setStatus(500, "Proxy Request Failed"); details.log.add("Proxy Request Failed"); } } // ok now, if cache item != null and cache-item is still valid if (cacheItem != null && cacheItemValid) { // service request from cache details.log.add("Servicing Request From Disk Cache"); // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response code response.setStatus(cacheItem.getResponseCode()); // set response headers for (ArcFileHeaderItem headerItem : cacheItem.getHeaderItems()) { String key = headerItem.getItemKey().toLowerCase(); // if not in don't proxy headers ... if (key.length() != 0) { if (!_DontProxyHeaders.contains(key) && !key.equals("set-cookie")) { response.addHeader(headerItem.getItemKey(), headerItem.getItemValue()); details.log.add("cache response: " + headerItem.getItemKey() + ": " + headerItem.getItemValue()); } else { details.log.add("cache hidden-hdr: " + headerItem.getItemKey() + ": " + headerItem.getItemValue()); } } } response.addHeader("Via", "1.1 (jetty)"); response.addHeader("cache-control", "no-cache,no-store"); response.addHeader("Connection", "close"); if (cacheItem.getContent().getCount() != 0) { response.setHeader("Content-Length", null); response.addHeader("Content-Length", Integer.toString(cacheItem.getContent().getCount())); IO.copy(new ByteArrayInputStream(cacheItem.getContent().getReadOnlyBytes()), response.getOutputStream()); } } LOG.info(details.toString()); } }
From source file:org.infoscoop.web.SessionManagerFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) request; if (log.isDebugEnabled()) { log.debug("Enter SessionManagerFilter form " + httpReq.getRequestURI()); }/*from ww w. j av a 2 s . com*/ if (request instanceof javax.servlet.http.HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; String uid = null; if (SessionCreateConfig.doLogin()) { uid = getUidFromSession(httpReq); if (uid != null) { addUidToSession(uid, request); } if (redirectPaths.contains(httpReq.getServletPath())) { httpResponse.addCookie(new Cookie("redirect_path", httpReq.getServletPath())); } if (uid == null && !isExcludePath(httpReq.getServletPath())) { if (httpRequest.getHeader("MSDPortal-Ajax") != null) { if (log.isInfoEnabled()) log.info("session timeout has occured. logoff automatically."); httpResponse.setHeader(HttpStatusCode.HEADER_NAME, HttpStatusCode.MSD_SESSION_TIMEOUT); httpResponse.sendError(500); return; } } } else { uid = getUidFromHeader(httpReq); if (uid == null) uid = getUidFromSession(httpReq); if (uid != null) { addUidToSession(uid, request); } } if (uid == null) { Cookie[] cookies = httpReq.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if (cookie.getName().equals("portal-credential")) { int keepPeriod = 7; try { keepPeriod = Integer.parseInt(PropertiesDAO.newInstance() .findProperty("loginStateKeepPeriod").getValue()); } catch (Exception ex) { log.warn("", ex); } if (keepPeriod <= 0) { Cookie credentialCookie = new Cookie("portal-credential", ""); credentialCookie.setMaxAge(0); credentialCookie.setPath("/"); httpResponse.addCookie(credentialCookie); log.info("clear auto login credential [" + credentialCookie.getValue() + "]"); } else { try { uid = tryAutoLogin(cookie); httpReq.getSession().setAttribute("Uid", uid); log.info("auto login success."); } catch (Exception ex) { log.info("auto login failed.", ex); } } } } } } if (uid == null && SessionCreateConfig.doLogin() && !isExcludePath(httpReq.getServletPath())) { String requestUri = httpReq.getRequestURI(); String loginUrl = requestUri.lastIndexOf("/manager/") > 0 ? requestUri.substring(0, requestUri.lastIndexOf("/")) + "/../login.jsp" : "login.jsp"; httpResponse.sendRedirect(loginUrl); return; } if (log.isInfoEnabled()) log.info("### Access from user " + uid + " to " + httpReq.getRequestURL()); // fix #42 // setUserInfo2Cookie(httpReq, (HttpServletResponse)response, uid); HttpSession session = httpRequest.getSession(); Subject loginUser = (Subject) session.getAttribute(LOGINUSER_SUBJECT_ATTR_NAME); if (loginUser == null || (isChangeLoginUser(uid, loginUser) && !(session instanceof PreviewImpersonationFilter.PreviewHttpSession))) { if (!SessionCreateConfig.getInstance().hasUidHeader() && uid != null) { AuthenticationService service = AuthenticationService.getInstance(); try { if (service != null) loginUser = service.getSubject(uid); } catch (Exception e) { log.error("", e); } } if (loginUser == null || isChangeLoginUser(uid, loginUser)) { loginUser = new Subject(); loginUser.getPrincipals().add(new ISPrincipal(ISPrincipal.UID_PRINCIPAL, uid)); } setLoginUserName(httpRequest, loginUser); for (Map.Entry entry : SessionCreateConfig.getInstance().getRoleHeaderMap().entrySet()) { String headerName = (String) entry.getKey(); String roleType = (String) entry.getValue(); Enumeration headerValues = httpRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { String headerValue = (String) headerValues.nextElement(); try { Set principals = loginUser.getPrincipals(); principals.add(new ISPrincipal(roleType, headerValue)); // loginUser.getPrincipals().add( roleType.getConstructor(paramTypes).newInstance(initArgs) ); if (log.isInfoEnabled()) log.info("Set principal to login subject: " + roleType + "=" + headerValue); } catch (IllegalArgumentException e) { log.error("", e); } catch (SecurityException e) { log.error("", e); } } } session.setAttribute(LOGINUSER_SUBJECT_ATTR_NAME, loginUser); } SecurityController.registerContextSubject(loginUser); if (httpRequest.getHeader("X-IS-TIMEZONE") != null) { int timeZoneOffset = 0; try { timeZoneOffset = Integer.parseInt(httpRequest.getHeader("X-IS-TIMEZONE")); } catch (NumberFormatException e) { if (log.isDebugEnabled()) log.debug(httpRequest.getHeader("X-IS-TIMEZONE"), e); } finally { UserContext.instance().getUserInfo().setClientTimezoneOffset(timeZoneOffset); } } } chain.doFilter(request, response); if (log.isDebugEnabled()) { log.debug("Exit SessionManagerFilterform " + httpReq.getRequestURI()); } }
From source file:org.opensubsystems.core.util.servlet.WebUtils.java
/** * Create debug string containing all parameter names and their values from * the request, all attributes, all cookies and other data characterizing the * request.//from w ww . j a va 2 s .c o m * * @param hsrqRequest - the servlet request. * @return String - debug string containing all parameter names and their * values from the request */ public static String debug(HttpServletRequest hsrqRequest) { Enumeration enumNames; Enumeration enumValues; Iterator iterValues; String strName; String[] arValues; Cookie[] arCookies; int iIndex; Map<String, String[]> mpParamMap; StringBuilder sbfReturn = new StringBuilder(); sbfReturn.append("HttpServletRequest=["); sbfReturn.append("\nRemoteAddress="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteAddr())); sbfReturn.append(";"); sbfReturn.append("\nRemotePort="); sbfReturn.append(hsrqRequest.getRemotePort()); sbfReturn.append(";"); sbfReturn.append("\nRemoteHost="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteHost())); sbfReturn.append(";"); sbfReturn.append("\nRemoteUser="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getRemoteUser())); sbfReturn.append(";"); sbfReturn.append("\nFullURL="); sbfReturn.append(getFullRequestURL(hsrqRequest)); sbfReturn.append(";"); sbfReturn.append("\nContextPath="); sbfReturn.append(hsrqRequest.getContextPath()); sbfReturn.append(";"); sbfReturn.append("\nServletPath="); sbfReturn.append(hsrqRequest.getServletPath()); sbfReturn.append(";"); sbfReturn.append("\nPathInfo ="); sbfReturn.append(hsrqRequest.getPathInfo()); sbfReturn.append(";"); sbfReturn.append("\nRequestURI="); sbfReturn.append(hsrqRequest.getRequestURI()); sbfReturn.append(";"); sbfReturn.append("\nRequestURL="); sbfReturn.append(hsrqRequest.getRequestURL()); sbfReturn.append(";"); sbfReturn.append("\nMethod="); sbfReturn.append(hsrqRequest.getMethod()); sbfReturn.append(";"); sbfReturn.append("\nAuthenticationType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getAuthType())); sbfReturn.append(";"); sbfReturn.append("\nCharacterEncoding="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getCharacterEncoding())); sbfReturn.append(";"); sbfReturn.append("\nContentType="); sbfReturn.append(StringUtils.valueIfNotNull(hsrqRequest.getContentType())); sbfReturn.append(";"); sbfReturn.append("\nMultiPart="); sbfReturn.append(ServletFileUpload.isMultipartContent(hsrqRequest)); sbfReturn.append(";"); // Parameters //////////////////////////////////////////////////////////// try { Map.Entry<String, String[]> entry; // Use getParameterMap rather than request.getParameterNames since it // correctly handles multipart requests mpParamMap = WebParamUtils.getParameterMap("WebUtils: ", hsrqRequest); for (iterValues = mpParamMap.entrySet().iterator(); iterValues.hasNext();) { entry = (Map.Entry<String, String[]>) iterValues.next(); strName = entry.getKey(); arValues = entry.getValue(); sbfReturn.append("\nParam="); sbfReturn.append(strName); sbfReturn.append(" values="); for (iIndex = 0; iIndex < arValues.length; iIndex++) { sbfReturn.append(arValues[iIndex]); if (iIndex < (arValues.length - 1)) { sbfReturn.append(";"); } } if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access parameter map of the request>"); s_logger.log(Level.SEVERE, "Cannot access parameter map of the request", ex); } // Uploaded files //////////////////////////////////////////////////////// if (ServletFileUpload.isMultipartContent(hsrqRequest)) { try { FileItem item; Map<String, FileItem> mpFiles; TwoElementStruct<Map<String, Object>, Map<String, FileItem>> params; params = WebParamUtils.getMultipartParameters("WebUtils: ", hsrqRequest); mpFiles = params.getSecond(); for (iterValues = mpFiles.values().iterator(); iterValues.hasNext();) { item = (FileItem) iterValues.next(); sbfReturn.append("\nUpload="); sbfReturn.append(item.getName()); sbfReturn.append(" field="); sbfReturn.append(item.getFieldName()); sbfReturn.append(" contentType="); sbfReturn.append(item.getContentType()); sbfReturn.append(" isInMemory="); sbfReturn.append(item.isInMemory()); sbfReturn.append(" sizeInBytes="); sbfReturn.append(item.getSize()); if (iterValues.hasNext()) { sbfReturn.append(";"); } } } catch (OSSInvalidDataException ex) { sbfReturn.append("<Cannot access list of multipart parameters>"); s_logger.log(Level.SEVERE, "Cannot access list of multipart parameters", ex); } } // Headers /////////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getHeaderNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nHeader="); sbfReturn.append(strName); sbfReturn.append(" values="); for (enumValues = hsrqRequest.getHeaders(strName); enumValues.hasMoreElements();) { sbfReturn.append(enumValues.nextElement()); if (enumValues.hasMoreElements()) { sbfReturn.append(";"); } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Cookies /////////////////////////////////////////////////////////////// arCookies = hsrqRequest.getCookies(); if (arCookies != null) { Cookie cookie; for (iIndex = 0; iIndex < arCookies.length; iIndex++) { cookie = arCookies[iIndex]; sbfReturn.append("\nCookie="); sbfReturn.append(cookie.getName()); sbfReturn.append(" path="); sbfReturn.append(cookie.getPath()); sbfReturn.append(" path="); sbfReturn.append(cookie.getDomain()); sbfReturn.append(" maxage="); sbfReturn.append(cookie.getMaxAge()); sbfReturn.append(" version="); sbfReturn.append(cookie.getVersion()); sbfReturn.append(" secure="); sbfReturn.append(cookie.getSecure()); sbfReturn.append(" value="); sbfReturn.append(cookie.getValue()); sbfReturn.append(" comment="); sbfReturn.append(StringUtils.valueIfNotNull(cookie.getComment())); if (iIndex < (arCookies.length - 1)) { sbfReturn.append(";"); } } } if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } // Attributes //////////////////////////////////////////////////////////// for (enumNames = hsrqRequest.getAttributeNames(); enumNames.hasMoreElements();) { strName = (String) enumNames.nextElement(); sbfReturn.append("\nAttribute="); sbfReturn.append(strName); sbfReturn.append(" value="); sbfReturn.append(hsrqRequest.getAttribute(strName)); if (enumNames.hasMoreElements()) { sbfReturn.append(";"); } } // Content /////////////////////////////////////////////////////////////// sbfReturn.append("\nContent="); try { sbfReturn.append(StringUtils.convertStreamToString(hsrqRequest.getInputStream(), true)); } catch (IOException ex) { sbfReturn.append("<Cannot access input stream of the request>"); s_logger.log(Level.SEVERE, "Cannot access input stream of the request", ex); } sbfReturn.append(";"); return sbfReturn.toString(); }
From source file:org.protorabbit.servlet.ProtoRabbitServlet.java
@SuppressWarnings("unchecked") @Override/*from w w w .j a v a 2 s. c om*/ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { WebContext wc = null; int bytesServed = 0; long iStartTime = System.currentTimeMillis(); String path = req.getServletPath(); String pathInfo = req.getPathInfo(); String clientId = req.getRemoteAddr(); try { String command = req.getParameter("command"); if (command != null) { if ("ping".equals(command)) { resp.setHeader("pragma", "NO-CACHE"); resp.setHeader("Cache-Control", "no-cache"); resp.getWriter().write((new Date()).getTime() + ""); return; } else if ("timeshift".equals(command)) { long clientTime = Long.parseLong(req.getParameter("clientTime")); resp.setHeader("pragma", "NO-CACHE"); resp.setHeader("Cache-Control", "no-cache"); long timeShift = ((new Date()).getTime() - clientTime); resp.getWriter().write("timeshift=" + timeShift + ";"); return; } else if ("episodesync".equals(command)) { long startTime = Long.parseLong(req.getParameter("timestamp")); long transitTime = Long.parseLong(req.getParameter("transitTime")); Episode e = jcfg.getEpisodeManager().getEpisode(clientId, startTime); if (e == null) { return; } e.setTransitTime(transitTime); Mark m = e.getMark("transit_to"); long transitStartTime = m.getStartTime(); long now = (new Date()).getTime(); long duration = (now - (transitStartTime + transitTime)); // add the page load directly following the start time (add 1 to always make sure it is after transit time) e.addMark(new Mark("page_load", transitStartTime + transitTime + 1)); Measure m1 = new Measure("transit_to", transitTime); // include transit time for this request and intial page load Measure m2 = new Measure("page_load", (duration + transitTime)); e.addMeasure("transit_to", m1); e.addMeasure("page_load", m2); // now - duration is assumed transit time to offset call to this command resp.getWriter().write("var t_firstbyte=new Number(new Date());" + "window.postMessage(\"EPISODES:mark:firstbyte:\" + t_firstbyte, \"*\");"); return; } else if ("stats".equals(command)) { Map<String, Object> stats = new HashMap<String, Object>(); stats.put("cachedResources", jcfg.getCombinedResourceManager().getResources()); stats.put("templates", jcfg.getTemplates()); stats.put("includeFiles", jcfg.getIncludeFiles()); if (json == null) { SerializationFactory factory = new SerializationFactory(); json = factory.getInstance(); } resp.setHeader("pragma", "NO-CACHE"); resp.setHeader("Cache-Control", "no-cache"); Object jo = json.serialize(stats); resp.getWriter().write(jo.toString()); return; } else if ("recordProfile".equals(command)) { long startTime = Long.parseLong(req.getParameter("timestamp")); long timeshift = Long.parseLong(req.getParameter("timeshift")); long timestamp = (new Date()).getTime(); long duration = timestamp - startTime; Episode e = jcfg.getEpisodeManager().getEpisode(clientId, startTime); if (e == null) { getLogger().severe("Unable to find episode " + startTime + " to recourd data into with client " + clientId); return; } e.setTimeshift(timeshift); // make sure to account for transit time Measure m = new Measure("full_request", duration - e.getTransitTime()); e.addMeasure("full_request", m); String data = req.getParameter("data"); JSONObject jo = null; try { jo = new JSONObject(data); jcfg.getEpisodeManager().updateEpisode(clientId, startTime, jo); } catch (JSONException ex) { ex.printStackTrace(); } resp.getWriter().write("ok"); return; } else if ("episodes".equals(command)) { if (json == null) { SerializationFactory factory = new SerializationFactory(); json = factory.getInstance(); } Object data = null; data = jcfg.getEpisodeManager().getEpisodes(); resp.setHeader("pragma", "NO-CACHE"); resp.setHeader("Cache-Control", "no-cache"); Object jo = json.serialize(data); resp.getWriter().write(jo.toString()); return; } else if ("version".equals(command)) { resp.getWriter().write(version); return; } else if ("resetProfiles".equals(command)) { jcfg.getEpisodeManager().reset(); resp.getWriter().write("profiles reset"); return; } else if ("startProfiling".equals(command)) { jcfg.setProfile(true); resp.getWriter().write("profiling enabled"); return; } else if ("stopProfiling".equals(command)) { jcfg.setProfile(false); resp.getWriter().write("profiling disabled"); return; } } else if (pathInfo != null) { for (String t : writeHeaders) { if (pathInfo.endsWith(t)) { writeHeaders(req, resp, pathInfo); return; } } } // check for updates to the templates.json file if (isDevMode) { updateConfig(); } boolean canGzip = false; // check if client supports gzip Enumeration<String> hnum = req.getHeaders("Accept-Encoding"); while (hnum.hasMoreElements()) { String acceptType = hnum.nextElement(); if (acceptType != null && acceptType.indexOf("gzip") != -1) { canGzip = true; break; } } wc = new WebContext(jcfg, ctx, req, resp); wc.setAttribute(Config.START_TIME, new Long(new Date().getTime())); String id = req.getParameter("resourceid"); if (id != null) { processResourceRequest(id, wc, req, resp, canGzip); return; } if (("/" + serviceURI).equals(path)) { path = req.getPathInfo(); } int lastSep = -1; if (path != null) { lastSep = path.lastIndexOf("/"); } String namespace = null; if (lastSep != -1 && lastSep < path.length() - 1) { int nextDot = path.indexOf(".", lastSep + 1); int lastSlash = path.lastIndexOf("/"); if (nextDot != -1) { id = path.substring(lastSep + 1, nextDot); } else { if (lastSlash != -1 && lastSlash < path.length()) { id = path.substring(lastSlash + 1); } } if (lastSlash != -1 && lastSlash < path.length()) { namespace = path.substring(0, lastSlash); } } ITemplate t = null; if (id != null) { t = jcfg.getTemplate(id, wc); if (jcfg.profile()) { long timestamp = (new Date()).getTime(); Episode e = new Episode(timestamp); e.setUserAgent(req.getHeader("user-agent")); e.setClientId(clientId); e.setUri(id); e.addMark(new Mark("full_request", timestamp)); e.addMark(new Mark("server_render", timestamp)); wc.setAttribute(Config.EPISODE, e); wc.setAttribute(Config.DEFAULT_EPISODE_PROCESS, new Boolean(true)); jcfg.getEpisodeManager().addEpisode(e); } } // make sure that if a namespace is required that is is used to access the template. Also account for "" which can // result from the namespace. boolean namespaceOk = true; if (t != null && t.getURINamespace(wc) != null) { if (namespace == null || (namespace != null && "".equals(namespace)) || !t.getURINamespace(wc).startsWith(namespace)) { namespaceOk = false; getLogger().warning( "request for template " + id + " without matching namespace " + t.getURINamespace(wc)); } } if (id == null || t == null || !namespaceOk) { getLogger().warning("template " + id + " requested but not found."); resp.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // set the template engine IEngine renderEngine = null; if (t.getTemplateURI(wc).getFullURI().endsWith(".st")) { renderEngine = new StringTemplateEngine(); // build up a list of the session/reqeust attributes for string tempalte Map<String, Object> sessionMap = new HashMap<String, Object>(); HttpSession hs = req.getSession(); Enumeration en = hs.getAttributeNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); sessionMap.put(key, hs.getAttribute(key)); } Map<String, Object> requestMap = new HashMap<String, Object>(); Enumeration ren = req.getAttributeNames(); while (ren.hasMoreElements()) { String key = (String) en.nextElement(); requestMap.put(key, req.getAttribute(key)); } wc.setAttribute("session", sessionMap); req.getSession().setAttribute("protorabbitVersion", version); req.getSession().setAttribute("protorabbitBuildDate", buildDate); wc.setAttribute("request", requestMap); } else { renderEngine = engine; } // buffer the output stream ByteArrayOutputStream bos = new ByteArrayOutputStream(); ICacheable tr = t.getTemplateResource(); resp.setHeader("Content-Type", "text/html"); if (jcfg.profile()) { resp.setHeader("pragma", "NO-CACHE"); resp.setHeader("Cache-Control", "no-cache"); } // get the initial content or get the content if it is expired if ((t.getTimeout(wc) != null && (t.getTimeout(wc) > 0) && ((tr == null || tr.getCacheContext().isExpired()) || t.requiresRefresh(wc) || jcfg.profile() || t.hasUserAgentPropertyDependencies(wc)))) { if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) { resp.setHeader("Vary", "Accept-Encoding"); resp.setHeader("Content-Encoding", "gzip"); } // headers after this point do not get written renderEngine.renderTemplate(id, wc, bos); String content = bos.toString(jcfg.getEncoding()); String hash = IOUtil.generateHash(content); ICacheable cr = new CacheableResource("text/html", t.getTimeout(wc), hash); if (!jcfg.profile()) { resp.setHeader("ETag", cr.getContentHash()); } cr.setContent(new StringBuffer(content)); t.setTemplateResource(cr); if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) { byte[] bytes = cr.getGZippedContent(); cr.incrementGzipAccessCount(); resp.setContentLength(bytes.length); OutputStream out = resp.getOutputStream(); if (bytes != null) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); bytesServed = bytes.length; IOUtil.writeBinaryResource(bis, out); } } else { OutputStream out = resp.getOutputStream(); byte[] bytes = cr.getContent().toString().getBytes(); cr.incrementAccessCount(); resp.setContentLength(bytes.length); bytesServed = bytes.length; if (bytes != null) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); IOUtil.writeBinaryResource(bis, out); } } // write out content / gzip or otherwise from the cache } else if (t.getTimeout(wc) != null && t.getTimeout(wc) > 0 && tr != null) { // if the client has the same resource as the one on the server return a 304 // get the If-None-Match header String etag = tr.getContentHash(); String ifNoneMatch = req.getHeader("If-None-Match"); if (etag != null && ifNoneMatch != null && ifNoneMatch.equals(etag)) { resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); if (jcfg.profile()) { profile(wc); } return; } resp.setContentType(tr.getContentType()); if (!jcfg.profile()) { resp.setHeader("ETag", etag); resp.setHeader("Expires", tr.getCacheContext().getExpires()); resp.setHeader("Cache-Control", "public,max-age=" + tr.getCacheContext().getMaxAge()); } if (canGzip && t.gzipTemplate(wc) != null && t.gzipTemplate(wc) == true) { OutputStream out = resp.getOutputStream(); resp.setHeader("Content-Encoding", "gzip"); resp.setHeader("Vary", "Accept-Encoding"); tr.incrementGzipAccessCount(); byte[] bytes = tr.getGZippedContent(); if (bytes != null) { resp.setContentLength(bytes.length); bytesServed = bytes.length; ByteArrayInputStream bis = new ByteArrayInputStream(bytes); IOUtil.writeBinaryResource(bis, out); } } else { OutputStream out = resp.getOutputStream(); tr.incrementAccessCount(); byte[] bytes = tr.getContent().toString().getBytes(); resp.setContentLength(bytes.length); if (bytes != null) { ByteArrayInputStream bis = new ByteArrayInputStream(bytes); bytesServed = bytes.length; IOUtil.writeBinaryResource(bis, out); } } } else { OutputStream out = resp.getOutputStream(); // t.getTemplateResource().incrementAccessCount(); renderEngine.renderTemplate(id, wc, bos); bytesServed = bos.size(); out.write(bos.toByteArray()); } // increment the total template accesses if (t != null) { t.incrementAccessCount(); } if (jcfg.profile()) { profile(wc); } } catch (java.net.SocketException jos) { logger.warning("Got broken pipe. Ignoring..."); return; } finally { if (wc != null) { wc.destroy(); } } long endTime = System.currentTimeMillis(); // add more stats stuff IStat stat = new StatsItem(); stat.setTimestamp(System.currentTimeMillis()); stat.setPath(path); stat.setPathInfo(pathInfo); stat.setRemoteClient(cg.getClientId(req)); stat.setType(StatsItem.types.VIEW); stat.setRequestURI(req.getRequestURI()); stat.setProcessTime(new Long(endTime - iStartTime)); stat.setContentLength(new Long(bytesServed)); stat.setContentType("text/html"); statsManager.add(stat); }
From source file:net.lightbody.bmp.proxy.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {/* www .j a v a 2 s .c om*/ throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }
From source file:org.openqa.jetty.servlet.Dump.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("Dump", this); request.setCharacterEncoding("ISO_8859_1"); getServletContext().setAttribute("Dump", this); String info = request.getPathInfo(); if (info != null && info.endsWith("Exception")) { try {//from w ww .j a v a 2 s .c om throw (Throwable) (Loader.loadClass(this.getClass(), info.substring(1)).newInstance()); } catch (Throwable th) { throw new ServletException(th); } } String redirect = request.getParameter("redirect"); if (redirect != null && redirect.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendRedirect(redirect); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String error = request.getParameter("error"); if (error != null && error.length() > 0) { response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); response.sendError(Integer.parseInt(error)); response.getOutputStream().println("THIS SHOULD NOT BE SEEN!"); return; } String length = request.getParameter("length"); if (length != null && length.length() > 0) { response.setContentLength(Integer.parseInt(length)); } String buffer = request.getParameter("buffer"); if (buffer != null && buffer.length() > 0) response.setBufferSize(Integer.parseInt(buffer)); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); if (info != null && info.indexOf("Locale/") >= 0) { try { String locale_name = info.substring(info.indexOf("Locale/") + 7); Field f = java.util.Locale.class.getField(locale_name); response.setLocale((Locale) f.get(null)); } catch (Exception e) { LogSupport.ignore(log, e); response.setLocale(Locale.getDefault()); } } String cn = request.getParameter("cookie"); String cv = request.getParameter("value"); String v = request.getParameter("version"); if (cn != null && cv != null) { Cookie cookie = new Cookie(cn, cv); cookie.setComment("Cookie from dump servlet"); if (v != null) { cookie.setMaxAge(300); cookie.setPath("/"); cookie.setVersion(Integer.parseInt(v)); } response.addCookie(cookie); } String pi = request.getPathInfo(); if (pi != null && pi.startsWith("/ex")) { OutputStream out = response.getOutputStream(); out.write("</H1>This text should be reset</H1>".getBytes()); if ("/ex0".equals(pi)) throw new ServletException("test ex0", new Throwable()); if ("/ex1".equals(pi)) throw new IOException("test ex1"); if ("/ex2".equals(pi)) throw new UnavailableException("test ex2"); if ("/ex3".equals(pi)) throw new HttpException(501); } PrintWriter pout = response.getWriter(); Page page = null; try { page = new Page(); page.title("Dump Servlet"); page.add(new Heading(1, "Dump Servlet")); Table table = new Table(0).cellPadding(0).cellSpacing(0); page.add(table); table.newRow(); table.addHeading("getMethod: ").cell().right(); table.addCell("" + request.getMethod()); table.newRow(); table.addHeading("getContentLength: ").cell().right(); table.addCell(Integer.toString(request.getContentLength())); table.newRow(); table.addHeading("getContentType: ").cell().right(); table.addCell("" + request.getContentType()); table.newRow(); table.addHeading("getCharacterEncoding: ").cell().right(); table.addCell("" + request.getCharacterEncoding()); table.newRow(); table.addHeading("getRequestURI: ").cell().right(); table.addCell("" + request.getRequestURI()); table.newRow(); table.addHeading("getRequestURL: ").cell().right(); table.addCell("" + request.getRequestURL()); table.newRow(); table.addHeading("getContextPath: ").cell().right(); table.addCell("" + request.getContextPath()); table.newRow(); table.addHeading("getServletPath: ").cell().right(); table.addCell("" + request.getServletPath()); table.newRow(); table.addHeading("getPathInfo: ").cell().right(); table.addCell("" + request.getPathInfo()); table.newRow(); table.addHeading("getPathTranslated: ").cell().right(); table.addCell("" + request.getPathTranslated()); table.newRow(); table.addHeading("getQueryString: ").cell().right(); table.addCell("" + request.getQueryString()); table.newRow(); table.addHeading("getProtocol: ").cell().right(); table.addCell("" + request.getProtocol()); table.newRow(); table.addHeading("getScheme: ").cell().right(); table.addCell("" + request.getScheme()); table.newRow(); table.addHeading("getServerName: ").cell().right(); table.addCell("" + request.getServerName()); table.newRow(); table.addHeading("getServerPort: ").cell().right(); table.addCell("" + Integer.toString(request.getServerPort())); table.newRow(); table.addHeading("getLocalName: ").cell().right(); table.addCell("" + request.getLocalName()); table.newRow(); table.addHeading("getLocalAddr: ").cell().right(); table.addCell("" + request.getLocalAddr()); table.newRow(); table.addHeading("getLocalPort: ").cell().right(); table.addCell("" + Integer.toString(request.getLocalPort())); table.newRow(); table.addHeading("getRemoteUser: ").cell().right(); table.addCell("" + request.getRemoteUser()); table.newRow(); table.addHeading("getRemoteAddr: ").cell().right(); table.addCell("" + request.getRemoteAddr()); table.newRow(); table.addHeading("getRemoteHost: ").cell().right(); table.addCell("" + request.getRemoteHost()); table.newRow(); table.addHeading("getRemotePort: ").cell().right(); table.addCell("" + request.getRemotePort()); table.newRow(); table.addHeading("getRequestedSessionId: ").cell().right(); table.addCell("" + request.getRequestedSessionId()); table.newRow(); table.addHeading("isSecure(): ").cell().right(); table.addCell("" + request.isSecure()); table.newRow(); table.addHeading("isUserInRole(admin): ").cell().right(); table.addCell("" + request.isUserInRole("admin")); table.newRow(); table.addHeading("getLocale: ").cell().right(); table.addCell("" + request.getLocale()); Enumeration locales = request.getLocales(); while (locales.hasMoreElements()) { table.newRow(); table.addHeading("getLocales: ").cell().right(); table.addCell(locales.nextElement()); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Other HTTP Headers") .attribute("COLSPAN", "2").left(); Enumeration h = request.getHeaderNames(); String name; while (h.hasMoreElements()) { name = (String) h.nextElement(); Enumeration h2 = request.getHeaders(name); while (h2.hasMoreElements()) { String hv = (String) h2.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(hv); } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Parameters") .attribute("COLSPAN", "2").left(); h = request.getParameterNames(); while (h.hasMoreElements()) { name = (String) h.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().right(); table.addCell(request.getParameter(name)); String[] values = request.getParameterValues(name); if (values == null) { table.newRow(); table.addHeading(name + " Values: ").cell().right(); table.addCell("NULL!!!!!!!!!"); } else if (values.length > 1) { for (int i = 0; i < values.length; i++) { table.newRow(); table.addHeading(name + "[" + i + "]: ").cell().right(); table.addCell(values[i]); } } } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Cookies").attribute("COLSPAN", "2").left(); Cookie[] cookies = request.getCookies(); for (int i = 0; cookies != null && i < cookies.length; i++) { Cookie cookie = cookies[i]; table.newRow(); table.addHeading(cookie.getName() + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell(cookie.getValue()); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Request Attributes") .attribute("COLSPAN", "2").left(); Enumeration a = request.getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(request.getAttribute(name)) + "</pre>"); } /* ------------------------------------------------------------ */ table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Servlet InitParameters") .attribute("COLSPAN", "2").left(); a = getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context InitParameters") .attribute("COLSPAN", "2").left(); a = getServletContext().getInitParameterNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getInitParameter(name)) + "</pre>"); } table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Context Attributes") .attribute("COLSPAN", "2").left(); a = getServletContext().getAttributeNames(); while (a.hasMoreElements()) { name = (String) a.nextElement(); table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + toString(getServletContext().getAttribute(name)) + "</pre>"); } if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data") && request.getContentLength() < 1000000) { MultiPartRequest multi = new MultiPartRequest(request); String[] parts = multi.getPartNames(); table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Multi-part content") .attribute("COLSPAN", "2").left(); for (int p = 0; p < parts.length; p++) { name = parts[p]; table.newRow(); table.addHeading(name + ": ").cell().attribute("VALIGN", "TOP").right(); table.addCell("<pre>" + multi.getString(parts[p]) + "</pre>"); } } String res = request.getParameter("resource"); if (res != null && res.length() > 0) { table.newRow(); table.newHeading().cell().nest(new Font(2, true)).add("<BR>Get Resource: " + res) .attribute("COLSPAN", "2").left(); table.newRow(); table.addHeading("this.getClass(): ").cell().right(); table.addCell("" + this.getClass().getResource(res)); table.newRow(); table.addHeading("this.getClass().getClassLoader(): ").cell().right(); table.addCell("" + this.getClass().getClassLoader().getResource(res)); table.newRow(); table.addHeading("Thread.currentThread().getContextClassLoader(): ").cell().right(); table.addCell("" + Thread.currentThread().getContextClassLoader().getResource(res)); table.newRow(); table.addHeading("getServletContext(): ").cell().right(); try { table.addCell("" + getServletContext().getResource(res)); } catch (Exception e) { table.addCell("" + e); } } /* ------------------------------------------------------------ */ page.add(Break.para); page.add(new Heading(1, "Request Wrappers")); ServletRequest rw = request; int w = 0; while (rw != null) { page.add((w++) + ": " + rw.getClass().getName() + "<br/>"); if (rw instanceof HttpServletRequestWrapper) rw = ((HttpServletRequestWrapper) rw).getRequest(); else if (rw instanceof ServletRequestWrapper) rw = ((ServletRequestWrapper) rw).getRequest(); else rw = null; } page.add(Break.para); page.add(new Heading(1, "International Characters")); page.add("Directly encoced: Drst<br/>"); page.add("HTML reference: Dürst<br/>"); page.add("Decimal (252) 8859-1: Dürst<br/>"); page.add("Hex (xFC) 8859-1: Dürst<br/>"); page.add( "Javascript unicode (00FC) : <script language='javascript'>document.write(\"D\u00FCrst\");</script><br/>"); page.add(Break.para); page.add(new Heading(1, "Form to generate GET content")); TableForm tf = new TableForm(response.encodeURL(getURI(request))); tf.method("GET"); tf.addTextField("TextField", "TextField", 20, "value"); tf.addButton("Action", "Submit"); page.add(tf); page.add(Break.para); page.add(new Heading(1, "Form to generate POST content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("TextField", "TextField", 20, "value"); Select select = tf.addSelect("Select", "Select", true, 3); select.add("ValueA"); select.add("ValueB1,ValueB2"); select.add("ValueC"); tf.addButton("Action", "Submit"); page.add(tf); page.add(new Heading(1, "Form to upload content")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.attribute("enctype", "multipart/form-data"); tf.addFileField("file", "file"); tf.addButton("Upload", "Upload"); page.add(tf); page.add(new Heading(1, "Form to get Resource")); tf = new TableForm(response.encodeURL(getURI(request))); tf.method("POST"); tf.addTextField("resource", "resource", 20, ""); tf.addButton("Action", "getResource"); page.add(tf); } catch (Exception e) { log.warn(LogSupport.EXCEPTION, e); } page.write(pout); String data = request.getParameter("data"); if (data != null && data.length() > 0) { int d = Integer.parseInt(data); while (d > 0) { pout.println("1234567890123456789012345678901234567890123456789\n"); d = d - 50; } } pout.close(); if (pi != null) { if ("/ex4".equals(pi)) throw new ServletException("test ex4", new Throwable()); if ("/ex5".equals(pi)) throw new IOException("test ex5"); if ("/ex6".equals(pi)) throw new UnavailableException("test ex6"); if ("/ex7".equals(pi)) throw new HttpException(501); } request.getInputStream().close(); }