List of usage examples for javax.servlet.http HttpServletRequest getInputStream
public ServletInputStream getInputStream() throws IOException;
From source file:com.couchbase.capi.servlet.CAPIServlet.java
/** * Handle special operations at the root level /_... * @param req// w w w . ja v a 2s . com * @param resp * @param special * @throws ServletException * @throws IOException */ protected void handleRootSpecial(HttpServletRequest req, HttpServletResponse resp, String special) throws ServletException, IOException { if (special.equals("_pre_replicate")) { logger.debug("got _pre_replicate: {}", req.getRequestURI()); handlePreReplicate(req, resp); return; } else if (special.equals("_commit_for_checkpoint")) { logger.debug("got _commit_for_checkpoint: {}", req.getRequestURI()); handleCommitForCheckpoint(req, resp); return; } else { logger.debug("got unknown special: {}", req.getRequestURI()); } InputStream is = req.getInputStream(); int requestLength = req.getContentLength(); byte[] buffer = new byte[requestLength]; IOUtils.readFully(is, buffer, 0, requestLength); logger.trace("root special request body was: '{}'", new String(buffer)); sendNotFoundResponse(resp, "missing"); }
From source file:com.kagubuzz.servlets.UploadServlet.java
/** * Handles the HTTP <code>POST</code> method. * // ww w . j a v a 2 s . com * @param request * servlet request * @param response * servlet response * @throws ServletException * if a servlet-specific error occurs * @throws IOException * if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException { ApplicationContext applicationContext = WebApplicationContextUtils .getWebApplicationContext(this.getServletContext()); fileService = (FileService) applicationContext.getBean("fileService"); JavaFileUtilities fileUtils = new JavaFileUtilities(); InputStream is = null; FileOutputStream os = null; Map<String, Object> uploadResult = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); //TODO: Mske all these files write to a tmp direcotry for th euploader to be erased when the review button is pushed try { byte[] buffer = new byte[4096]; int bytesRead = 0; // Make sure image file is less than 4 megs if (bytesRead > 1024 * 1024 * 4) throw new FileUploadException(); is = request.getInputStream(); File tmpFile = File.createTempFile("image-", ".jpg"); os = new FileOutputStream(tmpFile); System.out.println("Saving to " + JavaFileUtilities.getTempFilePath()); while ((bytesRead = is.read(buffer)) != -1) os.write(buffer, 0, bytesRead); KaguImage thumbnailImage = new KaguImage(tmpFile); thumbnailImage.setWorkingDirectory(JavaFileUtilities.getTempFilePath()); thumbnailImage.resize(140, 180); File thumbnail = thumbnailImage .saveAsJPG("thumbnail-" + FilenameUtils.removeExtension(tmpFile.getName())); fileService.write(fileUtils.fileToByteArrayOutputStream(tmpFile), tmpFile.getName(), fileService.getTempFilePath()); fileService.write(fileUtils.fileToByteArrayOutputStream(thumbnail), thumbnail.getName(), fileService.getTempFilePath()); response.setStatus(HttpServletResponse.SC_OK); uploadResult.put("success", "true"); uploadResult.put("indexedfilename", fileService.getTempDirectoryURL() + tmpFile.getName()); uploadResult.put("thumbnailfilename", fileService.getTempDirectoryURL() + thumbnail.getName()); } catch (FileNotFoundException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); uploadResult.put("success", "false"); log(UploadServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (IOException ex) { response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); uploadResult.put("success", "false"); log(UploadServlet.class.getName() + "has thrown an exception: " + ex.getMessage()); } catch (FileUploadException e) { response.setStatus(HttpServletResponse.SC_OK); uploadResult.put("success", "false"); uploadResult.put("indexedfilename", "filetobig"); } finally { try { mapper.writeValue(response.getWriter(), uploadResult); os.close(); is.close(); } catch (IOException ignored) { } } }
From source file:com.imaginary.home.cloud.api.call.LocationCall.java
@Override public void put(@Nonnull String requestId, @Nullable String userId, @Nonnull String[] path, @Nonnull HttpServletRequest req, @Nonnull HttpServletResponse resp, @Nonnull Map<String, Object> headers, @Nonnull Map<String, Object> parameters) throws RestException, IOException { try {//from ww w . j a va2 s . c o m String locationId = (path.length > 1 ? path[1] : null); Location location = null; if (locationId != null) { location = Location.getLocation(locationId); } if (location == null) { throw new RestException(HttpServletResponse.SC_NOT_FOUND, RestException.NO_SUCH_OBJECT, "The location " + locationId + " does not exist."); } BufferedReader reader = new BufferedReader(new InputStreamReader(req.getInputStream())); StringBuilder source = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { source.append(line); source.append(" "); } JSONObject object = new JSONObject(source.toString()); String action; if (object.has("action") && !object.isNull("action")) { action = object.getString("action"); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION, "An invalid action was specified (or not specified) in the PUT"); } if (object.has("location")) { object = object.getJSONObject("location"); } else { object = null; } if (action.equalsIgnoreCase("initializePairing")) { HashMap<String, Object> json = new HashMap<String, Object>(); String pairingCode = location.readyForPairing(); json.put("pairingCode", pairingCode); resp.setStatus(HttpServletResponse.SC_OK); resp.getWriter().println((new JSONObject(json)).toString()); resp.getWriter().flush(); } else if (action.equalsIgnoreCase("modify")) { if (object == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_PUT, "No location was specified in the PUT"); } String name, description; TimeZone timeZone; if (object.has("name") && !object.isNull("name")) { name = object.getString("name"); } else { name = location.getName(); } if (object.has("description") && !object.isNull("description")) { description = object.getString("description"); } else { description = location.getName(); } if (object.has("timeZone") && !object.isNull("timeZone")) { String tz = object.getString("timeZone"); timeZone = TimeZone.getTimeZone(tz); } else { timeZone = location.getTimeZone(); } location.modify(name, description, timeZone); resp.setStatus(HttpServletResponse.SC_NO_CONTENT); } else { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_ACTION, "The action " + action + " is not a valid action."); } } catch (JSONException e) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.INVALID_JSON, "Invalid JSON in request"); } catch (PersistenceException e) { throw new RestException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, RestException.INTERNAL_ERROR, e.getMessage()); } }
From source file:com.cloud.bridge.service.controller.s3.S3ObjectAction.java
public void executePostObject(HttpServletRequest request, HttpServletResponse response) throws IOException { String bucket = (String) request.getAttribute(S3Constants.BUCKET_ATTR_KEY); String contentType = request.getHeader("Content-Type"); int boundaryIndex = contentType.indexOf("boundary="); String boundary = "--" + (contentType.substring(boundaryIndex + 9)); String lastBoundary = boundary + "--"; InputStreamReader isr = new InputStreamReader(request.getInputStream()); BufferedReader br = new BufferedReader(isr); StringBuffer temp = new StringBuffer(); String oneLine = null;//from w ww . j a va 2s .c o m String name = null; String value = null; String metaName = null; // -> after stripped off the x-amz-meta- boolean isMetaTag = false; int countMeta = 0; int state = 0; // [A] First parse all the parts out of the POST request and message body // -> bucket name is still encoded in a Host header S3AuthParams params = new S3AuthParams(); List<S3MetaDataEntry> metaSet = new ArrayList<S3MetaDataEntry>(); S3PutObjectInlineRequest engineRequest = new S3PutObjectInlineRequest(); engineRequest.setBucketName(bucket); // -> the last body part contains the content that is used to write the S3 object, all // other body parts are header values while (null != (oneLine = br.readLine())) { if (oneLine.startsWith(lastBoundary)) { // -> this is the data of the object to put if (0 < temp.length()) { value = temp.toString(); temp.setLength(0); engineRequest.setContentLength(value.length()); engineRequest.setDataAsString(value); } break; } else if (oneLine.startsWith(boundary)) { // -> this is the header data if (0 < temp.length()) { value = temp.toString().trim(); temp.setLength(0); //System.out.println( "param: " + name + " = " + value ); if (name.equalsIgnoreCase("key")) { engineRequest.setKey(value); } else if (name.equalsIgnoreCase("x-amz-acl")) { engineRequest.setCannedAccess(value); } else if (isMetaTag) { S3MetaDataEntry oneMeta = new S3MetaDataEntry(); oneMeta.setName(metaName); oneMeta.setValue(value); metaSet.add(oneMeta); countMeta++; metaName = null; } // -> build up the headers so we can do authentication on this POST HeaderParam oneHeader = new HeaderParam(); oneHeader.setName(name); oneHeader.setValue(value); params.addHeader(oneHeader); } state = 1; } else if (1 == state && 0 == oneLine.length()) { // -> data of a body part starts here state = 2; } else if (1 == state) { // -> the name of the 'name-value' pair is encoded in the Content-Disposition header if (oneLine.startsWith("Content-Disposition: form-data;")) { isMetaTag = false; int nameOffset = oneLine.indexOf("name="); if (-1 != nameOffset) { name = oneLine.substring(nameOffset + 5); if (name.startsWith("\"")) name = name.substring(1); if (name.endsWith("\"")) name = name.substring(0, name.length() - 1); name = name.trim(); if (name.startsWith("x-amz-meta-")) { metaName = name.substring(11); isMetaTag = true; } } } } else if (2 == state) { // -> the body parts data may take up multiple lines //System.out.println( oneLine.length() + " body data: " + oneLine ); temp.append(oneLine); } // else System.out.println( oneLine.length() + " preamble: " + oneLine ); } // [B] Authenticate the POST request after we have all the headers try { S3RestServlet.authenticateRequest(request, params); } catch (Exception e) { throw new IOException(e.toString()); } // [C] Perform the request if (0 < countMeta) engineRequest.setMetaEntries(metaSet.toArray(new S3MetaDataEntry[0])); S3PutObjectInlineResponse engineResponse = ServiceProvider.getInstance().getS3Engine() .handleRequest(engineRequest); response.setHeader("ETag", engineResponse.getETag()); String version = engineResponse.getVersion(); if (null != version) response.addHeader("x-amz-version-id", version); }
From source file:com.ewcms.web.pubsub.PubsubServlet.java
/** * Comet event?// w w w . j a v a2s . c o m * * ???<a href = "http://tomcat.apache.org/tomcat-6.0-doc/aio.html#Example_code">ChatServlet</a> * * @param event * The Comet event that will be processed * @throws IOException * @throws ServletException */ public void event(CometEvent event) throws IOException, ServletException { HttpServletRequest request = event.getHttpServletRequest(); HttpServletResponse response = event.getHttpServletResponse(); if (event.getEventType() == CometEvent.EventType.BEGIN) { logger.debug("Begin for session:{} ", request.getSession(true).getId()); String fullContentType = "text/html;charset=UTF-8"; response.setContentType(fullContentType); addConnection(request.getPathInfo(), response); } else if (event.getEventType() == CometEvent.EventType.ERROR) { logger.debug("Error for session: {}", request.getSession(true).getId()); removeConnection(response); event.close(); } else if (event.getEventType() == CometEvent.EventType.END) { logger.debug("End for session:{} ", request.getSession(true).getId()); removeConnection(response); event.close(); } else if (event.getEventType() == CometEvent.EventType.READ) { InputStream is = request.getInputStream(); byte[] buf = new byte[512]; do { int n = is.read(buf); // can throw an IOException if (n > 0) { logger.debug("Read {} bytes:{} for session:{}", new Object[] { n, new String(buf, 0, n), request.getSession(true).getId() }); } else if (n < 0) { return; } } while (is.available() > 0); } }
From source file:org.overlord.sramp.server.servlets.MavenRepositoryServlet.java
/** * Upload artifact.//from w w w . j av a 2 s . co m * * @param req * the req * @param response * the response * @throws ServletException * the servlet exception * @throws IOException * Signals that an I/O exception has occurred. */ private void uploadArtifact(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { // Get the URL request and prepare it to obtain the maven metadata // information String url = req.getRequestURI(); String maven_url = ""; //$NON-NLS-1$ if (url.contains(URL_CONTEXT_STR)) { maven_url = url.substring(url.indexOf(URL_CONTEXT_STR) + URL_CONTEXT_STR.length()); } else { maven_url = url; } if (maven_url.startsWith("/")) { //$NON-NLS-1$ maven_url = maven_url.substring(1); } // Extract the relevant content from the POST'd form Map<String, String> responseMap = new HashMap<String, String>(); InputStream content = null; // Parse the request content = req.getInputStream(); // Builder class that converts the url into a Maven MetaData Object MavenMetaData metadata = MavenMetaDataBuilder.build(maven_url); try { if (metadata.isArtifact()) { if (SNAPSHOT_ALLOWED || !metadata.isSnapshotVersion()) { String uuid = service.uploadArtifact(metadata, content); responseMap.put("uuid", uuid); //$NON-NLS-1$ } else { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Messages.i18n.format("maven.servlet.put.snapshot.not.allowed")); //$NON-NLS-1$ } } else { response.sendError(HttpServletResponse.SC_BAD_REQUEST, Messages.i18n.format("maven.servlet.put.url.without.artifact")); //$NON-NLS-1$ } } catch (Throwable e) { logger.error(Messages.i18n.format("maven.servlet.artifact.content.put.exception"), e); //$NON-NLS-1$ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, Messages.i18n.format("maven.servlet.put.exception")); //$NON-NLS-1$ } finally { if (content != null) { IOUtils.closeQuietly(content); } } }
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;/*from w ww . j av 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.thinkberg.moxo.dav.PutHandler.java
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { FileObject object = getResourceManager().getFileObject(request.getPathInfo()); try {/*from w w w. j a v a 2 s . c o m*/ LockManager.getInstance().checkCondition(object, getIf(request)); } catch (LockException e) { if (e.getLocks() != null) { response.sendError(SC_LOCKED); } else { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); } return; } // it is forbidden to write data on a folder if (object.exists() && FileType.FOLDER.equals(object.getType())) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } FileObject parent = object.getParent(); if (!parent.exists()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } if (!FileType.FOLDER.equals(parent.getType())) { response.sendError(HttpServletResponse.SC_CONFLICT); return; } InputStream is = request.getInputStream(); OutputStream os = object.getContent().getOutputStream(); log("PUT sends " + request.getHeader("Content-length") + " bytes"); log("PUT copied " + Util.copyStream(is, os) + " bytes"); os.flush(); object.close(); response.setStatus(HttpServletResponse.SC_CREATED); }