List of usage examples for org.apache.commons.fileupload FileItem getInputStream
InputStream getInputStream() throws IOException;
From source file:org.niord.web.MessageExportRestService.java
/** {@inheritDoc} */ @Override/*from ww w . ja v a 2 s.c om*/ protected void checkBatchJob(String batchJobName, FileItem fileItem, Map<String, Object> params) throws Exception { // Check that the zip file contains a messages.json file if (!checkForMessagesFileInImportArchive(fileItem.getInputStream())) { throw new Exception("Zip archive is missing a valid messages.json entry"); } // Read and validate the parameters associated with the batch job ImportMessagesArchiveParams batchData; try { batchData = new ObjectMapper().readValue((String) params.get("data"), ImportMessagesArchiveParams.class); } catch (IOException e) { throw new Exception("Missing batch data with tag and message series", e); } if (StringUtils.isBlank(batchData.getSeriesId())) { throw new Exception("Missing message series for imported NMs"); } // Determine all valid message series for the current user Set<String> validMessageSeries = domainService.domainsWithUserRole(Roles.ADMIN).stream() .flatMap(d -> d.getMessageSeries().stream()).map(MessageSeries::getSeriesId) .collect(Collectors.toSet()); // Update parameters params.remove("data"); params.put("seriesId", batchData.getSeriesId()); if (StringUtils.isNotBlank(batchData.getTagId())) { params.put("tagId", batchData.getTagId()); } params.put("assignNewUids", batchData.getAssignNewUids() == null ? false : batchData.getAssignNewUids()); params.put("preserveStatus", batchData.getPreserveStatus() == null ? false : batchData.getPreserveStatus()); params.put("assignDefaultSeries", batchData.getAssignDefaultSeries() == null ? false : batchData.getAssignDefaultSeries()); params.put("createBaseData", batchData.getCreateBaseData() == null ? false : batchData.getCreateBaseData()); params.put("validMessageSeries", validMessageSeries); }
From source file:org.niord.web.PublicationRestService.java
/** * Uploads a publication file//from w w w .ja va 2s. c om * * @param request the servlet request * @return the updated publication descriptor */ @POST @Path("/upload-publication-file/{folder:.+}") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces("application/json;charset=UTF-8") @RolesAllowed(Roles.ADMIN) public PublicationDescVo uploadPublicationFile(@PathParam("folder") String path, @Context HttpServletRequest request) throws Exception { List<FileItem> items = repositoryService.parseFileUploadRequest(request); // Get hold of the first uploaded publication file FileItem fileItem = items.stream().filter(item -> !item.isFormField()).findFirst() .orElseThrow(() -> new WebApplicationException("No uploaded publication file", 400)); // Check for the associated publication desc record PublicationDescVo desc = items.stream() .filter(item -> item.isFormField() && "data".equals(item.getFieldName())).map(item -> { try { return new ObjectMapper().readValue(item.getString("UTF-8"), PublicationDescVo.class); } catch (Exception ignored) { } return null; }).filter(Objects::nonNull).findFirst() .orElseThrow(() -> new WebApplicationException("No publication descriptor found", 400)); // Validate that the path is a temporary repository folder path java.nio.file.Path folder = checkCreateTempRepoPath(path); String fileName = StringUtils.defaultIfBlank(desc.getFileName(), Paths.get(fileItem.getName()).getFileName().toString()); // NB: IE includes the path in item.getName()! File destFile = folder.resolve(fileName).toFile(); try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile))) { IOUtils.copy(fileItem.getInputStream(), out); } catch (IOException ex) { log.error("Error creating publication file " + destFile, ex); throw new WebApplicationException("Error creating destination file: " + destFile, 500); } desc.setFileName(fileName); desc.setLink(repositoryService.getRepoUri(destFile.toPath())); log.info("Copied publication file " + fileItem.getName() + " to destination " + destFile); return desc; }
From source file:org.nordapp.web.servlet.DEVServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from w w w .j a v a 2s . c o m //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler (HTTP) and session control (OSGi) // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); //RequestHandler rqHdl = new RequestHandler(context, ctrl); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); ctrl.setAll(); ctrl.saveTempSession(); // // Session and other services // String cert = null; //The '0' session of the mandator Session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), "0"); //The 'user' session mSession = SessionServiceImpl.getSession(context, cert, ctrl.getMandatorID(), ctrl.decodeCert().toString()); if (mSession == null) { List<String> list = ctrl.getShortTimePassword(); if (ctrl.getCertID() == null || (!list.contains(ctrl.getCertID()))) throw new UnavailableException("Needs a valid User-Session."); } //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } // // Get some data // FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); // // prepare the engine // String[] elem = RequestPath.getPath(req); if (elem.length != 0) throw new MalformedURLException("The URL needs the form '" + req.getServletPath() + "' but was '" + req.getRequestURI() + "'"); // // Initialize the work // ServiceReference<DeployService> srDeploy = context.getServiceReference(DeployService.class); if (srDeploy == null) throw new IOException( "The deploy service reference is not available (maybe down or a version conflict)."); DeployService svDeploy = context.getService(srDeploy); if (svDeploy == null) throw new IOException("The deploy service is not available (maybe down or a version conflict)."); String processID = IdGen.getURLSafeString(IdGen.getUUID()); String mandatorID = ctrl.getMandatorID(); String groupID = ctrl.getGroupID(); String artifactID = ctrl.getArtifactID(); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data } else { File zip = svDeploy.createEmptyZip(processID, mandatorID, groupID, artifactID); OutputStream os = new FileOutputStream(zip); InputStream is = item.getInputStream(); try { IOUtils.copy(is, os); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } svDeploy.zipToData(processID, mandatorID, groupID, artifactID, zip.getName()); } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } // // Prints the result from the user-session // StringBuffer buffer = new StringBuffer(); ResponseHandler rsHdl = new ResponseHandler(context, ctrl); logger.debug("The user session is{}found mandatorId:{}, sessionId:{}.", (mSession == null ? " not " : " "), ctrl.getMandatorID(), ctrl.getCertID()); rsHdl.getSessionData(buffer, mSession); // // // byte[] bytes = buffer.toString().getBytes(); // // Send the resource // rsHdl.avoidCaching(resp); rsHdl.sendData(bytes, resp); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.nordapp.web.servlet.SessionCallServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {/* w w w . j a v a2 s . c om*/ //@SuppressWarnings("unused") final String mandatorId = RequestPath.getMandator(req); final String uuid = RequestPath.getSession(req); // // Session handler // //SessionControl ctrl = new HttpSessionControlImpl(context, req.getSession()); SessionControl ctrl = new SessionControlImpl(context); ctrl.setMandatorID(mandatorId); ctrl.setCertID(uuid); ctrl.loadTempSession(); ctrl.getAll(); ctrl.incRequestCounter(); ctrl.setAll(); ctrl.saveTempSession(); // // Process upload // // Create a factory for disk-based file items DiskFileItemFactory factory = new DiskFileItemFactory(); // sets memory threshold - beyond which files are stored in disk factory.setSizeThreshold(MEMORY_THRESHOLD); //The mandator Mandator mandator = MandatorServiceImpl.getMandator(context, ctrl.getMandatorID()); if (mandator == null) { throw new UnavailableException("Needs a valid mandator id:" + ctrl.getMandatorID() + "."); } FilePath tmpLoc = FilePath.get(mandator.getPath()).add("temp"); File repository = tmpLoc.add("http-upload").toFile(); if (!repository.exists()) { repository.mkdirs(); } factory.setRepository(repository); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // sets maximum size of upload file upload.setFileSizeMax(MAX_FILE_SIZE); // sets maximum size of request (include file + form data) upload.setSizeMax(MAX_REQUEST_SIZE); // Gets the JSON data GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(LinkedHashMap.class, new GsonHashMapDeserializer()); Gson gson = gsonBuilder.create(); Map<String, Object> res = new HashMap<String, Object>(); try { // parses the request's content to extract file data //@SuppressWarnings("unchecked") List<FileItem> formItems = upload.parseRequest(req); if (formItems != null && formItems.size() > 0) { // iterates over form's fields for (FileItem item : formItems) { // processes only fields that are not form fields if (item.isFormField()) { //data res.put(item.getFieldName(), item.getString()); //ioc.setField(item.getFieldName(), item); } else { //Gets JSON as Stream Reader json = new InputStreamReader(item.getInputStream()); //String json = item.getString(); try { @SuppressWarnings("unchecked") LinkedHashMap<String, Object> mapJ = gson.fromJson(json, LinkedHashMap.class); for (String key : mapJ.keySet()) { Object val = mapJ.get(key); if (val == null) continue; res.put(key, val); } //for } finally { json.close(); } } //fi } //for } //fi } catch (Exception ex) { req.setAttribute("message", "There was an error: " + ex.getMessage()); } process(ctrl, req, resp, res); } catch (Exception e) { ResponseHandler rsHdl = new ResponseHandler(context, null); rsHdl.sendError(logger, e, resp, null); } }
From source file:org.nuxeo.ecm.platform.ui.web.util.FileUploadHelper.java
/** * Parses a Multipart Servlet Request to extract blobs *//* w w w. j ava 2 s.c o m*/ public static List<Blob> parseRequest(HttpServletRequest request) throws FileUploadException, IOException { List<Blob> blobs = new ArrayList<Blob>(); if (request instanceof MultipartRequest) { MultipartRequest seamMPRequest = (MultipartRequest) request; Enumeration<String> names = seamMPRequest.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); try (InputStream in = seamMPRequest.getFileInputStream(name)) { if (in != null) { Blob blob = Blobs.createBlob(in); blob.setFilename(seamMPRequest.getFileName(name)); blobs.add(blob); } } } } else { // fallback method for non-seam servlet request FileUpload fu = new FileUpload(new DiskFileItemFactory()); String fileNameCharset = request.getHeader("FileNameCharset"); if (fileNameCharset != null) { fu.setHeaderEncoding(fileNameCharset); } ServletRequestContext requestContext = new ServletRequestContext(request); List<FileItem> fileItems = fu.parseRequest(requestContext); for (FileItem item : fileItems) { try (InputStream is = item.getInputStream()) { Blob blob = Blobs.createBlob(is); blob.setFilename(item.getName()); blobs.add(blob); } } } return blobs; }
From source file:org.nuxeo.ecm.webengine.forms.FormData.java
protected Blob getBlob(FileItem item) { StreamSource src;/* w w w.j a v a2 s.co m*/ if (item.isInMemory()) { src = new ByteArraySource(item.get()); } else { try { src = new InputStreamSource(item.getInputStream()); } catch (IOException e) { throw WebException.wrap("Failed to get blob data", e); } } String ctype = item.getContentType(); StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype); try { blob.persist(); } catch (IOException e) { log.error(e, e); } blob.setFilename(item.getName()); return blob; }
From source file:org.nuxeo.ecm.webengine.util.FormData.java
protected Blob getBlob(FileItem item) throws WebException { StreamSource src;/*from ww w .jav a 2 s . c o m*/ if (item.isInMemory()) { src = new ByteArraySource(item.get()); } else { try { src = new InputStreamSource(item.getInputStream()); } catch (IOException e) { throw new WebException("Failed to get blob data", e); } } String ctype = item.getContentType(); StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype); blob.setFilename(item.getName()); return blob; }
From source file:org.nuxeo.opensocial.container.server.handler.AbstractActionHandler.java
protected static Blob getBlob(FileItem item) { StreamSource src;/*from w ww . j a va2s .c o m*/ if (item.isInMemory()) { src = new ByteArraySource(item.get()); } else { try { src = new InputStreamSource(item.getInputStream()); } catch (IOException e) { throw WebException.wrap("Failed to get blob data", e); } } String ctype = item.getContentType(); StreamingBlob blob = new StreamingBlob(src, ctype == null ? "application/octet-stream" : ctype); blob.setFilename(item.getName()); return blob; }
From source file:org.obiba.mica.file.rest.TempFilesResource.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Timed//from ww w . ja v a 2 s. com public Response upload(@Context HttpServletRequest request, @Context UriInfo uriInfo) throws IOException, FileUploadException { FileItem fileItem = getUploadedFile(request); if (fileItem == null) throw new FileUploadException("Failed to extract file item from request"); TempFile tempFile = tempFileService.addTempFile(fileItem.getName(), fileItem.getInputStream()); URI location = uriInfo.getBaseUriBuilder().path(TempFilesResource.class) .path(TempFilesResource.class, "file").build(tempFile.getId()); return Response.created(location).build(); }
From source file:se.streamsource.surface.web.context.FormDraftContext.java
public JSONArray createattachment(Response response) throws Exception { Request request = response.getRequest(); Representation representation = request.getEntity(); if (MediaType.MULTIPART_FORM_DATA.equals(representation.getMediaType(), true)) { RestletFileUpload upload = new RestletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); try {//from w ww .j a va 2s . com List<FileItem> items = upload.parseRequest(request); int numberOfFiles = 0; FileItem fi = null; for (FileItem fileItem : items) { if (!fileItem.isFormField()) { numberOfFiles++; fi = fileItem; } } if (numberOfFiles != 1) { throw new ResourceException(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED, "Could not handle multiple files"); } if (!acceptedTypes.contains(MediaType.valueOf(fi.getContentType()))) { throw new ResourceException(Status.CLIENT_ERROR_UNSUPPORTED_MEDIA_TYPE, "Could not upload file"); } Representation input = new InputRepresentation(new BufferedInputStream(fi.getInputStream())); Form disposition = new Form(); disposition.set(Disposition.NAME_FILENAME, fi.getName()); disposition.set(Disposition.NAME_SIZE, Long.toString(fi.getSize())); input.setDisposition(new Disposition(Disposition.TYPE_NONE, disposition)); CommandQueryClient client = RoleMap.current().get(CommandQueryClient.class); AttachmentResponseHandler responseHandler = module.objectBuilderFactory() .newObjectBuilder(AttachmentResponseHandler.class).newInstance(); client.getClient("attachments/").postCommand("createformattachment", input, responseHandler); ValueBuilder<UpdateAttachmentDTO> attachmentUpdateBuilder = module.valueBuilderFactory() .newValueBuilder(UpdateAttachmentDTO.class); attachmentUpdateBuilder.prototype().name().set(fi.getName()); attachmentUpdateBuilder.prototype().size().set(fi.getSize()); attachmentUpdateBuilder.prototype().mimeType().set(fi.getContentType()); ValueBuilder<AttachmentFieldDTO> attachmentFieldUpdateBuilder = responseHandler .getAttachmentValue(); // update attachment entity first with filename, size and mime type client.getClient("attachments/" + attachmentFieldUpdateBuilder.prototype().attachment().get().identity() + "/") .postCommand("update", attachmentUpdateBuilder.newInstance()); attachmentFieldUpdateBuilder.prototype().field() .set(EntityReference.parseEntityReference(fi.getFieldName())); attachmentFieldUpdateBuilder.prototype().name().set(fi.getName()); // update form submission attachment field with name and attachment field entity reference. client.postCommand("updateattachmentfield", attachmentFieldUpdateBuilder.newInstance()); StringBuffer result = new StringBuffer("[").append(attachmentUpdateBuilder.newInstance().toJSON()) .append("]"); return new JSONArray(result.toString()); } catch (FileUploadException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not upload file", e); } catch (IOException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Could not upload file", e); } } return null; }