List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:org.testdwr.plain.Test.java
@SuppressWarnings("unchecked") public Map<String, String> listHeaders(HttpServletRequest request) { Map<String, String> reply = new HashMap<String, String>(); Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = request.getHeaders(name); StringBuilder value = new StringBuilder(); while (values.hasMoreElements()) { String single = values.nextElement(); value.append(single);// w w w .j ava 2s.com if (values.hasMoreElements()) { value.append(", "); } } reply.put(name, value.toString()); } return reply; }
From source file:airlift.servlet.rest.RestServlet.java
/** * Apply security checks./*w ww . j a va 2 s . com*/ * * @param _request the _request * @param _response the _response * @param _method the _method * @return the rest context */ protected RestContext applySecurityChecks(HttpServletRequest _request, HttpServletResponse _response, Method _method) { //Deal with COR headers _response.addHeader("Access-Control-Allow-Origin", "*"); _response.addHeader("Access-Control-Allow-Headers", "Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control"); _response.addHeader("Access-Control-Allow-Credentials", "true"); _response.addHeader("Access-Control-Max-Age", "86400"); _response.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS"); java.util.Enumeration<String> headerNames = _request.getHeaderNames(); logInfo("reporting request header info ..."); while (headerNames.hasMoreElements() == true) { String headerName = headerNames.nextElement(); logInfo(headerName + ":" + _request.getHeader(headerName)); } String namespace = this.getServletConfig().getInitParameter("a.namespace"); if (namespace != null && org.apache.commons.lang.StringUtils.isWhitespace(namespace) == false) { com.google.appengine.api.NamespaceManager.set(namespace); } com.google.appengine.api.quota.QuotaService quotaService = com.google.appengine.api.quota.QuotaServiceFactory .getQuotaService(); logInfo("RestServlet START " + quotaService.getCpuTimeInMegaCycles()); java.util.List<String> acceptValueList = new java.util.ArrayList<String>(); java.util.Enumeration<String> acceptHeaderValues = _request.getHeaders("Accept"); while (acceptHeaderValues.hasMoreElements() == true) { String acceptHeaderValue = acceptHeaderValues.nextElement(); String[] tokenArray = acceptHeaderValue.split(","); for (int i = 0; i < tokenArray.length; i++) { //For now we ignore q and other parameters String acceptValue = tokenArray[i].replaceAll(";.*$", ""); if (acceptValue.contains("*") == false) { acceptValueList.add(acceptValue.toLowerCase()); } } } String method = determineMethod(_method, _request); Map uriParameterMap = new java.util.HashMap(); RestContext restContext = prepareRestContext(method, acceptValueList, _request, uriParameterMap, getServletName()); if (restContext.getHandlerPathList().isEmpty() == true) { sendCodedPage("404", "Not Found", _response); } UserService userService = getUserService(_request, restContext, _response); AbstractUser user = userService.getCurrentUser(); RestfulSecurityContext securityContext = new RestfulSecurityContext(userService.getUserKind(), this.cachingContextMap.get("user.session"), this.getServletConfig().getInitParameter("a.roleset.manager"), "true".equalsIgnoreCase(this.getServletConfig().getInitParameter("a.verbose.log"))); restContext.setSecurityContext(securityContext); securityContext.populate(user); restContext.setUser(user); boolean success = allowed(user, restContext, securityContext); logInfo("User is: " + user); if (!success && user == null) { boolean loginSuccessful = requestLogin(_request, _response, userService); if (loginSuccessful == false) { sendCodedPage("401", "UnAuthorized - you must log in to " + method + " access this resource.", _response); } } else if (!success && user != null) { sendCodedPage("401", "UnAuthorized - User " + user.getEmail() + " does not have " + method + " access to this resource. You may <a href=\"" + userService.createLogoutURL(_request.getRequestURI()) + "\">logout</a> and login as another user.", _response); } else if (success && timedOut(user) == true) { logInfo("Timed out user is now: " + user); boolean logoutSuccessful = logUserOut(_request, _response, userService); if (logoutSuccessful == false) { logInfo("Time out incepted log out failed"); sendCodedPage("408", "Request Timeout", _response); } } else if (success) { //User is not timed out and the user can access this page. //Not being timed out means that your time out date time is null //or your time out date time is greater than the current date //time. proceedToProcessRequest(user, securityContext, _request, _response, method, restContext, uriParameterMap); } long totalMegaCycles = quotaService.getCpuTimeInMegaCycles(); logInfo("RestServlet Megacycles: " + totalMegaCycles); logInfo("RestServlet CPU Seconds: " + quotaService.convertMegacyclesToCpuSeconds(totalMegaCycles)); return restContext; }
From source file:org.deegree.services.controller.OGCFrontController.java
private void logHeaders(HttpServletRequest request) { if (LOG.isDebugEnabled()) { LOG.debug("HTTP headers:"); Enumeration<String> headerEnum = request.getHeaderNames(); while (headerEnum.hasMoreElements()) { String headerName = headerEnum.nextElement(); LOG.debug("- " + headerName + "='" + request.getHeader(headerName) + "'"); }/*from w w w . ja v a 2s . c om*/ } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
/** * Create Amazon V2 signature. Reference: * http://docs.aws.amazon.com/general/latest/gr/signature-version-2.html *///from ww w. j av a2 s . com private static String createAuthorizationSignature(HttpServletRequest request, String uri, String credential) { // sort Amazon headers SortedSetMultimap<String, String> canonicalizedHeaders = TreeMultimap.create(); for (String headerName : Collections.list(request.getHeaderNames())) { Collection<String> headerValues = Collections.list(request.getHeaders(headerName)); headerName = headerName.toLowerCase(); if (!headerName.startsWith("x-amz-")) { continue; } if (headerValues.isEmpty()) { canonicalizedHeaders.put(headerName, ""); } for (String headerValue : headerValues) { canonicalizedHeaders.put(headerName, Strings.nullToEmpty(headerValue)); } } // build string to sign StringBuilder builder = new StringBuilder().append(request.getMethod()).append('\n') .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_MD5))).append('\n') .append(Strings.nullToEmpty(request.getHeader(HttpHeaders.CONTENT_TYPE))).append('\n'); String expires = request.getParameter("Expires"); if (expires != null) { builder.append(expires); } else if (!canonicalizedHeaders.containsKey("x-amz-date")) { builder.append(request.getHeader(HttpHeaders.DATE)); } builder.append('\n'); for (Map.Entry<String, String> entry : canonicalizedHeaders.entries()) { builder.append(entry.getKey()).append(':').append(entry.getValue()).append('\n'); } builder.append(uri); char separator = '?'; List<String> subresources = Collections.list(request.getParameterNames()); Collections.sort(subresources); for (String subresource : subresources) { if (SIGNED_SUBRESOURCES.contains(subresource)) { builder.append(separator).append(subresource); String value = request.getParameter(subresource); if (!"".equals(value)) { builder.append('=').append(value); } separator = '&'; } } String stringToSign = builder.toString(); logger.trace("stringToSign: {}", stringToSign); // sign string Mac mac; try { mac = Mac.getInstance("HmacSHA1"); mac.init(new SecretKeySpec(credential.getBytes(StandardCharsets.UTF_8), "HmacSHA1")); } catch (InvalidKeyException | NoSuchAlgorithmException e) { throw new RuntimeException(e); } return BaseEncoding.base64().encode(mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))); }
From source file:org.apache.maven.plugins.site.AuthAsyncProxyServlet.java
/** {@inheritDoc} */ public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; log.info("handle "); if (this.authentications != null && !this.authentications.isEmpty()) { String proxyAuthorization = request.getHeader("Proxy-Authorization"); if (proxyAuthorization != null && proxyAuthorization.startsWith("Basic ")) { String proxyAuth = proxyAuthorization.substring(6); String authorization = B64Code.decode(proxyAuth); String[] authTokens = authorization.split(":"); String user = authTokens[0]; String password = authTokens[1]; if (this.authentications.get(user) == null) { throw new IllegalArgumentException(user + " not found in the map!"); }// www . ja v a 2 s. c o m if (sleepTime > 0) { try { Thread.sleep(sleepTime); } catch (InterruptedException e) { // nop } } String authPass = this.authentications.get(user); if (password.equals(authPass)) { String targetPath = request.getServletPath(); HttpRequest rq = new HttpRequest(); rq.method = request.getMethod(); rq.path = targetPath; @SuppressWarnings("rawtypes") Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); rq.headers.put(name, request.getHeader(name)); } httpRequests.add(rq); if (request.getMethod().equalsIgnoreCase("PUT") && targetPath != null) { File targetFile = new File(siteTargetPath, targetPath); log.info("writing file " + targetFile.getPath()); FileUtils.writeByteArrayToFile(targetFile, IOUtils.toByteArray(request.getInputStream())); } //PrintWriter writer = response.getWriter(); response.setStatus(HttpServletResponse.SC_OK); return; } } // Proxy-Authenticate Basic realm="CCProxy Authorization" response.addHeader("Proxy-Authenticate", "Basic realm=\"Jetty Proxy Authorization\""); response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); return; } super.service(req, res); }
From source file:es.juntadeandalucia.mapea.proxy.ProxyRedirect.java
/*************************************************************************** * Process the HTTP Post request//from www . j av a 2s .co m ***************************************************************************/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { boolean checkedContent = false; boolean legend = false; String strErrorMessage = ""; String serverUrl = request.getParameter("url"); log.info("POST param serverUrl: " + serverUrl); if (serverUrl.startsWith("legend")) { serverUrl = serverUrl.replace("legend", ""); serverUrl = serverUrl.replace("?", "&"); serverUrl = serverUrl.replaceFirst("&", "?"); legend = true; } serverUrl = checkTypeRequest(serverUrl); // log.info("serverUrl ckecked: " + serverUrl); if (!serverUrl.equals("ERROR")) { if (serverUrl.startsWith("http://") || serverUrl.startsWith("https://")) { PostMethod httppost = null; try { if (log.isDebugEnabled()) { Enumeration<?> e = request.getHeaderNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = request.getHeader(name); log.debug("request header:" + name + ":" + value); } } HttpClient client = new HttpClient(); httppost = new PostMethod(serverUrl); // PATH httppost.setDoAuthentication(false); httppost.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // FIN_PATH // PATH_MAPEAEDITA_SECURITY - AP // PATCH_TICKET_MJM-20112405-POST String authorizationValue = request.getHeader(AUTHORIZATION); // ADD_SECURITY_20091210 if (authorizationValue == null) { // The 'Authorization' header must be in this form -> // Authorization: Basic <encodedLogin> // 'encodedLogin' is a string in the form 'user:pass' // that has been encoded by way of the Base64 algorithm. // More info on this can be found at // http://en.wikipedia.org/wiki/Basic_access_authentication String user = (String) request.getSession().getAttribute("user"); String pass = (String) request.getSession().getAttribute("pass"); if (user != null && pass != null) { String userAndPass = user + ":" + pass; String encodedLogin = new String( org.apache.commons.codec.binary.Base64.encodeBase64(userAndPass.getBytes())); httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin); } else { // MJM - 20110520 String ticketParameter = request.getParameter("ticket"); if (ticketParameter != null) { ticketParameter = ticketParameter.trim(); if (!ticketParameter.isEmpty()) { Ticket ticket = TicketFactory.createInstance(); try { Map<String, String> props = ticket.getProperties(ticketParameter); user = props.get("user"); pass = props.get("pass"); String userAndPass = user + ":" + pass; String encodedLogin = new String(org.apache.commons.codec.binary.Base64 .encodeBase64(userAndPass.getBytes())); httppost.addRequestHeader(AUTHORIZATION, "Basic " + encodedLogin); } catch (Exception e) { log.info("-------------------------------------------"); log.info("EXCEPCTION THROWED BY PROXYREDIRECT CLASS"); log.info("METHOD: doPost"); log.info("TICKET VALUE: " + ticketParameter); log.info("-------------------------------------------"); } } } } } else { httppost.addRequestHeader(AUTHORIZATION, authorizationValue); } // FIN_PATH_TICKET_MJM-20112405-POST // FIN_PATH_MAPEAEDITA_SECURITY - AP String body = inputStreamAsString(request.getInputStream()); StringRequestEntity bodyEntity = new StringRequestEntity(body, null, null); if (0 == httppost.getParameters().length) { log.debug("No Name/Value pairs found ... pushing as received"); // PATCH httppost.setRequestEntity(bodyEntity); // PATCH } if (log.isDebugEnabled()) { log.debug("Body = " + body); NameValuePair[] nameValuePairs = httppost.getParameters(); log.debug("NameValuePairs found: " + nameValuePairs.length); for (int i = 0; i < nameValuePairs.length; ++i) { log.debug("parameters:" + nameValuePairs[i].toString()); } } if (!legend) client.getParams().setParameter("http.protocol.content-charset", "UTF-8"); if (soap) { httppost.addRequestHeader("SOAPAction", serverUrl); } client.executeMethod(httppost); // PATH_FOLLOW_REDIRECT_POST int j = 0; String redirectLocation; Header locationHeader = httppost.getResponseHeader("location"); while (locationHeader != null && j < numMaxRedirects) { redirectLocation = locationHeader.getValue(); // AGG 20111304 Aadimos el cuerpo de la peticin POST a // la nueva peticin redirigida // String bodyPost = httppost.getResponseBodyAsString(); StringRequestEntity bodyEntityPost = new StringRequestEntity(body, null, null); httppost.releaseConnection(); httppost = new PostMethod(redirectLocation); // AGG 20110912 Aadidas cabeceras peticin SOAP if (redirectLocation.toLowerCase().contains("wsdl")) { redirectLocation = serverUrl.replace("?wsdl", ""); httppost.addRequestHeader("SOAPAction", redirectLocation); httppost.addRequestHeader("Content-type", "text/xml"); } httppost.setRequestEntity(bodyEntityPost); client.executeMethod(httppost); locationHeader = httppost.getResponseHeader("location"); j++; } log.info("Number of followed redirections: " + j); if (locationHeader != null && j == numMaxRedirects) { log.error("The maximum number of redirects (" + numMaxRedirects + ") is exceed."); } // FIN_PATH_FOLLOW_REDIRECT_POST if (log.isDebugEnabled()) { Header[] responseHeaders = httppost.getResponseHeaders(); for (int i = 0; i < responseHeaders.length; ++i) { String headerName = responseHeaders[i].getName(); String headerValue = responseHeaders[i].getValue(); log.debug("responseHeaders:" + headerName + "=" + headerValue); } } // dump response to out if (httppost.getStatusCode() == HttpStatus.SC_OK) { // PATH_SECURITY_PROXY - AG Header[] respHeaders = httppost.getResponseHeaders(); int compSize = httppost.getResponseBody().length; ArrayList<Header> headerList = new ArrayList<Header>(Arrays.asList(respHeaders)); String headersString = headerList.toString(); checkedContent = checkContent(headersString, compSize, serverUrl); // FIN_PATH_SECURITY_PROXY - AG if (checkedContent == true) { /* * checks if it has requested an getfeatureinfo to modify the response content * type. */ String requesteredUrl = request.getParameter("url"); if (GETINFO_PLAIN_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/plain"); } else if (GETINFO_GML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("application/gml+xml"); } else if (GETINFO_HTML_REGEX.matcher(requesteredUrl).matches()) { response.setContentType("text/html"); } else if (requesteredUrl.toLowerCase().contains("mapeaop=geosearch") || requesteredUrl.toLowerCase().contains("mapeaop=geoprint")) { response.setContentType("application/json"); } else { response.setContentType("text/xml"); } if (legend) { String responseBody = httppost.getResponseBodyAsString(); if (responseBody.contains("ServiceExceptionReport") && serverUrl.contains("LegendGraphic")) { response.sendRedirect("Componente/img/blank.gif"); } else { response.setContentLength(responseBody.length()); PrintWriter out = response.getWriter(); out.print(responseBody); response.flushBuffer(); } } else { // Patch_AGG 20112505 Prevents IE cache if (request.getProtocol().compareTo("HTTP/1.0") == 0) { response.setHeader("Pragma", "no-cache"); } else if (request.getProtocol().compareTo("HTTP/1.1") == 0) { response.setHeader("Cache-Control", "no-cache"); } response.setDateHeader("Expires", -1); // END patch // Copy request to response InputStream st = httppost.getResponseBodyAsStream(); final ServletOutputStream sos = response.getOutputStream(); IOUtils.copy(st, sos); } } else { strErrorMessage += errorType; log.error(strErrorMessage); } } else if (httppost.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { response.setStatus(HttpStatus.SC_UNAUTHORIZED); response.addHeader(WWW_AUTHENTICATE, httppost.getResponseHeader(WWW_AUTHENTICATE).getValue()); } else { strErrorMessage = "Unexpected failure: ".concat(httppost.getStatusLine().toString()) .concat(" ").concat(httppost.getResponseBodyAsString()); log.error("Unexpected failure: " + httppost.getStatusLine().toString()); } httppost.releaseConnection(); // AGG 20110927 Avoid Throwable (change it with exceptions) } catch (Exception e) { log.error("Error al tratar el contenido de la peticion: " + e.getMessage(), e); } finally { if (httppost != null) { httppost.releaseConnection(); } } } else { strErrorMessage += "Only HTTP(S) protocol supported"; log.error("Only HTTP(S) protocol supported"); // throw new // ServletException("only HTTP(S) protocol supported"); } } // There are errors. if (!strErrorMessage.equals("") || serverUrl.equals("ERROR")) { if (strErrorMessage.equals("") == true) { strErrorMessage = "Error en el parametro url de entrada"; } // String errorXML = strErrorMessage; String errorXML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><descripcion>" + strErrorMessage + "</descripcion></error>"; response.setContentType("text/xml"); try { PrintWriter out = response.getWriter(); out.print(errorXML); response.flushBuffer(); } catch (Exception e) { log.error(e); } } log.info("-------- End POST method --------"); }
From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { monitor.fireOnRequest(request, response); if (response.isCommitted()) return;/* w w w.j a v a2 s . c om*/ ExtendedHttpMethod method; HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getMethod().equals("GET")) method = new ExtendedGetMethod(); else method = new ExtendedPostMethod(); method.setDecompress(false); // for this create ui server and port, properties. JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project); capturedData.setRequestHost(httpRequest.getServerName()); capturedData.setRequestMethod(httpRequest.getMethod()); capturedData.setRequestHeader(httpRequest); capturedData.setHttpRequestParameters(httpRequest); capturedData.setTargetURL(httpRequest.getRequestURL().toString()); CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream()); // check connection header String connectionHeader = httpRequest.getHeader("Connection"); if (connectionHeader != null) { connectionHeader = connectionHeader.toLowerCase(); if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0) connectionHeader = null; } // copy headers boolean xForwardedFor = false; @SuppressWarnings("unused") long contentLength = -1; Enumeration<?> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hdr = (String) headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if (dontProxyHeaders.contains(lhdr)) continue; if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) contentLength = request.getContentLength(); Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { method.setRequestHeader(lhdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers method.setRequestHeader("Via", "SoapUI Monitor"); if (!xForwardedFor) method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr()); if (method instanceof ExtendedPostMethod) ((ExtendedPostMethod) method) .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType())); HostConfiguration hostConfiguration = new HostConfiguration(); StringBuffer url = new StringBuffer("http://"); url.append(httpRequest.getServerName()); if (httpRequest.getServerPort() != 80) url.append(":" + httpRequest.getServerPort()); if (httpRequest.getServletPath() != null) { url.append(httpRequest.getServletPath()); method.setPath(httpRequest.getServletPath()); if (httpRequest.getQueryString() != null) { url.append("?" + httpRequest.getQueryString()); method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString()); } } hostConfiguration.setHost(new URI(url.toString(), true)); // SoapUI.log("PROXY to:" + url); monitor.fireBeforeProxy(request, response, method, hostConfiguration); if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) { if (httpState == null) httpState = new HttpState(); HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState); } else { HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method); } // wait for transaction to end and store it. capturedData.stopCapture(); capturedData.setRequest(capture.getCapturedData()); capturedData.setRawResponseBody(method.getResponseBody()); capturedData.setResponseHeader(method); capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture)); capturedData.setRawResponseData( getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody())); capturedData.setResponseContent(new String(method.getDecompressedResponseBody())); monitor.fireAfterProxy(request, response, method, capturedData); if (!response.isCommitted()) { StringToStringsMap responseHeaders = capturedData.getResponseHeaders(); // capturedData = null; // copy headers to response HttpServletResponse httpResponse = (HttpServletResponse) response; for (String name : responseHeaders.keySet()) { for (String header : responseHeaders.get(name)) httpResponse.addHeader(name, header); } IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream()); } synchronized (this) { if (checkContentType(method)) { monitor.addMessageExchange(capturedData); } } }
From source file:com.mx.nibble.middleware.web.util.FileUploadOLD.java
public String execute() throws Exception { //ActionContext ac = invocation.getInvocationContext(); HttpServletResponse response = ServletActionContext.getResponse(); // MultiPartRequestWrapper multipartRequest = ((MultiPartRequestWrapper)ServletActionContext.getRequest()); HttpServletRequest multipartRequest = ServletActionContext.getRequest(); List<FileItem> items2 = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(multipartRequest); System.out.println("TAMAO ITEMS " + items2.size()); System.out.println("Check that we have a file upload request"); boolean isMultipart = ServletFileUpload.isMultipartContent(multipartRequest); System.out.println("isMultipart: " + isMultipart); String ourTempDirectory = "/opt/erp/import/obras/"; byte[] cr = { 13 }; byte[] lf = { 10 }; String CR = new String(cr); String LF = new String(lf); String CRLF = CR + LF;/*from www. j av a 2 s. c o m*/ System.out.println("Before a LF=chr(10)" + LF + "Before a CR=chr(13)" + CR + "Before a CRLF" + CRLF); //Initialization for chunk management. boolean bLastChunk = false; int numChunk = 0; //CAN BE OVERRIDEN BY THE postURL PARAMETER: if error=true is passed as a parameter on the URL boolean generateError = false; boolean generateWarning = false; boolean sendRequest = false; response.setContentType("text/plain"); java.util.Enumeration<String> headers = multipartRequest.getHeaderNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Headers of the received request:"); while (headers.hasMoreElements()) { String header = headers.nextElement(); System.out.println("[parseRequest.jsp] " + header + ": " + multipartRequest.getHeader(header)); } System.out.println("[parseRequest.jsp] ------------------------------ "); try { System.out.println(" Get URL Parameters."); Enumeration paraNames = multipartRequest.getParameterNames(); System.out.println("[parseRequest.jsp] ------------------------------ "); System.out.println("[parseRequest.jsp] Parameters: "); String pname; String pvalue; while (paraNames.hasMoreElements()) { pname = (String) paraNames.nextElement(); pvalue = multipartRequest.getParameter(pname); System.out.println("[parseRequest.jsp] " + pname + " = " + pvalue); if (pname.equals("jufinal")) { System.out.println("pname.equals(\"jufinal\")"); bLastChunk = pvalue.equals("1"); } else if (pname.equals("jupart")) { System.out.println("pname.equals(\"jupart\")"); numChunk = Integer.parseInt(pvalue); } //For debug convenience, putting error=true as a URL parameter, will generate an error //in this response. if (pname.equals("error") && pvalue.equals("true")) { generateError = true; } //For debug convenience, putting warning=true as a URL parameter, will generate a warning //in this response. if (pname.equals("warning") && pvalue.equals("true")) { generateWarning = true; } //For debug convenience, putting readRequest=true as a URL parameter, will send back the request content //into the response of this page. if (pname.equals("sendRequest") && pvalue.equals("true")) { sendRequest = true; } } System.out.println("[parseRequest.jsp] ------------------------------ "); int ourMaxMemorySize = 10000000; int ourMaxRequestSize = 2000000000; /////////////////////////////////////////////////////////////////////////////////////////////////////// //The code below is directly taken from the jakarta fileupload common classes //All informations, and download, available here : http://jakarta.apache.org/commons/fileupload/ /////////////////////////////////////////////////////////////////////////////////////////////////////// // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // Set factory constraints factory.setSizeThreshold(ourMaxMemorySize); factory.setRepository(new File(ourTempDirectory)); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // Set overall request size constraint upload.setSizeMax(ourMaxRequestSize); // Parse the request if (sendRequest) { //For debug only. Should be removed for production systems. System.out.println( "[parseRequest.jsp] ==========================================================================="); System.out.println("[parseRequest.jsp] Sending the received request content: "); InputStream is = multipartRequest.getInputStream(); int c; while ((c = is.read()) >= 0) { System.out.write(c); } //while is.close(); System.out.println( "[parseRequest.jsp] ==========================================================================="); } else if (!multipartRequest.getContentType().startsWith("multipart/form-data")) { System.out.println("[parseRequest.jsp] No parsing of uploaded file: content type is " + multipartRequest.getContentType()); } else { List /* FileItem */ items = upload.parseRequest(multipartRequest); // Process the uploaded items Iterator iter = items.iterator(); FileItem fileItem; File fout; System.out.println("[parseRequest.jsp] Let's read the sent data (" + items.size() + " items)"); while (iter.hasNext()) { fileItem = (FileItem) iter.next(); if (fileItem.isFormField()) { System.out.println("[parseRequest.jsp] (form field) " + fileItem.getFieldName() + " = " + fileItem.getString()); //If we receive the md5sum parameter, we've read finished to read the current file. It's not //a very good (end of file) signal. Will be better in the future ... probably ! //Let's put a separator, to make output easier to read. if (fileItem.getFieldName().equals("md5sum[]")) { System.out.println("[parseRequest.jsp] ------------------------------ "); } } else { //Ok, we've got a file. Let's process it. //Again, for all informations of what is exactly a FileItem, please //have a look to http://jakarta.apache.org/commons/fileupload/ // System.out.println("[parseRequest.jsp] FieldName: " + fileItem.getFieldName()); System.out.println("[parseRequest.jsp] File Name: " + fileItem.getName()); System.out.println("[parseRequest.jsp] ContentType: " + fileItem.getContentType()); System.out.println("[parseRequest.jsp] Size (Bytes): " + fileItem.getSize()); //If we are in chunk mode, we add ".partN" at the end of the file, where N is the chunk number. String uploadedFilename = fileItem.getName() + (numChunk > 0 ? ".part" + numChunk : ""); fout = new File(ourTempDirectory + (new File(uploadedFilename)).getName()); System.out.println("[parseRequest.jsp] File Out: " + fout.toString()); System.out.println(" write the file"); fileItem.write(fout); ////////////////////////////////////////////////////////////////////////////////////// System.out.println( " Chunk management: if it was the last chunk, let's recover the complete file"); System.out.println(" by concatenating all chunk parts."); // if (bLastChunk) { System.out.println( "[parseRequest.jsp] Last chunk received: let's rebuild the complete file (" + fileItem.getName() + ")"); //First: construct the final filename. FileInputStream fis; FileOutputStream fos = new FileOutputStream(ourTempDirectory + fileItem.getName()); int nbBytes; byte[] byteBuff = new byte[1024]; String filename; for (int i = 1; i <= numChunk; i += 1) { filename = fileItem.getName() + ".part" + i; System.out.println("[parseRequest.jsp] " + " Concatenating " + filename); fis = new FileInputStream(ourTempDirectory + filename); while ((nbBytes = fis.read(byteBuff)) >= 0) { //out.println("[parseRequest.jsp] " + " Nb bytes read: " + nbBytes); fos.write(byteBuff, 0, nbBytes); } fis.close(); } fos.close(); } // End of chunk management ////////////////////////////////////////////////////////////////////////////////////// fileItem.delete(); } } //while } if (generateWarning) { System.out.println("WARNING: just a warning message.\\nOn two lines!"); } System.out.println("[parseRequest.jsp] " + "Let's write a status, to finish the server response :"); //Let's wait a little, to simulate the server time to manage the file. Thread.sleep(500); //Do you want to test a successful upload, or the way the applet reacts to an error ? if (generateError) { System.out.println( "ERROR: this is a test error (forced in /wwwroot/pages/parseRequest.jsp).\\nHere is a second line!"); } else { System.out.println("SUCCESS"); //out.println(" <span class=\"cpg_user_message\">Il y eu une erreur lors de l'excution de la requte</span>"); } System.out.println("[parseRequest.jsp] " + "End of server treatment "); } catch (Exception e) { System.out.println(""); System.out.println("ERROR: Exception e = " + e.toString()); System.out.println(""); } return SUCCESS; }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {/*from ww w . j a va 2 s. c o m*/ URL url = new URL(uri); 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); } // 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)) 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.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) 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); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }