List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:org.apache.openaz.xacml.rest.XACMLPdpServlet.java
protected void doPutConfig(String config, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w w w .jav a 2s . co m*/ // prevent multiple configuration changes from stacking up if (XACMLPdpServlet.queue.remainingCapacity() <= 0) { logger.error("Queue capacity reached"); response.sendError(HttpServletResponse.SC_CONFLICT, "Multiple configuration changes waiting processing."); return; } // // Read the properties data into an object. // Properties newProperties = new Properties(); newProperties.load(request.getInputStream()); // should have something in the request if (newProperties.size() == 0) { logger.error("No properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT must contain at least one property"); return; } // // Which set of properties are they sending us? Whatever they send gets // put on the queue (if there is room). // if (config.equals("policies")) { newProperties = XACMLProperties.getPolicyProperties(newProperties, true); if (newProperties.size() == 0) { logger.error("No policy properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=policies must contain at least one policy property"); return; } XACMLPdpServlet.queue.offer(new PutRequest(newProperties, null)); } else if (config.equals("pips")) { newProperties = XACMLProperties.getPipProperties(newProperties); if (newProperties.size() == 0) { logger.error("No pips properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=pips must contain at least one pip property"); return; } XACMLPdpServlet.queue.offer(new PutRequest(null, newProperties)); } else if (config.equals("all")) { Properties newPolicyProperties = XACMLProperties.getPolicyProperties(newProperties, true); if (newPolicyProperties.size() == 0) { logger.error("No policy properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one policy property"); return; } Properties newPipProperties = XACMLProperties.getPipProperties(newProperties); if (newPipProperties.size() == 0) { logger.error("No pips properties in PUT"); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "PUT with cache=all must contain at least one pip property"); return; } XACMLPdpServlet.queue.offer(new PutRequest(newPolicyProperties, newPipProperties)); } else { // // Invalid value // logger.error("Invalid config value: " + config); response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Config must be one of 'policies', 'pips', 'all'"); return; } } catch (Exception e) { logger.error("Failed to process new configuration.", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } }
From source file:com.cloud.bridge.service.controller.s3.S3BucketAction.java
public void executePutBucket(HttpServletRequest request, HttpServletResponse response) throws IOException { int contentLength = request.getContentLength(); Object objectInContent = null; if (contentLength > 0) { InputStream is = null;/*from w ww .j a va2s. c o m*/ try { is = request.getInputStream(); String xml = StringHelper.stringFromStream(is); Class.forName("com.cloud.bridge.service.core.s3.S3CreateBucketConfiguration"); XSerializer serializer = new XSerializer(new XSerializerXmlAdapter()); objectInContent = serializer.serializeFrom(xml); if (objectInContent != null && !(objectInContent instanceof S3CreateBucketConfiguration)) { throw new InvalidRequestContentException("Invalid request content in create-bucket: " + xml); } is.close(); } catch (IOException e) { logger.error("Unable to read request data due to " + e.getMessage(), e); throw new NetworkIOException(e); } catch (ClassNotFoundException e) { logger.error("In a normal world this should never never happen:" + e.getMessage(), e); throw new RuntimeException("A required class was not found in the classpath:" + e.getMessage()); } finally { if (is != null) is.close(); } } S3CreateBucketRequest engineRequest = new S3CreateBucketRequest(); engineRequest.setBucketName((String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY)); engineRequest.setConfig((S3CreateBucketConfiguration) objectInContent); try { S3CreateBucketResponse engineResponse = ServiceProvider.getInstance().getS3Engine() .handleRequest(engineRequest); response.addHeader("Location", "/" + engineResponse.getBucketName()); response.setContentLength(0); response.setStatus(200); response.flushBuffer(); } catch (ObjectAlreadyExistsException oaee) { response.setStatus(409); String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> <Error><Code>OperationAborted</Code><Message>A conflicting conditional operation is currently in progress against this resource. Please try again..</Message>"; response.setContentType("text/xml; charset=UTF-8"); S3RestServlet.endResponse(response, xml.toString()); } }
From source file:org.openqa.grid.internal.TestSession.java
private HttpRequest prepareProxyRequest(HttpServletRequest request /*, ForwardConfiguration config*/) throws IOException { URL remoteURL = slot.getRemoteURL(); String pathSpec = request.getServletPath() + request.getContextPath(); String path = request.getRequestURI(); if (!path.startsWith(pathSpec)) { throw new IllegalStateException("Expected path " + path + " to start with pathSpec " + pathSpec); }//from w w w . j ava2 s . c o m String end = path.substring(pathSpec.length()); String ok = remoteURL + end; if (request.getQueryString() != null) { ok += "?" + request.getQueryString(); } String uri = new URL(remoteURL, ok).toExternalForm(); InputStream body = null; if (request.getContentLength() > 0 || request.getHeader("Transfer-Encoding") != null) { body = request.getInputStream(); } HttpRequest proxyRequest; if (body != null) { BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(request.getMethod(), uri); r.setEntity(new InputStreamEntity(body, request.getContentLength())); proxyRequest = r; } else { proxyRequest = new BasicHttpRequest(request.getMethod(), uri); } for (Enumeration<?> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = (String) e.nextElement(); if ("Content-Length".equalsIgnoreCase(headerName)) { continue; // already set } proxyRequest.setHeader(headerName, request.getHeader(headerName)); } return proxyRequest; }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data elements from an input stream. This handles a typical ajax * call with either name/value pairs (typical form submit style) or * serialised DC//from www. ja v a 2 s . c o m * * @param req * @param hasSerializedDc * is there a field called data that has the entire dc serialized * in it? This is typically how an Exility client sends data * @param inData * @throws ExilityException */ private void extractSerializedData(HttpServletRequest req, boolean hasSerializedDc, ServiceData inData) throws ExilityException { try { // Is this the best way to read> I am sure we should be able to read // better than byte-by-byte DataInputStream sr = new DataInputStream(req.getInputStream()); InputStreamReader isr = new InputStreamReader(sr, "UTF-8"); StringBuffer buffer = new StringBuffer(); Reader in = new BufferedReader(isr); int ch; while ((ch = in.read()) > -1) { buffer.append((char) ch); } String inputText = buffer.toString(); if (inputText.length() == 0) { return; } if (hasSerializedDc) { this.extractSerializedDc(inputText, inData); } else { this.deserialize(inputText, inData); } } catch (IOException ioEx) { // nothing to do here } }
From source file:cn.itganhuo.app.web.controller.UserController.java
/** * ???photo// w w w .j a v a 2 s. co m * * @param request * @return * @author -? * @version 0.0.1-SNAPSHOT */ @RequiresAuthentication @RequestMapping(value = "/uploadImg", method = RequestMethod.POST) @ResponseBody public String uploadImg(HttpServletRequest request) { String msg = "fail"; User user = null; Subject current_user = SecurityUtils.getSubject(); user = (User) current_user.getSession().getAttribute(ConstantPool.USER_SHIRO_SESSION_ID); if (user == null || user.getId() <= 0) { user = userService.loadByAccount(current_user.getPrincipal().toString()); } String path = request.getSession().getServletContext().getRealPath("/static/upload/") + "/photos/" + user.getId() + ".jpg"; File file = new File(path); try { if (file.exists()) file.delete(); else file.createNewFile(); FileUtils.copyInputStreamToFile(request.getInputStream(), file); msg = "success"; log.debug(user.getAccount() + "Path modified image=" + path); } catch (IOException e) { throw new InternalException(log, "file path=" + path, e); } log.debug(msg + "," + user.getAccount()); return msg + "," + user.getAccount(); }
From source file:net.yacy.http.ProxyHandler.java
@Override public void handleRemote(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { sb.proxyLastAccess = System.currentTimeMillis(); RequestHeader proxyHeaders = ProxyHandler.convertHeaderFromJetty(request); setProxyHeaderForClient(request, proxyHeaders); final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent); client.setTimout(timeout);/*from w ww. ja va2s . c om*/ client.setHeader(proxyHeaders.entrySet()); client.setRedirecting(false); // send request try { String queryString = request.getQueryString() != null ? "?" + request.getQueryString() : ""; DigestURL digestURI = new DigestURL(request.getScheme(), request.getServerName(), request.getServerPort(), request.getRequestURI() + queryString); if (request.getMethod().equals(HeaderFramework.METHOD_GET)) { client.GET(digestURI, false); } else if (request.getMethod().equals(HeaderFramework.METHOD_POST)) { client.POST(digestURI, request.getInputStream(), request.getContentLength(), false); } else if (request.getMethod().equals(HeaderFramework.METHOD_HEAD)) { client.HEADResponse(digestURI, false); } else { throw new ServletException("Unsupported Request Method"); } HttpResponse clientresponse = client.getHttpResponse(); int statusCode = clientresponse.getStatusLine().getStatusCode(); final ResponseHeader responseHeaderLegacy = new ResponseHeader(statusCode, clientresponse.getAllHeaders()); if (responseHeaderLegacy.isEmpty()) { throw new SocketException(clientresponse.getStatusLine().toString()); } cleanResponseHeader(clientresponse); // reserver cache entry final net.yacy.crawler.retrieval.Request yacyRequest = new net.yacy.crawler.retrieval.Request(null, digestURI, null, //requestHeader.referer() == null ? null : new DigestURI(requestHeader.referer()).hash(), "", responseHeaderLegacy.lastModified(), sb.crawler.defaultProxyProfile.handle(), 0, sb.crawler.defaultProxyProfile.timezoneOffset()); //sizeBeforeDelete < 0 ? 0 : sizeBeforeDelete); final Response yacyResponse = new Response(yacyRequest, null, responseHeaderLegacy, sb.crawler.defaultProxyProfile, false, null); final String storeError = yacyResponse.shallStoreCacheForProxy(); final boolean storeHTCache = yacyResponse.profile().storeHTCache(); final String supportError = TextParser.supports(yacyResponse.url(), yacyResponse.getMimeType()); if ( /* * Now we store the response into the htcache directory if * a) the response is cacheable AND */ (storeError == null) && /* * b) the user has configured to use the htcache OR * c) the content should be indexed */ ((storeHTCache) || (supportError != null))) { // we don't write actually into a file, only to RAM, and schedule writing the file. int l = responseHeaderLegacy.size(); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream((l < 32) ? 32 : l); final OutputStream toClientAndMemory = new MultiOutputStream( new OutputStream[] { response.getOutputStream(), byteStream }); convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); client.writeTo(toClientAndMemory); // cached bytes storeToCache(yacyResponse, byteStream.toByteArray()); } else { // no caching /*if (log.isFine()) log.logFine(reqID +" "+ url.toString() + " not cached." + " StoreError=" + ((storeError==null)?"None":storeError) + " StoreHTCache=" + storeHTCache + " SupportError=" + supportError);*/ convertHeaderToJetty(clientresponse, response); response.setStatus(statusCode); if (statusCode == HttpServletResponse.SC_OK) { // continue to serve header to client e.g. HttpStatus = 302 (while skiping content) client.writeTo(response.getOutputStream()); // may throw exception on httpStatus=302 while gzip encoded inputstream } } } catch (final SocketException se) { throw new ServletException("Socket Exception: " + se.getMessage()); } finally { client.finish(); } // we handled this request, break out of handler chain logProxyAccess(request); baseRequest.setHandled(true); }
From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, URISyntaxException { targetUriObj = new URI(targetUri.get()); targetHost = URIUtils.extractHost(targetUriObj); // Make the Request // note: we won't transfer the protocol version because I'm not sure it would // truly be compatible String method = request.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(request); // spec: RFC 2616, sec 4.3: either of these two headers signal that there is // a message body. if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null || request.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since // the container handles it eProxyRequest.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength())); proxyRequest = eProxyRequest;//w ww. j ava 2 s . com } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(request); setXForwardedForHeader(request); // Execute the request try { active.set(this); log.debug("REQUEST " + "[" + StringUtils.right(Thread.currentThread().getName(), 2) + "] " + method + ": " + request.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(targetHost, proxyRequest); } catch (Exception e) { // abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) { throw (RuntimeException) e; } if (e instanceof ServletException) { throw (ServletException) e; } // noinspection ConstantConditions if (e instanceof IOException) { throw (IOException) e; } throw new RuntimeException(e); } finally { active.set(null); } // Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter }
From source file:com.jaspersoft.jasperserver.rest.services.RESTReport.java
/** * This method allows the user to create (run/fill) a new report. * /*from ww w . j a v a 2 s .co m*/ * * @param req * @param resp * @throws ServiceException */ @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServiceException { // We are creating a new report here... // Add all the options... Map<String, String> options = new HashMap<String, String>(); // Add as option all the GET parameters... Enumeration en = req.getParameterNames(); while (en.hasMoreElements()) { String key = (String) en.nextElement(); options.put(key, req.getParameter(key)); } Map<String, Object> parameters = new HashMap<String, Object>(); // We expect the user to send us a ResourceDescriptor with some parameters in it... HttpServletRequest mreq = restUtils.extractAttachments(runReportService, req); String resourceDescriptorXml = null; // get the resource descriptor... if (mreq instanceof MultipartHttpServletRequest) { resourceDescriptorXml = mreq.getParameter(restUtils.REQUEST_PARAMENTER_RD); } else { try { resourceDescriptorXml = IOUtils.toString(req.getInputStream()); } catch (IOException ex) { throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage()); } } if (resourceDescriptorXml == null) { restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Missing parameter " + restUtils.REQUEST_PARAMENTER_RD + " " + runReportService.getInputAttachments()); return; } // Parse the resource descriptor... InputSource is = new InputSource(new StringReader(resourceDescriptorXml)); Document doc = null; ResourceDescriptor rd = null; try { doc = XMLUtil.getNewDocumentBuilder().parse(is); rd = Unmarshaller.readResourceDescriptor(doc.getDocumentElement()); } catch (SAXException ex) { restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, "Invalid resource descriptor"); return; } catch (ServiceException se) { if (se.getErrorCode() == ServiceException.RESOURCE_NOT_FOUND) { restUtils.setStatusAndBody(HttpServletResponse.SC_NOT_FOUND, resp, se.getLocalizedMessage()); throw new ServiceException(HttpServletResponse.SC_NOT_FOUND, se.getMessage()); } else { throw se; } } catch (Exception ex) { throw new ServiceException(ServiceException.INTERNAL_SERVER_ERROR, ex.getLocalizedMessage()); } // At this point we have a resource descriptor, find the parameters in it and the uri String uri = rd.getUriString(); List params = rd.getParameters(); for (int i = 0; i < params.size(); ++i) { ListItem parameter = (ListItem) params.get(i); if (parameter.isIsListItem()) { // Check if a collection exists for this parameter.. List collection = (List) parameters.get(parameter.getLabel()); if (collection == null) { collection = new ArrayList<String>(); parameters.put(parameter.getLabel(), collection); } collection.add(parameter.getValue()); } else { parameters.put(parameter.getLabel(), parameter.getValue()); } } if (log.isDebugEnabled()) log.debug("Running report " + uri + " with parameters: " + parameters + " and options: " + options); // highcharts report for REST v1 is by default noninteractive. if (!options.containsKey(Argument.PARAM_INTERACTIVE)) { options.put(Argument.PARAM_INTERACTIVE, Boolean.FALSE.toString()); } Map<String, DataSource> attachments = new ConcurrentHashMap<String, DataSource>(); OperationResult or = runReportService.runReport(uri, parameters, options, attachments); if (or.getReturnCode() != 0) { restUtils.setStatusAndBody(HttpServletResponse.SC_BAD_REQUEST, resp, or.getMessage()); return; } else { JasperPrint jp = (JasperPrint) runReportService.getAttributes().get("jasperPrint"); // Store the attachments in the session, with proper keys... HttpSession session = req.getSession(); String executionId = UUID.randomUUID().toString(); Report report = new Report(); report.setUuid(executionId); report.setOriginalUri(uri); report.setAttachments(attachments); report.setJasperPrint(jp); session.setAttribute(report.getUuid(), report); // Send out the xml... resp.setContentType("text/xml; charset=UTF-8"); restUtils.setStatusAndBody(HttpServletResponse.SC_CREATED, resp, report.toXml()); } }
From source file:nl.b3p.viewer.stripes.ProxyActionBean.java
private Resolution proxyArcIMS() throws Exception { HttpServletRequest request = getContext().getRequest(); if (!"POST".equals(request.getMethod())) { return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN); }//from w w w . jav a 2 s .com Map params = new HashMap(getContext().getRequest().getParameterMap()); // Only allow these parameters in proxy request params.keySet().retainAll(Arrays.asList("ClientVersion", "Encode", "Form", "ServiceName")); URL theUrl = new URL(url); // Must not allow file / jar etc protocols, only HTTP: String path = theUrl.getPath(); for (Map.Entry<String, String[]> param : (Set<Map.Entry<String, String[]>>) params.entrySet()) { if (path.length() == theUrl.getPath().length()) { path += "?"; } else { path += "&"; } path += URLEncoder.encode(param.getKey(), "UTF-8") + "=" + URLEncoder.encode(param.getValue()[0], "UTF-8"); } theUrl = new URL("http", theUrl.getHost(), theUrl.getPort(), path); // TODO logging for inspecting malicious proxy use ByteArrayOutputStream post = new ByteArrayOutputStream(); IOUtils.copy(request.getInputStream(), post); // This check makes some assumptions on how browsers serialize XML // created by OpenLayers' ArcXML.js write() function (whitespace etc.), // but all major browsers pass this check if (!post.toString("US-ASCII").startsWith("<ARCXML version=\"1.1\"><REQUEST><GET_IMAGE")) { return new ErrorResolution(HttpServletResponse.SC_FORBIDDEN); } final HttpURLConnection connection = (HttpURLConnection) theUrl.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setAllowUserInteraction(false); connection.setRequestProperty("X-Forwarded-For", request.getRemoteAddr()); connection.connect(); try { IOUtils.copy(new ByteArrayInputStream(post.toByteArray()), connection.getOutputStream()); } finally { connection.getOutputStream().flush(); connection.getOutputStream().close(); } return new StreamingResolution(connection.getContentType()) { @Override protected void stream(HttpServletResponse response) throws IOException { try { IOUtils.copy(connection.getInputStream(), response.getOutputStream()); } finally { connection.disconnect(); } } }; }
From source file:com.envision.envservice.filter.RedmineFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Content-Type", "application/json; charset=utf-8"); String requestType = request.getMethod(); String url = ""; String api_key = ""; String param = ""; String result = ""; if (requestType == "GET" || "GET".equals(requestType)) { url = getRedmineUrl(request.getRequestURL().toString()); api_key = getSessionApiKey(request); if (api_key == null || "".equals(api_key)) { return; }/*w w w .ja v a2 s .com*/ WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext(); RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext .getBean("redmineHttpRequestService"); result = redmineHttpRequestService.doGET(url, api_key); } else if (requestType == "POST" || "POST".equals(requestType)) { url = getRedmineUrl(request.getRequestURL().toString()); api_key = getSessionApiKey(request); if (api_key == null || "".equals(api_key)) { return; } param = getParam(request.getInputStream()); WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext(); RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext .getBean("redmineHttpRequestService"); result = redmineHttpRequestService.doPost(url, param, api_key); } else if (requestType == "PUT" || "PUT".equals(requestType)) { url = getRedmineUrl(request.getRequestURL().toString()); api_key = getSessionApiKey(request); if (api_key == null || "".equals(api_key)) { return; } param = getParam(request.getInputStream()); WebApplicationContext webAppContext = ContextLoader.getCurrentWebApplicationContext(); RedmineHttpRequestService redmineHttpRequestService = (RedmineHttpRequestService) webAppContext .getBean("redmineHttpRequestService"); result = redmineHttpRequestService.doPut(url, param, api_key); } else { return; } response.getWriter().write(result); return; }