List of usage examples for org.apache.commons.fileupload FileItemStream getName
String getName();
From source file:com.github.terma.gigaspacewebconsole.server.ImportServlet.java
private void safeDoPost(final HttpServletRequest request) throws Exception { final ServletFileUpload upload = new ServletFileUpload(); final FileItemIterator iterator = upload.getItemIterator(request); ImportRequest importRequest = null;/*from www .ja v a2 s .c o m*/ String inputFile = null; InputStream inputStream = null; while (iterator.hasNext()) { final FileItemStream item = iterator.next(); final String name = item.getFieldName(); final InputStream stream = item.openStream(); if (item.isFormField()) { if ("json".equals(name)) { importRequest = gson.fromJson(Streams.asString(stream), ImportRequest.class); } } else { inputFile = item.getName(); inputStream = stream; break; } } if (importRequest == null) throw new IOException("Expect 'json' parameter!"); if (inputStream == null) throw new IOException("Expect file to import!"); importRequest.file = inputFile; ProviderResolver.getProvider(importRequest.driver).import1(importRequest, inputStream); }
From source file:com.google.dotorg.translation_workflow.servlet.UploadServlet.java
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, MalformedURLException { String rawProjectId = request.getParameter("projectId"); try {/*from w w w . ja v a 2s . co m*/ ServletFileUpload upload = new ServletFileUpload(); upload.setSizeMax(1048576); UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); Cloud cloud = Cloud.open(); int projectId = Integer.parseInt(rawProjectId); Project project = cloud.getProjectById(projectId); TextValidator nameValidator = TextValidator.BRIEF_STRING; String invalidRows = ""; int validRows = 0; try { FileItemIterator iterator = upload.getItemIterator(request); int articlesLength = 0; while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream in = item.openStream(); if (item.isFormField()) { } else { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); String fileContents = null; if (!contentType.equalsIgnoreCase("text/csv")) { logger.warning("Invalid filetype upload " + contentType); response.sendRedirect( "/project_overview?project=" + rawProjectId + "&msg=invalid_type"); } try { fileContents = IOUtils.toString(in); PersistenceManager pm = cloud.getPersistenceManager(); Transaction tx = pm.currentTransaction(); tx.begin(); String[] lines = fileContents.split("\n"); List<Translation> newTranslations = new ArrayList<Translation>(); articlesLength = lines.length; validRows = articlesLength; int lineNo = 0; for (String line : lines) { lineNo++; line = line.replaceAll("\",", "\";"); line = line.replaceAll("\"", ""); String[] fields = line.split(";"); String articleName = fields[0].replace("_", " "); articleName = nameValidator.filter(URLDecoder.decode(articleName)); try { URL url = new URL(fields[1]); String category = ""; String difficulty = ""; if (fields.length > 2) { category = nameValidator.filter(fields[2]); } if (fields.length > 3) { difficulty = nameValidator.filter(fields[3]); } Translation translation = project.createTranslation(articleName, url.toString(), category, difficulty); newTranslations.add(translation); } catch (MalformedURLException e) { validRows--; invalidRows = invalidRows + "," + lineNo; logger.warning("Invalid URL : " + fields[1]); } } pm.makePersistentAll(newTranslations); tx.commit(); } finally { IOUtils.closeQuietly(in); } } } cloud.close(); logger.info(validRows + " of " + articlesLength + " articles uploaded from csv to the project " + project.getId() + " by User :" + user.getUserId()); if (invalidRows.length() > 0) { response.sendRedirect( "/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1)); } else { response.sendRedirect("/project_overview?project=" + rawProjectId); } /*response.sendRedirect("/project_overview?project=" + rawProjectId + "&_invalid=" + invalidRows.substring(1));*/ } catch (SizeLimitExceededException e) { logger.warning("Exceeded the maximum size (" + e.getPermittedSize() + ") of the file (" + e.getActualSize() + ")"); response.sendRedirect("/project_overview?project=" + rawProjectId + "&msg=size_exceeded"); } } catch (Exception ex) { logger.info("String " + ex.toString()); throw new ServletException(ex); } }
From source file:com.vmware.photon.controller.api.frontend.resources.vm.VmIsoAttachResource.java
private Task parseIsoDataFromRequest(HttpServletRequest request, String id) throws InternalException, ExternalException { Task task = null;/*from w w w. ja va 2 s .co m*/ ServletFileUpload fileUpload = new ServletFileUpload(); List<InputStream> dataStreams = new LinkedList<>(); try { FileItemIterator iterator = fileUpload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { logger.warn(String.format("The parameter '%s' is unknown in attach ISO.", item.getFieldName())); } else { InputStream fileStream = item.openStream(); dataStreams.add(fileStream); task = vmFeClient.attachIso(id, fileStream, item.getName()); } } } catch (IOException ex) { throw new IsoUploadException("Iso upload IOException", ex); } catch (FileUploadException ex) { throw new IsoUploadException("Iso upload FileUploadException", ex); } finally { for (InputStream stream : dataStreams) { try { stream.close(); } catch (IOException | NullPointerException ex) { logger.warn("Unexpected exception closing data stream.", ex); } } } if (task == null) { throw new IsoUploadException("There is no iso stream data in the iso upload request."); } return task; }
From source file:com.twosigma.beaker.core.module.elfinder.ConnectorController.java
private HttpServletRequest parseMultipartContent(final HttpServletRequest request) throws Exception { if (!ServletFileUpload.isMultipartContent(request)) return request; final Map<String, String> requestParams = new HashMap<String, String>(); List<FileItemStream> listFiles = new ArrayList<FileItemStream>(); // Parse the request ServletFileUpload sfu = new ServletFileUpload(); String characterEncoding = request.getCharacterEncoding(); if (characterEncoding == null) { characterEncoding = "UTF-8"; }// w w w. j a va 2s. c o m sfu.setHeaderEncoding(characterEncoding); FileItemIterator iter = sfu.getItemIterator(request); while (iter.hasNext()) { final FileItemStream item = iter.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { requestParams.put(name, Streams.asString(stream, characterEncoding)); } else { String fileName = item.getName(); if (fileName != null && !"".equals(fileName.trim())) { ByteArrayOutputStream os = new ByteArrayOutputStream(); IOUtils.copy(stream, os); final byte[] bs = os.toByteArray(); stream.close(); listFiles.add((FileItemStream) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { FileItemStream.class }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("openStream".equals(method.getName())) { return new ByteArrayInputStream(bs); } return method.invoke(item, args); } })); } } } request.setAttribute(FileItemStream.class.getName(), listFiles); Object proxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] { HttpServletRequest.class }, new InvocationHandler() { @Override public Object invoke(Object arg0, Method arg1, Object[] arg2) throws Throwable { // we replace getParameter() and getParameterValues() // methods if ("getParameter".equals(arg1.getName())) { String paramName = (String) arg2[0]; return requestParams.get(paramName); } if ("getParameterValues".equals(arg1.getName())) { String paramName = (String) arg2[0]; // normalize name 'key[]' to 'key' if (paramName.endsWith("[]")) paramName = paramName.substring(0, paramName.length() - 2); if (requestParams.containsKey(paramName)) return new String[] { requestParams.get(paramName) }; // if contains key[1], key[2]... int i = 0; List<String> paramValues = new ArrayList<String>(); while (true) { String name2 = String.format("%s[%d]", paramName, i++); if (requestParams.containsKey(name2)) { paramValues.add(requestParams.get(name2)); } else { break; } } return paramValues.isEmpty() ? new String[0] : paramValues.toArray(new String[paramValues.size()]); } return arg1.invoke(request, arg2); } }); return (HttpServletRequest) proxyInstance; }
From source file:com.smartgwt.extensions.fileuploader.server.ProjectServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); boolean isGWT = true; try {/*from ww w . java 2s . c o m*/ if (log.isDebugEnabled()) log.debug(request.getParameterMap()); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { args.put("contentType", item.getContentType()); String fileName = item.getName(); int slash = fileName.lastIndexOf("/"); if (slash < 0) slash = fileName.lastIndexOf("\\"); if (slash > 0) fileName = fileName.substring(slash + 1); args.put("fileName", fileName); // upload requests can come from smartGWT (args) or // FCKEditor (request) String contextName = args.get("context"); String model = args.get("model"); String path = args.get("path"); if (contextName == null) { isGWT = false; contextName = request.getParameter("context"); model = request.getParameter("model"); path = request.getParameter("path"); if (log.isDebugEnabled()) log.debug("query=" + request.getQueryString()); } else if (log.isDebugEnabled()) log.debug(args); // the following code stores the file based on your parameters /* ProjectContext context = ContextService.get().getContext( contextName); ProjectState state = (ProjectState) request.getSession() .getAttribute(contextName); InputStream in = null; try { in = item.openStream(); state.getFileManager().storeFile( context.getModel(model), path + fileName, in); } catch (Exception e) { e.printStackTrace(); log.error("Fail to upload " + fileName + " to " + path); } finally { if (in != null) try { in.close(); } catch (Exception e) { } } */ } } // TODO: need to handle conversion options and error reporting response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); if (isGWT) { out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); } else out.println(getEditorResponse()); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:n3phele.backend.RepoProxy.java
@POST @Path("{id}/upload/{bucket}") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response upload(@PathParam("id") Long id, @PathParam("bucket") String bucket, @QueryParam("name") String destination, @QueryParam("expires") long expires, @QueryParam("signature") String signature, @Context HttpServletRequest request) throws NotFoundException { Repository repo = Dao.repository().load(id); if (!checkTemporaryCredential(expires, signature, repo.getCredential().decrypt().getSecret(), bucket + ":" + destination)) { log.severe("Expired temporary authorization"); throw new NotFoundException(); }/* ww w. j av a 2 s . co m*/ try { ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iterator = upload.getItemIterator(request); log.info("FileSizeMax =" + upload.getFileSizeMax() + " SizeMax=" + upload.getSizeMax() + " Encoding " + upload.getHeaderEncoding()); while (iterator.hasNext()) { FileItemStream item = iterator.next(); if (item.isFormField()) { log.info("FieldName: " + item.getFieldName() + " value:" + Streams.asString(item.openStream())); } else { InputStream stream = item.openStream(); log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName() + " content " + item.getContentType()); URI target = CloudStorage.factory().putObject(repo, stream, item.getContentType(), destination); Response.created(target).build(); } } } catch (Exception e) { log.log(Level.WARNING, "Processing error", e); } return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).build(); }
From source file:com.github.cxt.Myjersey.jerseycore.FileResource.java
@Path("upload2") @POST/*w w w. j a v a 2 s .co m*/ @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.APPLICATION_JSON) public String uploadFile(@Context HttpServletRequest request) throws IOException { //??,httpclent? System.out.println(request.getCharacterEncoding()); ServletFileUpload upload = new ServletFileUpload(); upload.setHeaderEncoding(CHARSET); try { FileItemIterator fileIterator = upload.getItemIterator(request); while (fileIterator.hasNext()) { FileItemStream item = fileIterator.next(); InputStream is = item.openStream(); try { if (!item.isFormField()) { String fileName = item.getName(); if (fileName == null || fileName.trim().equals("")) { continue; } String name = Calendar.getInstance().getTimeInMillis() + fileName; String path = request.getServletContext().getRealPath("/"); path += File.separator + "data" + File.separator + name; File file = new File(path); FileUtils.copyInputStreamToFile(is, file); } else { System.out.println(Streams.asString(is, CHARSET)); } } finally { if (null != is) { try { is.close(); } catch (IOException ignore) { } } } } return "{\"success\": true}"; } catch (IOException | FileUploadException e) { return "{\"success\": false}"; } }
From source file:com.priocept.jcr.server.UploadServlet.java
private void processFiles(HttpServletRequest request, HttpServletResponse response) { HashMap<String, String> args = new HashMap<String, String>(); try {//from w w w.j a va2 s. c o m if (log.isDebugEnabled()) log.debug(request.getParameterMap()); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); // pick up parameters first and note actual FileItem while (iter.hasNext()) { FileItemStream item = iter.next(); String name = item.getFieldName(); if (item.isFormField()) { args.put(name, Streams.asString(item.openStream())); } else { args.put("contentType", item.getContentType()); String fileName = item.getName(); int slash = fileName.lastIndexOf("/"); if (slash < 0) slash = fileName.lastIndexOf("\\"); if (slash > 0) fileName = fileName.substring(slash + 1); args.put("fileName", fileName); if (log.isDebugEnabled()) log.debug(args); InputStream in = null; try { in = item.openStream(); writeToFile(request.getSession().getId() + "/" + fileName, in, true, request.getSession().getServletContext().getRealPath("/")); } catch (Exception e) { // e.printStackTrace(); log.error("Fail to upload " + fileName); response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadFailed) parent.uploadFailed('" + e.getLocalizedMessage().replaceAll("\'|\"", "") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); return; } finally { if (in != null) try { in.close(); } catch (Exception e) { } } } } response.setContentType("text/html"); response.setHeader("Pragma", "No-cache"); response.setDateHeader("Expires", 0); response.setHeader("Cache-Control", "no-cache"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<body>"); out.println("<script type=\"text/javascript\">"); out.println("if (parent.uploadComplete) parent.uploadComplete('" + args.get("fileName") + "');"); out.println("</script>"); out.println("</body>"); out.println("</html>"); out.flush(); } catch (Exception e) { System.out.println(e.getMessage()); } }
From source file:edu.umn.msi.tropix.webgui.server.UploadController.java
@ServiceMethod(secure = true) public ModelAndView handleRequest(final HttpServletRequest request, final HttpServletResponse response) throws Exception { LOG.debug("In UploadController.handleRequest"); //final String userId = securityProvider.getUserIdForSessionId(request.getParameter("sessionId")); //Preconditions.checkState(userId != null); final String userId = userSession.getGridId(); LOG.debug("Upload by user with id " + userId); String clientId = request.getParameter("clientId"); if (!StringUtils.hasText(clientId)) { clientId = UUID.randomUUID().toString(); }/*from w w w. j a v a 2 s. co m*/ final String endStr = request.getParameter("end"); final String startStr = request.getParameter("start"); final String zipStr = request.getParameter("zip"); final String lastUploadStr = request.getParameter("lastUpload"); final boolean isZip = StringUtils.hasText("zip") ? Boolean.parseBoolean(zipStr) : false; final boolean lastUploads = StringUtils.hasText(lastUploadStr) ? Boolean.parseBoolean(lastUploadStr) : true; LOG.trace("Upload request with startStr " + startStr); final StringWriter rawJsonWriter = new StringWriter(); final JSONWriter jsonWriter = new JSONWriter(rawJsonWriter); final FileItemFactory factory = new DiskFileItemFactory(); final long requestLength = StringUtils.hasText(endStr) ? Long.parseLong(endStr) : request.getContentLength(); long bytesWritten = StringUtils.hasText(startStr) ? Long.parseLong(startStr) : 0L; final ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); // Deal with international file names final FileItemIterator iter = upload.getItemIterator(request); // Setup message conditionalSampleComponent to track upload progress... final ProgressMessageSupplier supplier = new ProgressMessageSupplier(); supplier.setId(userId + "/" + clientId); supplier.setName("Upload File(s) to Web Application"); final ProgressTrackerImpl progressTracker = new ProgressTrackerImpl(); progressTracker.setUserGridId(userId); progressTracker.setCometPusher(cometPusher); progressTracker.setProgressMessageSupplier(supplier); jsonWriter.object(); jsonWriter.key("result"); jsonWriter.array(); while (iter.hasNext()) { final FileItemStream item = iter.next(); if (item.isFormField()) { continue; } File destination; InputStream inputStream = null; OutputStream outputStream = null; if (!isZip) { final String fileName = FilenameUtils.getName(item.getName()); // new File(item.getName()).getName(); LOG.debug("Handling upload of file with name " + fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(fileName); recordJsonInfo(jsonWriter, info); destination = info.getTempLocation(); } else { destination = FILE_UTILS.createTempFile(); } try { inputStream = item.openStream(); outputStream = FILE_UTILS.getFileOutputStream(destination); bytesWritten += progressTrackingIoUtils.copy(inputStream, outputStream, bytesWritten, requestLength, progressTracker); if (isZip) { ZipUtilsFactory.getInstance().unzip(destination, new Function<String, File>() { public File apply(final String fileName) { final String cleanedUpFileName = FilenameUtils.getName(fileName); final TempFileInfo info = tempFileStore.getTempFileInfo(cleanedUpFileName); recordJsonInfo(jsonWriter, info); return info.getTempLocation(); } }); } } finally { IO_UTILS.closeQuietly(inputStream); IO_UTILS.closeQuietly(outputStream); if (isZip) { FILE_UTILS.deleteQuietly(destination); } } } if (lastUploads) { progressTracker.complete(); } jsonWriter.endArray(); jsonWriter.endObject(); // response.setStatus(200); final String json = rawJsonWriter.getBuffer().toString(); LOG.debug("Upload json response " + json); response.setContentType("text/html"); // GWT was attaching <pre> tag to result without this response.getOutputStream().println(json); return null; }
From source file:ca.nrc.cadc.beacon.web.resources.FileItemServerResourceTest.java
@Test public void uploadFileItem() throws Exception { final Map<String, Object> requestAttributes = new HashMap<>(); final VOSURI parentURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub")); final VOSURI expectedURI = new VOSURI(URI.create("vos://cadc.nrc.ca!vospace/parent/sub/MYUPLOADFILE.txt")); final DataNode expectedDataNode = new DataNode(expectedURI); final String data = "MYUPLOADDATA"; final byte[] dataBytes = data.getBytes(); final InputStream inputStream = new ByteArrayInputStream(dataBytes); final List<NodeProperty> propertyList = new ArrayList<>(); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#length", "" + dataBytes.length)); propertyList.add(new NodeProperty("ivo://ivoa.net/vospace/core#MD5", new String(MessageDigest.getInstance("MD5").digest(dataBytes)))); expectedDataNode.setProperties(propertyList); requestAttributes.put("path", "my/file.txt"); expect(mockRequest.getEntity()).andReturn(new EmptyRepresentation()).once(); expect(mockServletContext.getContextPath()).andReturn("/teststorage").once(); replay(mockServletContext);//from w w w .j a v a 2 s . c om testSubject = new FileItemServerResource(null, mockVOSpaceClient, new UploadVerifier(), new FileValidator()) { @Override public Response getResponse() { return mockResponse; } @Override ServletContext getServletContext() { return mockServletContext; } @Override public Request getRequest() { return mockRequest; } /** * Returns the request attributes. * * @return The request attributes. * @see Request#getAttributes() */ @Override public Map<String, Object> getRequestAttributes() { return requestAttributes; } @Override VOSURI getCurrentItemURI() { return parentURI; } /** * Abstract away the Transfer stuff. It's cumbersome. * * @param outputStreamWrapper The OutputStream wrapper. * @param dataNode The node to upload. * @throws Exception To capture transfer and upload failures. */ @Override void upload(UploadOutputStreamWrapper outputStreamWrapper, DataNode dataNode) throws Exception { // Do nothing. } @Override <T> T executeSecurely(PrivilegedExceptionAction<T> runnable) throws IOException { try { return runnable.run(); } catch (Exception e) { throw new RuntimeException(e); } } }; final FileItemStream mockFileItemStream = createMock(FileItemStream.class); expect(mockVOSpaceClient.getNode("/parent/sub/MYUPLOADFILE.txt")) .andThrow(new NodeNotFoundException("No such node.")).once(); expect(mockVOSpaceClient.createNode(expectedDataNode, false)).andReturn(expectedDataNode).once(); expect(mockFileItemStream.getName()).andReturn("MYUPLOADFILE.txt").once(); expect(mockFileItemStream.openStream()).andReturn(inputStream).once(); expect(mockFileItemStream.getContentType()).andReturn("text/plain").once(); replay(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream); final VOSURI resultURI = testSubject.upload(mockFileItemStream); assertEquals("End URI is wrong.", expectedURI, resultURI); verify(mockVOSpaceClient, mockResponse, mockRequest, mockFileItemStream, mockServletContext); }