List of usage examples for org.apache.commons.fileupload FileItemStream isFormField
boolean isFormField();
FileItem
instance represents a simple form field. From source file:org.opencastproject.index.service.impl.IndexServiceImpl.java
@Override public String createEvent(HttpServletRequest request) throws InternalServerErrorException, IllegalArgumentException { JSONObject metadataJson = null;//from ww w .j av a 2 s .c o m MediaPackage mp = null; try { if (ServletFileUpload.isMultipartContent(request)) { mp = getIngestService().createMediaPackage(); for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("metadata".equals(fieldName)) { String metadata = Streams.asString(item.openStream()); try { metadataJson = (JSONObject) parser.parse(metadata); } catch (Exception e) { logger.warn("Unable to parse metadata {}", metadata); throw new IllegalArgumentException("Unable to parse metadata"); } } } else { if ("presenter".equals(item.getFieldName())) { mp = getIngestService().addTrack(item.openStream(), item.getName(), MediaPackageElements.PRESENTER_SOURCE, mp); } else if ("presentation".equals(item.getFieldName())) { mp = getIngestService().addTrack(item.openStream(), item.getName(), MediaPackageElements.PRESENTATION_SOURCE, mp); } else if ("audio".equals(item.getFieldName())) { mp = getIngestService().addTrack(item.openStream(), item.getName(), new MediaPackageElementFlavor("presenter-audio", "source"), mp); } else { logger.warn("Unknown field name found {}", item.getFieldName()); } } } } else { throw new IllegalArgumentException("No multipart content"); } // MH-10834 If there is only an audio track, change the flavor from presenter-audio/source to presenter/source. if (mp.getTracks().length == 1 && mp.getTracks()[0].getFlavor() .equals(new MediaPackageElementFlavor("presenter-audio", "source"))) { Track audioTrack = mp.getTracks()[0]; mp.remove(audioTrack); audioTrack.setFlavor(MediaPackageElements.PRESENTER_SOURCE); mp.add(audioTrack); } return createEvent(metadataJson, mp); } catch (Exception e) { logger.error("Unable to create event: {}", ExceptionUtils.getStackTrace(e)); throw new InternalServerErrorException(e.getMessage()); } }
From source file:org.opencastproject.ingest.endpoint.IngestRestService.java
protected Response addMediaPackageElement(HttpServletRequest request, MediaPackageElement.Type type) { MediaPackageElementFlavor flavor = null; try {/*from w ww .j a v a 2 s .co m*/ InputStream in = null; String fileName = null; MediaPackage mp = null; if (ServletFileUpload.isMultipartContent(request)) { boolean isDone = false; for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); String fieldName = item.getFieldName(); if (item.isFormField()) { if ("flavor".equals(fieldName)) { String flavorString = Streams.asString(item.openStream()); if (flavorString != null) { flavor = MediaPackageElementFlavor.parseFlavor(flavorString); } } else if ("mediaPackage".equals(fieldName)) { mp = factory.newMediaPackageBuilder().loadFromXml(item.openStream()); } } else { // once the body gets read iter.hasNext must not be invoked or the stream can not be read // MH-9579 fileName = item.getName(); in = item.openStream(); isDone = true; } if (isDone) { break; } } if (MediaPackageSupport.sanityCheck(mp).isSome()) return Response.serverError().status(Status.BAD_REQUEST).build(); switch (type) { case Attachment: mp = ingestService.addAttachment(in, fileName, flavor, mp); break; case Catalog: mp = ingestService.addCatalog(in, fileName, flavor, mp); break; case Track: mp = ingestService.addTrack(in, fileName, flavor, mp); break; default: throw new IllegalStateException("Type must be one of track, catalog, or attachment"); } // ingestService.ingest(mp); return Response.ok(MediaPackageParser.getAsXml(mp)).build(); } return Response.serverError().status(Status.BAD_REQUEST).build(); } catch (Exception e) { logger.warn(e.getMessage(), e); return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); } }
From source file:org.opencastproject.ingest.endpoint.IngestRestService.java
@POST @Produces(MediaType.TEXT_XML)/* w w w. j a v a 2 s . c om*/ @Consumes(MediaType.MULTIPART_FORM_DATA) @Path("addMediaPackage/{wdID}") @RestQuery(name = "addMediaPackage", description = "Create and ingest media package from media tracks with additional Dublin Core metadata. Notice: It is mandatory to set a title for the recording. This can be done with the 'title' form field or by supplying a DC catalog with a title included.", pathParameters = { @RestParameter(description = "Workflow definition id", isRequired = true, name = "wdID", type = RestParameter.Type.STRING) }, restParameters = { @RestParameter(description = "The kind of media track. This has to be specified in the request prior to each media track", isRequired = true, name = "flavor", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "abstract", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "accessRights", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "available", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "contributor", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "coverage", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "created", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "creator", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "date", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "description", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "extent", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "format", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "identifier", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "isPartOf", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "isReferencedBy", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "isReplacedBy", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "language", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "license", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "publisher", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "relation", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "replaces", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "rights", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "rightsHolder", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "source", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "spatial", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "subject", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "temporal", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "title", type = RestParameter.Type.STRING), @RestParameter(description = "Episode metadata value", isRequired = false, name = "type", type = RestParameter.Type.STRING), @RestParameter(description = "URL of episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalogUri", type = RestParameter.Type.STRING), @RestParameter(description = "Episode DublinCore Catalog", isRequired = false, name = "episodeDCCatalog", type = RestParameter.Type.STRING), @RestParameter(description = "URL of series DublinCore Catalog", isRequired = false, name = "seriesDCCatalogUri", type = RestParameter.Type.STRING), @RestParameter(description = "Series DublinCore Catalog", isRequired = false, name = "seriesDCCatalog", type = RestParameter.Type.STRING), @RestParameter(description = "URL of a media track file", isRequired = false, name = "mediaUri", type = RestParameter.Type.STRING) }, bodyParameter = @RestParameter(description = "The media track file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = { @RestResponse(description = "Returns augmented media package", responseCode = HttpServletResponse.SC_OK), @RestResponse(description = "", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "", responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR) }, returnDescription = "") public Response addMediaPackage(@Context HttpServletRequest request, @PathParam("wdID") String wdID) { MediaPackageElementFlavor flavor = null; try { MediaPackage mp = ingestService.createMediaPackage(); DublinCoreCatalog dcc = null; Map<String, String> workflowProperties = new HashMap<String, String>(); int seriesDCCatalogNumber = 0; int episodeDCCatalogNumber = 0; boolean hasMedia = false; if (ServletFileUpload.isMultipartContent(request)) { for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { String fieldName = item.getFieldName(); String value = Streams.asString(item.openStream()); /* Ignore empty fields */ if ("".equals(value)) { continue; } /* Remember? the flavor for the next media. */ if ("flavor".equals(fieldName)) { flavor = MediaPackageElementFlavor.parseFlavor(value); /* Fields for DC catalog */ } else if (dcterms.contains(fieldName)) { if ("identifier".equals(fieldName)) { /* Use the identifier for the mediapackage */ mp.setIdentifier(new IdImpl(value)); } EName en = new EName(DublinCore.TERMS_NS_URI, fieldName); if (dcc == null) { dcc = dublinCoreService.newInstance(); } dcc.add(en, value); /* Episode metadata by URL */ } else if ("episodeDCCatalogUri".equals(fieldName)) { try { URI dcurl = new URI(value); ingestService.addCatalog(dcurl, MediaPackageElements.EPISODE, mp); episodeDCCatalogNumber += 1; } catch (java.net.URISyntaxException e) { /* Parameter was not a valid URL: Return 400 Bad Request */ logger.warn(e.getMessage(), e); return Response.serverError().status(Status.BAD_REQUEST).build(); } /* Episode metadata DC catalog (XML) as string */ } else if ("episodeDCCatalog".equals(fieldName)) { String fileName = "episode" + episodeDCCatalogNumber + ".xml"; episodeDCCatalogNumber += 1; InputStream is = new ByteArrayInputStream(value.getBytes("UTF-8")); ingestService.addCatalog(is, fileName, MediaPackageElements.EPISODE, mp); /* Series by URL */ } else if ("seriesDCCatalogUri".equals(fieldName)) { try { URI dcurl = new URI(value); ingestService.addCatalog(dcurl, MediaPackageElements.SERIES, mp); } catch (java.net.URISyntaxException e) { /* Parameter was not a valid URL: Return 400 Bad Request */ logger.warn(e.getMessage(), e); return Response.serverError().status(Status.BAD_REQUEST).build(); } /* Series DC catalog (XML) as string */ } else if ("seriesDCCatalog".equals(fieldName)) { String fileName = "series" + seriesDCCatalogNumber + ".xml"; seriesDCCatalogNumber += 1; InputStream is = new ByteArrayInputStream(value.getBytes("UTF-8")); ingestService.addCatalog(is, fileName, MediaPackageElements.SERIES, mp); /* Add media files by URL */ } else if ("mediaUri".equals(fieldName)) { if (flavor == null) { /* A flavor has to be specified in the request prior the media file */ return Response.serverError().status(Status.BAD_REQUEST).build(); } URI mediaUrl; try { mediaUrl = new URI(value); } catch (java.net.URISyntaxException e) { /* Parameter was not a valid URL: Return 400 Bad Request */ logger.warn(e.getMessage(), e); return Response.serverError().status(Status.BAD_REQUEST).build(); } ingestService.addTrack(mediaUrl, flavor, mp); hasMedia = true; } else { /* Tread everything else as workflow properties */ workflowProperties.put(fieldName, value); } /* Media files as request parameter */ } else { if (flavor == null) { /* A flavor has to be specified in the request prior the video file */ return Response.serverError().status(Status.BAD_REQUEST).build(); } ingestService.addTrack(item.openStream(), item.getName(), flavor, mp); hasMedia = true; } } /* Check if we got any media. Fail if not. */ if (!hasMedia) { logger.warn("Rejected ingest without actual media."); return Response.serverError().status(Status.BAD_REQUEST).build(); } Catalog[] dccs = mp.getCatalogs(MediaPackageElements.EPISODE); for (int i = 0; i < dccs.length; i++) { EName en = new EName(DublinCore.TERMS_NS_URI, "identifier"); String id = ((DublinCoreCatalog) dccs[i]).getFirst(en); if (id != null) { mp.setIdentifier(new IdImpl(id)); } } /* Add episode mediapackage if metadata were send separately */ if (dcc != null) { ByteArrayOutputStream out = new ByteArrayOutputStream(); dcc.toXml(out, true); InputStream in = new ByteArrayInputStream(out.toByteArray()); ingestService.addCatalog(in, "dublincore.xml", MediaPackageElements.EPISODE, mp); /* Check if we have metadata for the episode */ } else if (episodeDCCatalogNumber == 0) { logger.warn("Rejected ingest without episode metadata. At least provide a title."); return Response.serverError().status(Status.BAD_REQUEST).build(); } WorkflowInstance workflow = (wdID == null) ? ingestService.ingest(mp) : ingestService.ingest(mp, wdID, workflowProperties); return Response.ok(workflow).build(); } return Response.serverError().status(Status.BAD_REQUEST).build(); } catch (Exception e) { logger.warn(e.getMessage(), e); return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); } }
From source file:org.opencastproject.ingest.endpoint.IngestRestService.java
private Response ingestZippedMediaPackage(HttpServletRequest request, String wdID, String wiID) { if (isIngestLimitEnabled()) { setIngestLimit(getIngestLimit() - 1); logger.debug("An ingest has started so remaining ingest limit is " + getIngestLimit()); }//from ww w.ja va2 s. c o m InputStream in = null; logger.info("Received new request from {} to ingest a zipped mediapackage", request.getRemoteHost()); try { String workflowDefinitionId = wdID; String workflowIdAsString = wiID; Long workflowInstanceIdAsLong = null; Map<String, String> workflowConfig = new HashMap<String, String>(); if (ServletFileUpload.isMultipartContent(request)) { boolean isDone = false; for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { if (WORKFLOW_INSTANCE_ID_PARAM.equals(item.getFieldName())) { workflowIdAsString = IOUtils.toString(item.openStream(), "UTF-8"); continue; } else if (WORKFLOW_DEFINITION_ID_PARAM.equals(item.getFieldName())) { workflowDefinitionId = IOUtils.toString(item.openStream(), "UTF-8"); continue; } else { logger.debug("Processing form field: " + item.getFieldName()); workflowConfig.put(item.getFieldName(), IOUtils.toString(item.openStream(), "UTF-8")); } } else { logger.debug("Processing file item"); // once the body gets read iter.hasNext must not be invoked or the stream can not be read // MH-9579 in = item.openStream(); isDone = true; } if (isDone) break; } } else { logger.debug("Processing file item"); in = request.getInputStream(); } /* Try to convert the workflowId to integer */ if (!StringUtils.isBlank(workflowIdAsString)) { try { workflowInstanceIdAsLong = Long.parseLong(workflowIdAsString); } catch (NumberFormatException e) { logger.warn("{} '{}' is not numeric", WORKFLOW_INSTANCE_ID_PARAM, workflowIdAsString); } } if (StringUtils.isBlank(workflowDefinitionId)) { workflowDefinitionId = defaultWorkflowDefinitionId; } WorkflowInstance workflow = ingestService.addZippedMediaPackage(in, workflowDefinitionId, workflowConfig, workflowInstanceIdAsLong); return Response.ok(WorkflowParser.toXml(workflow)).build(); } catch (MediaPackageException e) { logger.warn(e.getMessage()); return Response.serverError().status(Status.BAD_REQUEST).build(); } catch (Exception e) { logger.warn(e.getMessage(), e); return Response.serverError().status(Status.INTERNAL_SERVER_ERROR).build(); } finally { IOUtils.closeQuietly(in); if (isIngestLimitEnabled()) { setIngestLimit(getIngestLimit() + 1); logger.debug("An ingest has finished so increased ingest limit to " + getIngestLimit()); } } }
From source file:org.opencastproject.staticfiles.endpoint.StaticFileRestService.java
@POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN)//www .j a v a 2 s .com @Path("") @RestQuery(name = "postStaticFile", description = "Post a new static resource", bodyParameter = @RestParameter(description = "The static resource file", isRequired = true, name = "BODY", type = RestParameter.Type.FILE), reponses = { @RestResponse(description = "Returns the id of the uploaded static resource", responseCode = HttpServletResponse.SC_CREATED), @RestResponse(description = "No filename or file to upload found", responseCode = HttpServletResponse.SC_BAD_REQUEST), @RestResponse(description = "The upload size is too big", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "") public Response postStaticFile(@Context HttpServletRequest request) { if (maxUploadSize > 0 && request.getContentLength() > maxUploadSize) { logger.warn("Preventing upload of static file as its size {} is larger than the max size allowed {}", request.getContentLength(), maxUploadSize); return Response.status(Status.BAD_REQUEST).build(); } ProgressInputStream inputStream = null; try { String filename = null; if (ServletFileUpload.isMultipartContent(request)) { boolean isDone = false; for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { continue; } else { logger.debug("Processing file item"); filename = item.getName(); inputStream = new ProgressInputStream(item.openStream()); inputStream.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { long totalNumBytesRead = (Long) evt.getNewValue(); if (totalNumBytesRead > maxUploadSize) { logger.warn("Upload limit of {} bytes reached, returning a bad request.", maxUploadSize); throw new WebApplicationException(Status.BAD_REQUEST); } } }); isDone = true; } if (isDone) break; } } else { logger.warn("Request is not multi part request, returning a bad request."); return Response.status(Status.BAD_REQUEST).build(); } if (filename == null) { logger.warn("Request was missing the filename, returning a bad request."); return Response.status(Status.BAD_REQUEST).build(); } if (inputStream == null) { logger.warn("Request was missing the file, returning a bad request."); return Response.status(Status.BAD_REQUEST).build(); } String uuid = staticFileService.storeFile(filename, inputStream); try { return Response.created(getStaticFileURL(uuid)).entity(uuid).build(); } catch (NotFoundException e) { logger.error("Previous stored file with uuid {} couldn't beren found: {}", uuid, ExceptionUtils.getStackTrace(e)); return Response.serverError().build(); } } catch (WebApplicationException e) { return e.getResponse(); } catch (Exception e) { logger.error("Unable to store file because: {}", ExceptionUtils.getStackTrace(e)); return Response.serverError().build(); } finally { IOUtils.closeQuietly(inputStream); } }
From source file:org.opencastproject.workingfilerepository.impl.WorkingFileRepositoryRestEndpoint.java
@POST @Produces(MediaType.TEXT_HTML)//from w ww. ja v a 2 s . com @Path(WorkingFileRepository.MEDIAPACKAGE_PATH_PREFIX + "{mediaPackageID}/{mediaPackageElementID}") @RestQuery(name = "put", description = "Store a file in working repository under ./mediaPackageID/mediaPackageElementID", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "mediaPackageID", description = "the mediapackage identifier", isRequired = true, type = STRING), @RestParameter(name = "mediaPackageElementID", description = "the mediapackage element identifier", isRequired = true, type = STRING) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) }) public Response restPut(@PathParam("mediaPackageID") String mediaPackageID, @PathParam("mediaPackageElementID") String mediaPackageElementID, @Context HttpServletRequest request) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { continue; } URI url = this.put(mediaPackageID, mediaPackageElementID, item.getName(), item.openStream()); return Response.ok(url.toString()).build(); } } return Response.serverError().status(400).build(); }
From source file:org.opencastproject.workingfilerepository.impl.WorkingFileRepositoryRestEndpoint.java
@POST @Produces(MediaType.TEXT_HTML)//w w w . ja v a2 s . c o m @Path(WorkingFileRepository.COLLECTION_PATH_PREFIX + "{collectionId}") @RestQuery(name = "putInCollection", description = "Store a file in working repository under ./collectionId/filename", returnDescription = "The URL to access the stored file", pathParameters = { @RestParameter(name = "collectionId", description = "the colection identifier", isRequired = true, type = STRING) }, restParameters = { @RestParameter(name = "file", description = "the filename", isRequired = true, type = FILE) }, reponses = { @RestResponse(responseCode = SC_OK, description = "OK, file stored") }) public Response restPutInCollection(@PathParam("collectionId") String collectionId, @Context HttpServletRequest request) throws Exception { if (ServletFileUpload.isMultipartContent(request)) { for (FileItemIterator iter = new ServletFileUpload().getItemIterator(request); iter.hasNext();) { FileItemStream item = iter.next(); if (item.isFormField()) { continue; } URI url = this.putInCollection(collectionId, item.getName(), item.openStream()); return Response.ok(url.toString()).build(); } } return Response.serverError().status(400).build(); }
From source file:org.opendatakit.aggregate.parser.MultiPartFormData.java
/** * Construct a mult-part form data container by parsing a multi part form * request into a set of multipartformitems. The information are stored in * items and are indexed by either the field name or the file name (or both) * provided in the http submission// w w w. ja v a2 s. c om * * @param req * an HTTP request from a multipart form * * @throws FileUploadException * @throws IOException */ public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException { simpleFieldNameMap = new HashMap<String, String>(); fieldNameMap = new HashMap<String, MultiPartFormItem>(); fileNameMap = new HashMap<String, MultiPartFormItem>(); fileNameWithoutExtensionNameMap = new HashMap<String, MultiPartFormItem>(); ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory()); int size = req.getContentLength(); if (size > 0) { upload.setFileSizeMax(size); } else { upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX); } List<MultiPartFormItem> fileNameList = new ArrayList<MultiPartFormItem>(); FileItemIterator items = upload.getItemIterator(req); while (items.hasNext()) { FileItemStream item = items.next(); ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); BufferedInputStream formStream = new BufferedInputStream(item.openStream()); // TODO: determine ways to possibly improve efficiency int nextByte = formStream.read(); while (nextByte != -1) { byteStream.write(nextByte); nextByte = formStream.read(); } formStream.close(); if (item.isFormField()) { simpleFieldNameMap.put(item.getFieldName(), byteStream.toString()); } else { MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(), item.getContentType(), byteStream); String fieldName = item.getFieldName(); if (fieldName != null) { fieldNameMap.put(fieldName, data); } String fileName = item.getName(); if (fileName != null && fileName.length() != 0) { fileNameList.add(data); } } } // Find the common prefix to the filenames being uploaded... // Deal with Windows backslash file separator... boolean first = true; String[] commonPath = null; int commonPrefix = 0; for (MultiPartFormItem e : fileNameList) { String fullFilePath = e.getFilename(); if (first) { commonPath = fullFilePath.split("[/\\\\]"); commonPrefix = commonPath.length - 1; // everything but // filename... first = false; } else { String[] path = fullFilePath.split("[/\\\\]"); int pathPrefix = path.length - 1; // everything but // filename... if (pathPrefix < commonPrefix) commonPrefix = pathPrefix; for (int i = 0; i < commonPrefix; ++i) { if (!commonPath[i].equals(path[i])) { commonPrefix = i; break; } } } } // and now go back through the attachments, adjusting the filename // and building the filename mapping. for (MultiPartFormItem e : fileNameList) { String fullFilePath = e.getFilename(); String[] filePath = fullFilePath.split("[/\\\\]"); StringBuilder b = new StringBuilder(); first = true; // start at the first entry after the common prefix... for (int i = commonPrefix; i < filePath.length; ++i) { if (!first) { b.append("/"); } first = false; b.append(filePath[i]); } // and construct the filename with common directory prefix // stripped. String fileName = b.toString(); e.setFilename(fileName); if (fileName != null) { // TODO: possible bug in ODK collect truncating file extension // may need to remove this code after ODK collect is fixed int indexOfExtension = fileName.lastIndexOf("."); if (indexOfExtension > 0) { fileNameWithoutExtensionNameMap.put(fileName.substring(0, indexOfExtension), e); } fileNameMap.put(fileName, e); } } }
From source file:org.operamasks.faces.render.widget.AjaxFileUploadRenderer.java
@SuppressWarnings("unchecked") private void processUploading(FacesContext context, UIComponent component) throws IOException, FileUploadException { UploadingMediator uploadingMediator = getUploadingMediator(); if (!uploadingMediator.canStartUploading(context)) { return;/* ww w. ja v a 2 s . com*/ } else { uploadingMediator.startUploading(context); } UIForm parentForm = getParentForm(component); ServletFileUpload upload = new ServletFileUpload(); upload.setProgressListener(new FileUploadProgressListener(context)); HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest(); InputStream input = null; try { FileItemIterator iter = upload.getItemIterator(request); int itemIndex = 0; while (iter.hasNext()) { FileItemStream item = iter.next(); UIFileUpload fileUpload = findFileUploadByFieldName(parentForm, item.getFieldName()); if (!item.isFormField() && isFieldRequired(fileUpload) && isFieldNull(item)) { throw new FacesException(getRequiredFacesMessage(context, fileUpload)); } if (!item.isFormField()) { FileUploadItem uploadItem = createFileUploadItem(item, ++itemIndex, fileUpload.getMaxSize()); if (fileUpload == null) throw new FacesException("Can't find corresponding UIFileUpload component for this field " + uploadItem.getFieldName()); input = openStream(item, fileUpload); if (fileUpload.getWriteTo() != null) { writeToFile(input, fileUpload.getWriteTo()); } else { fileUpload.getUploadListener().invoke(context.getELContext(), new Object[] { uploadItem }); consumeStream(input); } } else { // Only need process file uploading, so consume other form fields input = openStream(item, fileUpload); consumeStream(input); } } } catch (FileUploadException e) { throw e; } catch (IOException e) { throw e; } finally { if (input != null) input.close(); } }
From source file:org.oryxeditor.server.StencilSetExtensionGeneratorServlet.java
/** * Request parameters are documented in//from w w w. j av a2 s. c o m * editor/test/examples/stencilset-extension-generator.xhtml * The parameter 'csvFile' is always required. * An example CSV file can be found in * editor/test/examples/design-thinking-example-data.csv * which has been exported using OpenOffice.org from * editor/test/examples/design-thinking-example-data.ods */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { this.request = request; this.response = response; this.baseUrl = Repository.getBaseUrl(request); this.repository = new Repository(baseUrl); // parameters and their default values String modelNamePrefix = "Generated Model using "; String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX; String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH; String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET; String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL; List<String> stencilSetExtensionUrls = new ArrayList<String>(); String[] columnPropertyMapping = null; String[] csvHeader = null; List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>(); String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator."; String additionalERDFContentForGeneratedModel = ""; String[] modelTags = null; // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request); if (isMultipart) { // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(); // Parse the request FileItemIterator iterator; try { iterator = upload.getItemIterator(request); while (iterator.hasNext()) { FileItemStream item = iterator.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { // ordinary form field String value = Streams.asString(stream); //System.out.println("Form field " + name + " with value " // + value + " detected."); if (name.equals("modelNamePrefix")) { modelNamePrefix = value; } else if (name.equals("stencilSetExtensionNamePrefix")) { stencilSetExtensionNamePrefix = value; } else if (name.equals("baseStencilSetPath")) { baseStencilSetPath = value; } else if (name.equals("baseStencilSet")) { baseStencilSet = value; } else if (name.equals("stencilSetExtension")) { stencilSetExtensionUrls.add(value); } else if (name.equals("baseStencil")) { baseStencil = value; } else if (name.equals("columnPropertyMapping")) { columnPropertyMapping = value.split(","); } else if (name.equals("modelDescription")) { modelDescription = value; } else if (name.equals("modelTags")) { modelTags = value.split(","); } else if (name.equals("additionalERDFContentForGeneratedModel")) { additionalERDFContentForGeneratedModel = value; } } else { // file field //System.out.println("File field " + name + " with file name " // + item.getName() + " detected."); // Process the input stream if (name.equals("csvFile")) { CsvMapReader csvFileReader = new CsvMapReader(new InputStreamReader(stream), CsvPreference.EXCEL_PREFERENCE); csvHeader = csvFileReader.getCSVHeader(true); if (columnPropertyMapping != null && columnPropertyMapping.length > 0) { csvHeader = columnPropertyMapping; } Map<String, String> row; while ((row = csvFileReader.read(csvHeader)) != null) { stencilPropertyMatrix.add(row); } } } } // generate stencil set Date creationDate = new Date(System.currentTimeMillis()); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS"); String stencilSetExtensionName = stencilSetExtensionNamePrefix + " " + dateFormat.format(creationDate); stencilSetExtensionUrls .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName, stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil)); // generate new model String modelName = modelNamePrefix + stencilSetExtensionName; String model = repository.generateERDF(UUID.randomUUID().toString(), additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet, stencilSetExtensionUrls, modelName, modelDescription); String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription, baseStencilSet, baseStencilSetPath); // hack for reverse proxies: modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://")); // tag model if (modelTags != null) { for (String tagName : modelTags) { repository.addTag(modelUrl, tagName.trim()); } } // redirect client to editor with that newly generated model response.setHeader("Location", modelUrl); response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { // TODO Add some error message } }