List of usage examples for org.apache.commons.fileupload FileItemIterator next
FileItemStream next() throws FileUploadException, IOException;
From source file:ai.ilikeplaces.servlets.ServletFileUploads.java
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request__//from www .j av a2 s. c o m * @param response__ * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(final HttpServletRequest request__, final HttpServletResponse response__) throws ServletException, IOException { response__.setContentType("text/html;charset=UTF-8"); Loggers.DEBUG.debug(logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0020"), request__.getLocale()); PrintWriter out = response__.getWriter(); final ResourceBundle gUI = PropertyResourceBundle.getBundle("ai.ilikeplaces.rbs.GUI"); try { fileUpload: { if (!isFileUploadPermitted()) { errorTemporarilyDisabled(out); break fileUpload; } processSignOn: { final HttpSession session = request__.getSession(false); if (session == null) { errorNoLogin(out); break fileUpload; } else if (session.getAttribute(ServletLogin.HumanUser) == null) { errorNoLogin(out); break processSignOn; } processRequestType: { @SuppressWarnings("unchecked") final HumanUserLocal sBLoggedOnUserLocal = ((SessionBoundBadRefWrapper<HumanUserLocal>) session .getAttribute(ServletLogin.HumanUser)).getBoundInstance(); try { /*Check that we have a file upload request*/ final boolean isMultipart = ServletFileUpload.isMultipartContent(request__); if (!isMultipart) { LoggerFactory.getLogger(ServletFileUploads.class.getName()).error( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0001")); errorNonMultipart(out); break processRequestType; } processRequest: { // Create a new file upload handler final ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iter = upload.getItemIterator(request__); boolean persisted = false; loop: { Long locationId = null; String photoDescription = null; String photoName = null; Boolean isPublic = null; Boolean isPrivate = null; boolean fileSaved = false; while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); String absoluteFileSystemFileName = FilePath; InputStream stream = item.openStream(); @_fix(issue = "Handle no extension files") String usersFileName = null; String randomFileName = null; if (item.isFormField()) { final String value = Streams.asString(stream); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0002"), name); Loggers.DEBUG.debug( logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0003"), value); if (name.equals("locationId")) { locationId = Long.parseLong(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0004"))); } if (name.equals("photoDescription")) { photoDescription = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0005"))); } if (name.equals("photoName")) { photoName = value; Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0006"))); } if (name.equals("isPublic")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPublic = Boolean.valueOf(value); Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0008"))); } if (name.equals("isPrivate")) { if (!(value.equals("true") || value.equals("false"))) { throw new IllegalArgumentException(logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0007") + value); } isPrivate = Boolean.valueOf(value); Loggers.DEBUG.debug("HELLO, I PROPERLY RECEIVED photoName."); } } if ((!item.isFormField())) { Loggers.DEBUG.debug((logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0009") + name)); Loggers.DEBUG.debug((logMsgs .getString("ai.ilikeplaces.servlets.ServletFileUploads.0010") + item.getName())); // Process the input stream if (!(item.getName().lastIndexOf(".") > 0)) { errorFileType(out, item.getName()); break processRequest; } usersFileName = (item.getName().indexOf("\\") <= 1 ? item.getName() : item.getName() .substring(item.getName().lastIndexOf("\\") + 1)); final String userUploadedFileName = item.getName(); String fileExtension = "error"; if (userUploadedFileName.toLowerCase().endsWith(".jpg")) { fileExtension = ".jpg"; } else if (userUploadedFileName.toLowerCase().endsWith(".jpeg")) { fileExtension = ".jpeg"; } else if (userUploadedFileName.toLowerCase().endsWith(".png")) { fileExtension = ".png"; } else { errorFileType(out, gUI.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0019")); break processRequest; } randomFileName = getRandomFileName(locationId); randomFileName += fileExtension; final File uploadedFile = new File( absoluteFileSystemFileName += randomFileName); final FileOutputStream fos = new FileOutputStream(uploadedFile); while (true) { final int dataByte = stream.read(); if (dataByte != -1) { fos.write(dataByte); } else { break; } } fos.close(); stream.close(); fileSaved = true; } Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0011") + locationId); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0012") + fileSaved); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0013") + photoDescription); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0014") + photoName); Loggers.DEBUG.debug( logMsgs.getString("ai.ilikeplaces.servlets.ServletFileUploads.0015") + isPublic); if (fileSaved && (photoDescription != null)) { persistData: { handlePublicPrivateness: { if ((isPublic != null) && isPublic && (locationId != null)) { Return<PublicPhoto> r = DB .getHumanCRUDPublicPhotoLocal(true) .cPublicPhoto(sBLoggedOnUserLocal.getHumanUserId(), locationId, absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName), 4); if (r.returnStatus() == 0) { successFileName(out, usersFileName, logMsgs.getString( "ai.ilikeplaces.servlets.ServletFileUploads.0016")); } else { errorBusy(out); } } else if ((isPrivate != null) && isPrivate) { Return<PrivatePhoto> r = DB .getHumanCRUDPrivatePhotoLocal(true) .cPrivatePhoto(sBLoggedOnUserLocal.getHumanUserId(), absoluteFileSystemFileName, photoName, photoDescription, new String(CDN + randomFileName)); if (r.returnStatus() == 0) { successFileName(out, usersFileName, "private"); } else { errorBusy(out); } } else { throw UNSUPPORTED_OPERATION_EXCEPTION; } } } /*We got what we need from the loop. Lets break it*/ break loop; } } } if (!persisted) { errorMissingParameters(out); break processRequest; } } } catch (FileUploadException ex) { Loggers.EXCEPTION.error(null, ex); errorBusy(out); } } } } } catch (final Throwable t_) { Loggers.EXCEPTION.error("SORRY! I ENCOUNTERED AN EXCEPTION DURING THE FILE UPLOAD", t_); } }
From source file:com.exilant.exility.core.HtmlRequestHandler.java
/** * Extract data from request object (form, data and session) * /*from www. java 2s . co m*/ * @param req * @param formIsSubmitted * @param hasSerializedDc * @param outData * @return all input fields into a service data * @throws ExilityException */ @SuppressWarnings("resource") public ServiceData createInData(HttpServletRequest req, boolean formIsSubmitted, boolean hasSerializedDc, ServiceData outData) throws ExilityException { ServiceData inData = new ServiceData(); if (formIsSubmitted == false) { /** * most common call from client that uses serverAgent to send an * ajax request with serialized dc as data */ this.extractSerializedData(req, hasSerializedDc, inData); } else { /** * form is submitted. this is NOT from serverAgent.js. This call * would be from other .jsp files */ if (hasSerializedDc == false) { /** * client has submitted a form with form fields in that. * Traditional form submit **/ this.extractParametersAndFiles(req, inData); } else { /** * Logic got evolved over a period of time. several calling jsps * actually inspect the stream for file, and in the process they * would have extracted form fields into session. So, we extract * form fields, as well as dip into session */ HttpSession session = req.getSession(); if (ServletFileUpload.isMultipartContent(req) == false) { /** * Bit convoluted. the .jsp has already extracted files and * form fields into session. field. */ String txt = session.getAttribute("dc").toString(); this.extractSerializedDc(txt, inData); this.extractFilesToDc(req, inData); } else { /** * jsp has not touched input stream, and it wants us to do * everything. */ try { ServletFileUpload fileUploader = new ServletFileUpload(); fileUploader.setHeaderEncoding("UTF-8"); FileItemIterator iterator = fileUploader.getItemIterator(req); while (iterator.hasNext()) { FileItemStream stream = iterator.next(); String fieldName = stream.getFieldName(); InputStream inStream = null; inStream = stream.openStream(); try { if (stream.isFormField()) { String fieldValue = Streams.asString(inStream); /** * dc is a special name that contains * serialized DC */ if (fieldName.equals("dc")) { this.extractSerializedDc(fieldValue, inData); } else { inData.addValue(fieldName, fieldValue); } } else { /** * it is a file. we assume that the files * are small, and hence we carry the content * in memory with a specific naming * convention */ String fileContents = IOUtils.toString(inStream); inData.addValue(fieldName + HtmlRequestHandler.PATH_SUFFIX, fileContents); } } catch (Exception e) { Spit.out("error whiel extracting data from request stream " + e.getMessage()); } IOUtils.closeQuietly(inStream); } } catch (Exception e) { // nothing to do here } /** * read session variables */ @SuppressWarnings("rawtypes") Enumeration e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); if (name.equals("dc")) { this.extractSerializedDc(req.getSession().getAttribute(name).toString(), inData); } String value = req.getSession().getAttribute(name).toString(); inData.addValue(name, value); System.out.println("name is: " + name + " value is: " + value); } } } } this.getStandardFields(req, inData); return inData; }
From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java
private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem) throws IOException { log.info("Multipart detected"); ServletFileUpload upload = new ServletFileUpload(); try {/*from w w w.j a v a2 s . c o m*/ // Parse the request FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); try (InputStream stream = item.openStream()) { if (item.isFormField()) { // TODO What to do with this? log.info("Form field {} with value {} detected.", name, Streams.asString(stream)); } else { // TODO Must we support multiple files uploading? log.info("File field {} with file name detected.", name, item.getName()); log.info("Start to receive bytes (estimated bytes)", Integer.toString(req.getContentLength())); int bytes = IOUtils.copy(stream, repoItemOutputStrem); resp.setStatus(SC_OK); log.info("Bytes received: {}", Integer.toString(bytes)); } } } } catch (FileUploadException e) { throw new IOException(e); } }
From source file:foo.domaintest.http.HttpApiModule.java
@Provides @Singleton// w w w .ja v a2 s. c om Multimap<String, String> provideParameterMap(@RequestData("queryString") String queryString, @RequestData("postBody") Lazy<String> lazyPostBody, @RequestData("charset") String requestCharset, FileItemIterator multipartIterator) { // Calling request.getParameter() or request.getParameterMap() etc. consumes the POST body. If // we got the "postpayload" param we don't want to parse the body, so use only the query params. // Note that specifying both "payload" and "postpayload" will result in the "payload" param // being honored and the POST body being completely ignored. ImmutableMultimap.Builder<String, String> params = new ImmutableMultimap.Builder<>(); Multimap<String, String> getParams = parseQuery(queryString); params.putAll(getParams); if (getParams.containsKey("postpayload")) { // Treat the POST body as if it was the "payload" param. return params.put("payload", nullToEmpty(lazyPostBody.get())).build(); } // No "postpayload" so it's safe to consume the POST body and look for params there. if (multipartIterator == null) { // Handle GETs and form-urlencoded POST requests. params.putAll(parseQuery(nullToEmpty(lazyPostBody.get()))); } else { // Handle multipart/form-data requests. try { while (multipartIterator != null && multipartIterator.hasNext()) { FileItemStream item = multipartIterator.next(); try (InputStream stream = item.openStream()) { params.put(item.isFormField() ? item.getFieldName() : item.getName(), CharStreams.toString(new InputStreamReader(stream, requestCharset))); } } } catch (FileUploadException | IOException e) { // Ignore the failure and fall through to return whatever params we managed to parse. } } return params.build(); }
From source file:hk.hku.cecid.corvus.http.PartnershipSenderUnitTest.java
/** * A Helper method which assert whether the HTTP content received in the HTTP monitor * is a multi-part form data, with basic-auth and well-formed partnership operation request. */// w ww. j a v a 2 s.c o m private void assertHttpRequestReceived() throws Exception { // Debug print information. Map headers = monitor.getHeaders(); // #0 Assertion assertFalse("No HTTP header found in the captured data.", headers.isEmpty()); Map.Entry tmp = null; Iterator itr = null; itr = headers.entrySet().iterator(); logger.info("Header information"); while (itr.hasNext()) { tmp = (Map.Entry) itr.next(); logger.info(tmp.getKey() + " : " + tmp.getValue()); } // #1 Check BASIC authentication value. String basicAuth = (String) headers.get("Authorization"); // #1 Assertion assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth); String[] authToken = basicAuth.split(" "); // There are 2 token, one is the "Basic" and another is the base64 auth value. assertTrue(authToken.length == 2); assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic")); // #1 Decode the base64 authentication value to see whether it is "corvus:corvus". String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8"); assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential); // #2 Check content Type String contentType = monitor.getContentType(); String mediaType = contentType.split(";")[0]; assertEquals("Invalid content type", "multipart/form-data", mediaType); // #3 Check the multi-part content. // Make a request context that bridge the content from our monitor to FileUpload library. RequestContext rc = new RequestContext() { public String getCharacterEncoding() { return "charset=ISO-8859-1"; } public int getContentLength() { return monitor.getContentLength(); } public String getContentType() { return monitor.getContentType(); } public InputStream getInputStream() { return monitor.getInputStream(); } }; FileUpload multipartParser = new FileUpload(); FileItemIterator item = multipartParser.getItemIterator(rc); FileItemStream fstream = null; /* * For each field in the partnership, we have to check the existence of the * associated field in the HTTP request. Also we check whether the content * of that web form field has same data to the field in the partnership. */ itr = this.target.getPartnershipMapping().entrySet().iterator(); Map data = ((KVPairData) this.target.properties).getProperties(); Map.Entry e; // an entry representing the partnership data to web form name mapping. String formParamName; // a temporary pointer pointing to the value in the entry. Object dataValue; // a temporary pointer pointing to the value in the partnership data. while (itr.hasNext()) { e = (Map.Entry) itr.next(); formParamName = (String) e.getValue(); // Add new part if the mapped key is not null. if (formParamName != null) { assertTrue("Insufficient number of web form parameter hit.", item.hasNext()); // Get the next multi-part element. fstream = item.next(); // Assert field name assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName()); // Assert field content dataValue = data.get(e.getKey()); if (dataValue instanceof String) { // Assert content equal. assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null)); } else if (dataValue instanceof byte[]) { byte[] expectedBytes = (byte[]) dataValue; byte[] actualBytes = IOHandler.readBytes(fstream.openStream()); // Assert byte length equal assertEquals(expectedBytes.length, actualBytes.length); for (int j = 0; j < expectedBytes.length; j++) assertEquals(expectedBytes[j], actualBytes[j]); } else { throw new IllegalArgumentException("Invalid content found in multipart."); } // Log information. logger.info("Field name found and verifed: " + fstream.getFieldName() + " content type:" + fstream.getContentType()); } } /* Check whether the partnership operation in the HTTP request is expected as i thought */ assertTrue("Missing request_action ?!", item.hasNext()); fstream = item.next(); assertEquals("request_action", fstream.getFieldName()); // Assert the request_action has same content the operation name. Map partnershipOpMap = this.target.getPartnershipOperationMapping(); assertEquals(partnershipOpMap.get(new Integer(this.target.getExecuteOperation())), IOHandler.readString(fstream.openStream(), null)); }
From source file:com.liferay.faces.bridge.context.map.internal.MultiPartFormDataProcessorImpl.java
@Override public Map<String, List<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, List<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();/* www . ja v a 2s.c o m*/ } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). long uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getLongValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, List<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) BridgeFactoryFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:com.boundlessgeo.geoserver.api.controllers.ImportController.java
/** * API endpoint to import a file or list of files as a new layer or layers into into an existing * store inGeoServer. /*from w w w. j a v a 2 s . c o m*/ * Files are provided as MediaType.MULTIPART_FORM_DATA_VALUE in the request * @param wsName The workspace to import the files into * @param storeName The store to import the layers into. If null, tries to import into a new * store. * @param request The HTTP request * @return a JSON object describing the result of the import. See {@link #get(String, Long) get}. * @throws Exception if the request is invalid, or the file upload fails. */ @RequestMapping(value = "/{wsName:.+}/{storeName:.+}", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public @ResponseBody JSONObj importFile(@PathVariable String wsName, @PathVariable String storeName, HttpServletRequest request) throws Exception { // grab the workspace Catalog catalog = geoServer.getCatalog(); WorkspaceInfo ws = findWorkspace(wsName, catalog); // get the uploaded files FileItemIterator files = doFileUpload(request); if (!files.hasNext()) { throw new BadRequestException("Request must contain one or more files"); } // create a new temp directory for the uploaded file File uploadDir = Files.createTempDirectory("importFile").toFile(); if (!uploadDir.exists()) { throw new RuntimeException("Unable to create directory for file upload"); } uploadDir.deleteOnExit(); // pass off the uploaded file(s) to the importer Directory dir = new Directory(uploadDir); while (files.hasNext()) { FileItemStream item = files.next(); try (InputStream stream = item.openStream()) { String name = item.getName(); dir.accept(name, stream); } } Long id; if (storeName == null) { id = importer.createContextAsync(dir, ws, null); } else { StoreInfo store = findStore(wsName, storeName, geoServer.getCatalog()); id = importer.createContextAsync(dir, ws, store); } return get(wsName, createImport(importer.getTask(id)), request); }
From source file:com.liferay.faces.bridge.context.map.MultiPartFormDataProcessorImpl.java
@Override public Map<String, Collection<UploadedFile>> process(ClientDataRequest clientDataRequest, PortletConfig portletConfig, FacesRequestParameterMap facesRequestParameterMap) { Map<String, Collection<UploadedFile>> uploadedFileMap = null; PortletSession portletSession = clientDataRequest.getPortletSession(); String uploadedFilesDir = PortletConfigParam.UploadedFilesDir.getStringValue(portletConfig); // Using the portlet sessionId, determine a unique folder path and create the path if it does not exist. String sessionId = portletSession.getId(); // FACES-1452: Non-alpha-numeric characters must be removed order to ensure that the folder will be // created properly. sessionId = sessionId.replaceAll("[^A-Za-z0-9]", StringPool.BLANK); File uploadedFilesPath = new File(uploadedFilesDir, sessionId); if (!uploadedFilesPath.exists()) { uploadedFilesPath.mkdirs();//from w w w . j a va 2s . c om } // Initialize commons-fileupload with the file upload path. DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); diskFileItemFactory.setRepository(uploadedFilesPath); // Initialize commons-fileupload so that uploaded temporary files are not automatically deleted. diskFileItemFactory.setFileCleaningTracker(null); // Initialize the commons-fileupload size threshold to zero, so that all files will be dumped to disk // instead of staying in memory. diskFileItemFactory.setSizeThreshold(0); // Determine the max file upload size threshold (in bytes). int uploadedFileMaxSize = PortletConfigParam.UploadedFileMaxSize.getIntegerValue(portletConfig); // Parse the request parameters and save all uploaded files in a map. PortletFileUpload portletFileUpload = new PortletFileUpload(diskFileItemFactory); portletFileUpload.setFileSizeMax(uploadedFileMaxSize); uploadedFileMap = new HashMap<String, Collection<UploadedFile>>(); // FACES-271: Include name+value pairs found in the ActionRequest. Set<Map.Entry<String, String[]>> actionRequestParameterSet = clientDataRequest.getParameterMap().entrySet(); for (Map.Entry<String, String[]> mapEntry : actionRequestParameterSet) { String parameterName = mapEntry.getKey(); String[] parameterValues = mapEntry.getValue(); if (parameterValues.length > 0) { for (String parameterValue : parameterValues) { facesRequestParameterMap.addValue(parameterName, parameterValue); } } } UploadedFileFactory uploadedFileFactory = (UploadedFileFactory) FactoryExtensionFinder .getFactory(UploadedFileFactory.class); // Begin parsing the request for file parts: try { FileItemIterator fileItemIterator = null; if (clientDataRequest instanceof ResourceRequest) { ResourceRequest resourceRequest = (ResourceRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(new ActionRequestAdapter(resourceRequest)); } else { ActionRequest actionRequest = (ActionRequest) clientDataRequest; fileItemIterator = portletFileUpload.getItemIterator(actionRequest); } boolean optimizeNamespace = PortletConfigParam.OptimizePortletNamespace.getBooleanValue(portletConfig); if (fileItemIterator != null) { int totalFiles = 0; String namespace = facesRequestParameterMap.getNamespace(); // For each field found in the request: while (fileItemIterator.hasNext()) { try { totalFiles++; // Get the stream of field data from the request. FileItemStream fieldStream = (FileItemStream) fileItemIterator.next(); // Get field name from the field stream. String fieldName = fieldStream.getFieldName(); // If namespace optimization is enabled and the namespace is present in the field name, // then remove the portlet namespace from the field name. if (optimizeNamespace) { int pos = fieldName.indexOf(namespace); if (pos >= 0) { fieldName = fieldName.substring(pos + namespace.length()); } } // Get the content-type, and file-name from the field stream. String contentType = fieldStream.getContentType(); boolean formField = fieldStream.isFormField(); String fileName = null; try { fileName = fieldStream.getName(); } catch (InvalidFileNameException e) { fileName = e.getName(); } // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the // current field is a simple form-field because the call below to diskFileItem.getString() // will fail otherwise. DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName, contentType, formField, fileName); Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true); // If the current field is a simple form-field, then save the form field value in the map. if (diskFileItem.isFormField()) { String characterEncoding = clientDataRequest.getCharacterEncoding(); String requestParameterValue = null; if (characterEncoding == null) { requestParameterValue = diskFileItem.getString(); } else { requestParameterValue = diskFileItem.getString(characterEncoding); } facesRequestParameterMap.addValue(fieldName, requestParameterValue); } else { File tempFile = diskFileItem.getStoreLocation(); // If the copy was successful, then if (tempFile.exists()) { // Copy the commons-fileupload temporary file to a file in the same temporary // location, but with the filename provided by the user in the upload. This has two // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying // the file, the developer can have access to a semi-permanent file, because the // commmons-fileupload DiskFileItem.finalize() method automatically deletes the // temporary one. String tempFileName = tempFile.getName(); String tempFileAbsolutePath = tempFile.getAbsolutePath(); String copiedFileName = stripIllegalCharacters(fileName); String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName, copiedFileName); File copiedFile = new File(copiedFileAbsolutePath); FileUtils.copyFile(tempFile, copiedFile); // If present, build up a map of headers. Map<String, List<String>> headersMap = new HashMap<String, List<String>>(); FileItemHeaders fileItemHeaders = fieldStream.getHeaders(); if (fileItemHeaders != null) { Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames(); if (headerNameItr != null) { while (headerNameItr.hasNext()) { String headerName = headerNameItr.next(); Iterator<String> headerValuesItr = fileItemHeaders .getHeaders(headerName); List<String> headerValues = new ArrayList<String>(); if (headerValuesItr != null) { while (headerValuesItr.hasNext()) { String headerValue = headerValuesItr.next(); headerValues.add(headerValue); } } headersMap.put(headerName, headerValues); } } } // Put a valid UploadedFile instance into the map that contains all of the // uploaded file's attributes, along with a successful status. Map<String, Object> attributeMap = new HashMap<String, Object>(); String id = Long.toString(((long) hashCode()) + System.currentTimeMillis()); String message = null; UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile( copiedFileAbsolutePath, attributeMap, diskFileItem.getCharSet(), diskFileItem.getContentType(), headersMap, id, message, fileName, diskFileItem.getSize(), UploadedFile.Status.FILE_SAVED); facesRequestParameterMap.addValue(fieldName, copiedFileAbsolutePath); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); logger.debug("Received uploaded file fieldName=[{0}] fileName=[{1}]", fieldName, fileName); } else { if ((fileName != null) && (fileName.trim().length() > 0)) { Exception e = new IOException("Failed to copy the stream of uploaded file=[" + fileName + "] to a temporary file (possibly a zero-length uploaded file)"); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); String fieldName = Integer.toString(totalFiles); addUploadedFile(uploadedFileMap, fieldName, uploadedFile); } } } } // If there was an error in parsing the request for file parts, then put a bogus UploadedFile instance in // the map so that the developer can have some idea that something went wrong. catch (Exception e) { logger.error(e); UploadedFile uploadedFile = uploadedFileFactory.getUploadedFile(e); addUploadedFile(uploadedFileMap, "unknown", uploadedFile); } return uploadedFileMap; }
From source file:net.ymate.platform.mvc.web.support.FileUploadHelper.java
/** * ???????//from w w w .j a v a 2 s. c om * * @param processer * @throws IOException * @throws FileUploadException */ private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer) throws FileUploadException, IOException { ServletFileUpload _upload = new ServletFileUpload(); if (this.__listener != null) { _upload.setProgressListener(this.__listener); } _upload.setFileSizeMax(this.__fileSizeMax); _upload.setSizeMax(this.__sizeMax); UploadFormWrapper _form = new UploadFormWrapper(); Map<String, List<String>> tmpParams = new HashMap<String, List<String>>(); Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>(); // FileItemIterator _iter = _upload.getItemIterator(this.__request); while (_iter.hasNext()) { FileItemStream _item = _iter.next(); if (_item.isFormField()) { List<String> _valueList = tmpParams.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<String>(); tmpParams.put(_item.getFieldName(), _valueList); } _valueList.add(Streams.asString(_item.openStream(), WebMVC.getConfig().getCharsetEncoding())); } else { List<UploadFileWrapper> _valueList2 = tmpFiles.get(_item.getFieldName()); if (_valueList2 == null) { _valueList2 = new ArrayList<UploadFileWrapper>(); tmpFiles.put(_item.getFieldName(), _valueList2); } // ?? _valueList2.add(processer.process(_item)); } } // for (Entry<String, List<String>> entry : tmpParams.entrySet()) { String key = entry.getKey(); List<String> value = entry.getValue(); _form.getFieldMap().put(key, value.toArray(new String[value.size()])); } for (Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) { String key = entry.getKey(); _form.getFileMap().put(key, entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()])); } return _form; }
From source file:net.ymate.platform.webmvc.util.FileUploadHelper.java
/** * ???????//w ww . java 2 s.c o m * * @param processer ? * @throws FileUploadException ? * @throws IOException ? */ private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer) throws FileUploadException, IOException { ServletFileUpload _upload = new ServletFileUpload(); _upload.setFileSizeMax(__fileSizeMax); _upload.setSizeMax(__sizeMax); if (__listener != null) { _upload.setProgressListener(__listener); } Map<String, List<String>> tmpParams = new HashMap<String, List<String>>(); Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>(); // FileItemIterator _fileItemIT = _upload.getItemIterator(__request); while (_fileItemIT.hasNext()) { FileItemStream _item = _fileItemIT.next(); if (_item.isFormField()) { List<String> _valueList = tmpParams.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<String>(); tmpParams.put(_item.getFieldName(), _valueList); } _valueList.add(Streams.asString(_item.openStream(), __charsetEncoding)); } else { List<UploadFileWrapper> _valueList = tmpFiles.get(_item.getFieldName()); if (_valueList == null) { _valueList = new ArrayList<UploadFileWrapper>(); tmpFiles.put(_item.getFieldName(), _valueList); } // ?? _valueList.add(processer.process(_item)); } } // UploadFormWrapper _form = new UploadFormWrapper(); for (Map.Entry<String, List<String>> entry : tmpParams.entrySet()) { _form.getFieldMap().put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()])); } for (Map.Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) { _form.getFileMap().put(entry.getKey(), entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()])); } return _form; }