List of usage examples for javax.servlet.http HttpServletRequest getContentLength
public int getContentLength();
From source file:org.opendatakit.api.forms.FormService.java
@POST @ApiOperation(value = "Upload a zipped form definition as multipart/form-data.", response = FormUploadResult.class) @Consumes({ MediaType.MULTIPART_FORM_DATA }) @Produces({ MediaType.APPLICATION_JSON, ApiConstants.MEDIA_TEXT_XML_UTF8, ApiConstants.MEDIA_APPLICATION_XML_UTF8 }) @Path("{appId}/{odkClientVersion}") public Response doPost(@Context HttpServletRequest req, @Context HttpServletResponse resp, @PathParam("odkClientVersion") String odkClientVersion, @PathParam("appId") String appId, @Context UriInfo info) throws IOException { logger.debug("Uploading..."); ServiceUtils.examineRequest(req.getServletContext(), req); req.getContentLength(); if (!ServletFileUpload.isMultipartContent(req)) { throw new WebApplicationException(ErrorConsts.NO_MULTI_PART_CONTENT, HttpServletResponse.SC_BAD_REQUEST); }/* www. j a v a 2 s.co m*/ try { TablesUserPermissions userPermissions = ContextUtils.getTablesUserPermissions(callingContext); List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(req); Map<String, byte[]> files = null; String tableId = null; List<String> regionalOffices = new ArrayList<>(); // unzipping files for (FileItem item : items) { // Retrieve all Regional Office IDs to which a form definition // is going to be assigned to if (item.getFieldName().equals(WebConsts.OFFICE_ID)) { regionalOffices.add(item.getString()); } String fieldName = item.getFieldName(); String fileName = FilenameUtils.getName(item.getName()); if (fieldName.equals(WebConsts.ZIP_FILE)) { if (fileName == null || !(fileName.endsWith(".zip"))) { throw new WebApplicationException(ErrorConsts.NO_ZIP_FILE, HttpServletResponse.SC_BAD_REQUEST); } InputStream fileStream = item.getInputStream(); ZipInputStream zipStream = new ZipInputStream(fileStream); files = processZipInputStream(zipStream); } } tableId = getTableIdFromFiles(files); FormUploadResult formUploadResult = uploadFiles(odkClientVersion, appId, tableId, userPermissions, files, regionalOffices); FileManifestManager manifestManager = new FileManifestManager(appId, odkClientVersion, callingContext); OdkTablesFileManifest manifest = manifestManager.getManifestForTable(tableId); FileManifestService.fixDownloadUrls(info, appId, odkClientVersion, manifest); formUploadResult.setManifest(manifest); String eTag = Integer.toHexString(manifest.hashCode()); // Is this // right? return Response.status(Status.CREATED).entity(formUploadResult).header(HttpHeaders.ETAG, eTag) .header(ApiConstants.OPEN_DATA_KIT_VERSION_HEADER, ApiConstants.OPEN_DATA_KIT_VERSION) .header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Credentials", "true") .build(); } catch (FileUploadException | ODKDatastoreException | ODKTaskLockException | PermissionDeniedException | TableAlreadyExistsException e) { logger.error("Error uploading zip", e); throw new WebApplicationException(ErrorConsts.PERSISTENCE_LAYER_PROBLEM + "\n" + e.toString(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } }
From source file:org.haiku.haikudepotserver.job.controller.JobController.java
/** * <p>This URL can be used to supply data that can be used with a job to be run as an input to the * job. A GUID is returned in the header {@link #HEADER_DATAGUID} that can be later used to refer * to this uploaded data.</p>//from w w w.j a v a2s.c om */ @RequestMapping(value = "/" + SEGMENT_JOBDATA, method = RequestMethod.POST) @ResponseBody public void supplyData(final HttpServletRequest request, final HttpServletResponse response, @RequestHeader(value = HttpHeaders.CONTENT_TYPE, required = false) String contentType, @RequestParam(value = KEY_USECODE, required = false) String useCode) throws IOException { Preconditions.checkArgument(null != request, "the request must be provided"); int length = request.getContentLength(); if (-1 != length && length > MAX_SUPPLY_DATA_LENGTH) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } ObjectContext context = serverRuntime.newContext(); tryObtainAuthenticatedUser(context).orElseThrow(() -> { LOGGER.warn("attempt to supply job data with no authenticated user"); return new JobDataAuthorizationFailure(); }); JobData data = jobService.storeSuppliedData(useCode, !Strings.isNullOrEmpty(contentType) ? contentType : MediaType.OCTET_STREAM.toString(), new ByteSource() { @Override public InputStream openStream() throws IOException { return request.getInputStream(); } }); response.setStatus(HttpServletResponse.SC_OK); response.setHeader(HEADER_DATAGUID, data.getGuid()); }
From source file:org.exoplatform.upload.UploadService.java
public void createUploadResource(String uploadId, HttpServletRequest request) throws FileUploadException { UploadResource upResource = new UploadResource(uploadId); upResource.setFileName("");// Avoid NPE in UploadHandler uploadResources.put(upResource.getUploadId(), upResource); putToStackInSession(request.getSession(true), uploadId); double contentLength = request.getContentLength(); upResource.setEstimatedSize(contentLength); if (isLimited(upResource, contentLength)) { upResource.setStatus(UploadResource.FAILED_STATUS); return;//from w w w . j ava 2 s . c o m } ServletFileUpload servletFileUpload = makeServletFileUpload(upResource); // parse request List<FileItem> itemList = servletFileUpload.parseRequest(request); if (itemList == null || itemList.size() != 1 || itemList.get(0).isFormField()) { log.debug("Please upload 1 file per request"); return; } DiskFileItem fileItem = (DiskFileItem) itemList.get(0); String fileName = fileItem.getName(); if (fileName == null) fileName = uploadId; fileName = fileName.substring(fileName.lastIndexOf('\\') + 1); String storeLocation = uploadLocation_ + "/" + uploadId + "." + fileName; // commons-fileupload will store the temp file with name *.tmp // we need to rename it to our desired name fileItem.getStoreLocation().renameTo(new File(storeLocation)); upResource.setFileName(fileName); upResource.setMimeType(fileItem.getContentType()); upResource.setStoreLocation(storeLocation); upResource.setStatus(UploadResource.UPLOADED_STATUS); }
From source file:com.adaptris.core.http.jetty.JettyMessageConsumer.java
@Override public AdaptrisMessage createMessage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { AdaptrisMessage msg = null;/*from w ww. j a v a2 s .co m*/ try { logHeaders(request); if (getEncoder() != null) { msg = getEncoder().readMessage(request); } else { msg = defaultIfNull(getMessageFactory()).newMessage(); try (InputStream in = request.getInputStream(); OutputStream out = msg.getOutputStream()) { if (request.getContentLength() == -1) { IOUtils.copy(request.getInputStream(), out); } else { StreamUtil.copyStream(request.getInputStream(), out, request.getContentLength()); } } } msg.setContentEncoding(request.getCharacterEncoding()); addParamMetadata(msg, request); addHeaderMetadata(msg, request); } catch (CoreException e) { throw new IOException(e.getMessage(), e); } return msg; }
From source file:petascope.wcs2.Wcs2Servlet.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse res) { long startTime = System.currentTimeMillis(); setServletURL(req);//from ww w . j a v a 2 s . c om meta.clearCache(); String request = null; try { try { request = IOUtils.toString(req.getReader()); log.trace("POST request length: " + req.getContentLength()); log.trace("GET query string: " + req.getQueryString()); log.trace("POST request body:\n" + request + "\n----------------------------------------\n"); Map<String, String> params = buildParameterDictionary(request); if (params.containsKey("request")) { request = params.get("request"); } request = StringUtil.urldecode(request, req.getContentType()); if (request == null || request.length() == 0) { if (req.getQueryString() != null && req.getQueryString().length() > 0) { request = req.getQueryString(); request = StringUtil.urldecode(request, req.getContentType()); } else { printUsage(res, request); return; } } log.debug("Petascope Request: \n------START REQUEST--------\n" + request + "\n------END REQUEST------\n"); handleWcs2Request(request, res, req); } catch (WCSException e) { throw e; } catch (PetascopeException e) { throw new WCSException(e.getExceptionCode(), e.getMessage()); } catch (SecoreException e) { throw new WCSException(e.getExceptionCode(), e); } catch (Exception e) { log.error("Runtime error : {}", e.getMessage()); throw new WCSException(ExceptionCode.RuntimeError, "Runtime error while processing request", e); } } catch (WCSException e) { printError(res, request, e); } long elapsedTimeMillis = System.currentTimeMillis() - startTime; log.debug("Total Petascope Processing Time : " + elapsedTimeMillis); }
From source file:jp.go.nict.langrid.servicesupervisor.frontend.FrontEnd.java
/** * /*www .j a v a 2s . c o m*/ * */ public static LogInfo createLogInfo(HttpServletRequest request, InputStream responseBody, long responseMillis, int responseCode, int responseBytes, String protocolId) { String fromAddress = request.getRemoteAddr(); String fromHost = request.getRemoteHost(); if (fromAddress.equals("127.0.0.1")) { // localhost????HTTPHEADER_FROMADDRESS??? String fromAddressHeader = request.getHeader(LangridConstants.HTTPHEADER_FROMADDRESS); if (fromAddressHeader != null) { fromAddress = fromAddressHeader; fromHost = fromAddressHeader; } } int callNest = 0; String callNestString = request.getHeader(LangridConstants.HTTPHEADER_CALLNEST); if (callNestString != null && callNestString.length() > 0) { try { callNest = Integer.parseInt(callNestString); } catch (NumberFormatException e) { logger.warning("The value of call nest header is not a number: " + callNestString); } } String callTree = ""; try { callTree = getCallTree(protocolId, responseBody); } catch (IOException e) { } return new LogInfo(fromAddress, fromHost, Calendar.getInstance(), request.getRequestURI(), request.getContentLength(), responseMillis, responseCode, responseBytes, protocolId, request.getHeader("Referrer"), request.getHeader("User-Agent"), callNest, callTree); }
From source file:bijian.util.upload.MyMultiPartRequest.java
/** * Creates a RequestContext needed by Jakarta Commons Upload. * * @param req the request./*from www. j av a2 s . c o m*/ * @return a new request context. */ private RequestContext createRequestContext(final HttpServletRequest req) { return new RequestContext() { public String getCharacterEncoding() { return req.getCharacterEncoding(); } public String getContentType() { return req.getContentType(); } public int getContentLength() { return req.getContentLength(); } public InputStream getInputStream() throws IOException { InputStream in = req.getInputStream(); if (in == null) { throw new IOException("Missing content in the request"); } return req.getInputStream(); } }; }
From source file:de.adorsys.oauth.server.FixedServletUtils.java
/** * Creates a new HTTP request from the specified HTTP servlet request. * * @param servletRequest The servlet request. Must not be * {@code null}.//from w w w.j av a2 s . co m * @param maxEntityLength The maximum entity length to accept, -1 for * no limit. * * @return The HTTP request. * * @throws IllegalArgumentException The the servlet request method is * not GET, POST, PUT or DELETE or the * content type header value couldn't * be parsed. * @throws IOException For a POST or PUT body that * couldn't be read due to an I/O * exception. */ public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength) throws IOException { HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase()); String urlString = reconstructRequestURLString(servletRequest); URL url; try { url = new URL(urlString); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e); } HTTPRequest request = new HTTPRequest(method, url); try { request.setContentType(servletRequest.getContentType()); } catch (ParseException e) { throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e); } Enumeration<String> headerNames = servletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); request.setHeader(headerName, servletRequest.getHeader(headerName)); } if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) { request.setQuery(servletRequest.getQueryString()); } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) { if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) { throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars"); } Map<String, String[]> parameterMap = servletRequest.getParameterMap(); StringBuilder builder = new StringBuilder(); if (!parameterMap.isEmpty()) { for (Entry<String, String[]> entry : parameterMap.entrySet()) { String key = entry.getKey(); String[] value = entry.getValue(); if (value.length > 0 && value[0] != null) { String encoded = URLEncoder.encode(value[0], "UTF-8"); builder = builder.append(key).append('=').append(encoded).append('&'); } } String queryString = StringUtils.substringBeforeLast(builder.toString(), "&"); request.setQuery(queryString); } else { // read body StringBuilder body = new StringBuilder(256); BufferedReader reader = servletRequest.getReader(); reader.reset(); char[] cbuf = new char[256]; int readChars; while ((readChars = reader.read(cbuf)) != -1) { body.append(cbuf, 0, readChars); if (maxEntityLength > 0 && body.length() > maxEntityLength) { throw new IOException( "Request entity body is too large, limit is " + maxEntityLength + " chars"); } } reader.reset(); // reader.close(); request.setQuery(body.toString()); } } return request; }
From source file:org.osaf.cosmo.mc.MorseCodeServlet.java
private boolean checkWritePreconditions(HttpServletRequest req, HttpServletResponse resp) { if (req.getContentLength() <= 0) { resp.setStatus(HttpServletResponse.SC_LENGTH_REQUIRED); return false; }//from w w w . ja va 2 s .c om if (req.getContentType() == null || !req.getContentType().startsWith(MEDIA_TYPE_EIMML)) { resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE); return false; } if (req.getHeader("Content-Transfer-Encoding") != null || req.getHeader("Content-Encoding") != null || req.getHeader("Content-Base") != null || req.getHeader("Content-Location") != null || req.getHeader("Content-MD5") != null || req.getHeader("Content-Range") != null) { resp.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED); return false; } return true; }
From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java
/** * Creates a new request wrapper to handle multi-part data using methods * adapted from Jason Pell's multipart classes (see class description). * // w ww . jav a 2 s. co m * @param saveDir * the directory to save off the file * @param servletRequest * the request containing the multipart * @throws java.io.IOException * is thrown if encoding fails. * @throws */ public void parse(HttpServletRequest servletRequest, String saveDir) throws IOException { Integer delay = 3; UploadListener listener = null; DiskFileItemFactory fac = null; // Parse the request try { if (maxSize >= 0L && servletRequest.getContentLength() > maxSize) { servletRequest.setAttribute("error", "size"); FileItemIterator it = new ServletFileUpload(fac).getItemIterator(servletRequest); // handle with each file: while (it.hasNext()) { FileItemStream item = it.next(); if (item.isFormField()) { List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } InputStream stream = item.openStream(); values.add(Streams.asString(stream)); params.put(item.getFieldName(), values); } } return; } else { listener = new UploadListener(servletRequest, delay); fac = new MonitoredDiskFileItemFactory(listener); } // Make sure that the data is written to file fac.setSizeThreshold(0); if (saveDir != null) { fac.setRepository(new File(saveDir)); } ServletFileUpload upload = new ServletFileUpload(fac); upload.setSizeMax(maxSize); List items = upload.parseRequest(createRequestContext(servletRequest)); for (Object item1 : items) { FileItem item = (FileItem) item1; if (log.isDebugEnabled()) log.debug("Found item " + item.getFieldName()); if (item.isFormField()) { log.debug("Item is a normal form field"); List<String> values; if (params.get(item.getFieldName()) != null) { values = params.get(item.getFieldName()); } else { values = new ArrayList<String>(); } String charset = servletRequest.getCharacterEncoding(); if (charset != null) { values.add(item.getString(charset)); } else { values.add(item.getString()); } params.put(item.getFieldName(), values); } else { log.debug("Item is a file upload"); // Skip file uploads that don't have a file name - meaning // that no file was selected. if (item.getName() == null || item.getName().trim().length() < 1) { log.debug("No file has been uploaded for the field: " + item.getFieldName()); continue; } String targetFileName = item.getName(); if (!targetFileName.contains(":")) item.write(new File(targetDirectory + targetFileName)); //?Action List<FileItem> values; if (files.get(item.getFieldName()) != null) { values = files.get(item.getFieldName()); } else { values = new ArrayList<FileItem>(); } values.add(item); files.put(item.getFieldName(), values); } } } catch (Exception e) { log.error(e); errors.add(e.getMessage()); } }