Package org.apache.commons.fileupload

Examples of org.apache.commons.fileupload.FileItemStream


            FileItemIterator iter = upload.getItemIterator(requestContext);
            List<UploadContext> uploadContexts = new ArrayList<UploadContext>(7);
            List<NamedString> formParameters = new ArrayList<NamedString>(7);
            while (iter.hasNext())
            {
               FileItemStream item = iter.next();
               InputStream stream = item.openStream();
               if (!item.isFormField())
               {
                  String contentType = item.getContentType();
                  log.debug("File field " + item.getFieldName() + " with file name " + item.getName() + " and content type "
                     + contentType + " detected.");
                  BufferedInputStream bufIn = new BufferedInputStream(stream);

                  ByteArrayOutputStream baos = new ByteArrayOutputStream();
                  BufferedOutputStream bos = new BufferedOutputStream(baos);

                  int c = bufIn.read();
                  while (c != -1)
                  {
                     bos.write(c);
                     c = bufIn.read();
                  }

                  bos.flush();
                  baos.flush();
                  bufIn.close();
                  bos.close();

                  UploadContext uploadContext = WSRPTypeFactory.createUploadContext(contentType, baos.toByteArray());

                  List<NamedString> mimeAttributes = new ArrayList<NamedString>(2);

                  NamedString mimeAttribute = new NamedString();
                  mimeAttribute.setName(FileUpload.CONTENT_DISPOSITION);
                  mimeAttribute.setValue(FileUpload.FORM_DATA + ";"
                     + " name=\"" + item.getFieldName() + "\";"
                     + " filename=\"" + item.getName() + "\"");
                  mimeAttributes.add(mimeAttribute);

                  mimeAttribute = new NamedString();
                  mimeAttribute.setName(FileUpload.CONTENT_TYPE);
                  mimeAttribute.setValue(item.getContentType());
                  mimeAttributes.add(mimeAttribute);

                  uploadContext.getMimeAttributes().addAll(mimeAttributes);

                  uploadContexts.add(uploadContext);
               }
               else
               {
                  NamedString formParameter = new NamedString();
                  formParameter.setName(item.getFieldName());
                  formParameter.setValue(Streams.asString(stream));
                  formParameters.add(formParameter);
               }
            }
            interactionParams.getUploadContexts().addAll(uploadContexts);
View Full Code Here


            MGraph metadata = null;
            FileItemIterator fileItemIterator;
            try {
                fileItemIterator = fu.getItemIterator(new MessageBodyReaderContext(entityStream, mediaType));
                while(fileItemIterator.hasNext()){
                    FileItemStream fis = fileItemIterator.next();
                    if(fis.getFieldName().equals("metadata")){
                        if(contentItem != null){
                            throw new WebApplicationException(
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity("The Multipart MIME part with the 'metadata' " +
                                    "MUST BE before the MIME part containing the " +
                                    "'content'!").build());
                        }
                        //the metadata may define the ID for the contentItem
                        //only used if not parsed as query param
                        if(contentItemId == null && fis.getName() != null && !fis.getName().isEmpty()){
                            contentItemId = new UriRef(fis.getName());
                        }
                        metadata = new IndexedMGraph();
                        try {
                            getParser().parse(metadata, fis.openStream(), fis.getContentType());
                        } catch (Exception e) {
                            throw new WebApplicationException(e,
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity(String.format("Unable to parse Metadata " +
                                    "from Multipart MIME part '%s' (" +
                                    "contentItem: %s| contentType: %s)",
                                    fis.getFieldName(),fis.getName(),fis.getContentType()))
                                .build());
                        }
                    } else if(fis.getFieldName().equals("content")){
                        contentItem = createContentItem(contentItemId, metadata, fis, parsedContentIds);
                    } else if(fis.getFieldName().equals("properties") ||
                            fis.getFieldName().equals(ENHANCEMENT_PROPERTIES_URI.getUnicodeString())){
                        //parse the enhancementProperties
                        if(contentItem == null){
                            throw new WebApplicationException(
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity("Multipart MIME parts for " +
                                    "EnhancementProperties MUST BE after the " +
                                    "MIME parts for 'metadata' AND 'content'")
                                .build());
                        }
                        MediaType propMediaType = MediaType.valueOf(fis.getContentType());
                        if(!APPLICATION_JSON_TYPE.isCompatible(propMediaType)){
                            throw new WebApplicationException(
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity("EnhancementProperties (Multipart MIME parts" +
                                    "with the name '"+fis.getFieldName()+"') MUST " +
                                    "BE encoded as 'appicaltion/json' (encountered: '" +
                                    fis.getContentType()+"')!")
                                .build());
                        }
                        String propCharset = propMediaType.getParameters().get("charset");
                        if(propCharset == null){
                            propCharset = "UTF-8";
                        }
                        Map<String,Object> enhancementProperties = getEnhancementProperties(contentItem);
                        try {
                            enhancementProperties.putAll(toMap(new JSONObject(
                                IOUtils.toString(fis.openStream(),propCharset))));
                        } catch (JSONException e) {
                            throw new WebApplicationException(e,
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity("Unable to parse EnhancementProperties from" +
                                    "Multipart MIME parts with the name 'properties'!")
                                .build());
                        }
                       
                    } else { //additional metadata as serialised RDF
                        if(contentItem == null){
                            throw new WebApplicationException(
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity("Multipart MIME parts for additional " +
                                    "contentParts MUST BE after the MIME " +
                                    "parts for 'metadata' AND 'content'")
                                .build());
                        }
                        if(fis.getFieldName() == null || fis.getFieldName().isEmpty()){
                            throw new WebApplicationException(
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity("Multipart MIME parts representing " +
                                    "ContentParts for additional RDF metadata" +
                                    "MUST define the contentParts URI as" +
                                    "'name' of the MIME part!").build());
                        }
                        MGraph graph = new IndexedMGraph();
                        try {
                            getParser().parse(graph, fis.openStream(), fis.getContentType());
                        } catch (Exception e) {
                            throw new WebApplicationException(e,
                                Response.status(Response.Status.BAD_REQUEST)
                                .entity(String.format("Unable to parse RDF " +
                                        "for ContentPart '%s' ( contentType: %s)",
                                        fis.getName(),fis.getContentType()))
                                .build());
                        }
                        UriRef contentPartId = new UriRef(fis.getFieldName());
                        contentItem.addPart(contentPartId, graph);
                    }
                }
                if(contentItem == null){
                    throw new WebApplicationException(
View Full Code Here

            //multiple contentParts are parsed
            FileItemIterator contentPartIterator = fu.getItemIterator(
                new MessageBodyReaderContext(
                    content.openStream(), partContentType));
            while(contentPartIterator.hasNext()){
                FileItemStream fis = contentPartIterator.next();
                if(contentItem == null){
                    log.debug("create ContentItem {} for content (type:{})",
                        id,content.getContentType());
                    contentItem = ciFactory.createContentItem(id,
                        new StreamSource(fis.openStream(),fis.getContentType()),
                        metadata);
                } else {
                    Blob blob = ciFactory.createBlob(new StreamSource(fis.openStream(), fis.getContentType()));
                    UriRef contentPartId = null;
                    if(fis.getFieldName() != null && !fis.getFieldName().isEmpty()){
                        contentPartId = new UriRef(fis.getFieldName());
                    } else {
                        //generating a random ID might break metadata
                        //TODO maybe we should throw an exception instead
                        contentPartId = new UriRef("urn:contentpart:"+ randomUUID());
                    }
                    log.debug("  ... add Blob {} to ContentItem {} with content (type:{})",
                        new Object[]{contentPartId, id, fis.getContentType()});
                    contentItem.addPart(contentPartId, blob);
                    parsedContentParts.add(contentPartId.getUnicodeString());
                }
            }
        } else {
View Full Code Here

      upload.setFileSizeMax(maxFileSize);
      try {
        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
          FileItemStream item = iter.next();
          String name = item.getFieldName();
          InputStream stream = item.openStream();
          if (item.isFormField()) {
            String value = Streams.asString(stream);
            tr.put(item.getFieldName(), value);
            logger.log(Level.DEBUG, "Form field " + name
                + " with value " + value + " detected.");
          } else {
            logger.log(Level.DEBUG, "File field " + name
                + " with file name " + item.getName()
                + " detected.");

            FileHolder FH = new FileHolder();
            FH.setContentType(item.getContentType());

            // ie sends entire path, other only filename
            FH.setCompletePath(item.getName());
            // no point to read file if it does not exist..
            if (null != item.getName()
                && item.getName().length() > 0) {
              // filename
              FH.setFileName(item.getName().substring(
                  item.getName().lastIndexOf("\\") + 1));
            }

            InputStream inStream = item.openStream();

            int lBufferSize = 1024;
            byte[] lByteBuffer = new byte[lBufferSize];

            int lBytesRead = 0;
            int lTotbytesRead = 0;
            int lCount = 0;

            ByteArrayOutputStream lByteArrayOutputStream = new ByteArrayOutputStream(
                lBufferSize * 2);

            while ((lBytesRead = inStream.read(lByteBuffer)) != -1) {
              lTotbytesRead += lBytesRead;
              lCount++;

              lByteArrayOutputStream.write(lByteBuffer, 0,
                  lBytesRead);
            }
            logger.log(Level.DEBUG, "Chuncks count: " + lCount);
            logger.log(Level.DEBUG, "Total bytes read: "
                + lTotbytesRead);

            FH.setFileContent(lByteArrayOutputStream.toByteArray());

            tr.put(item.getFieldName(), FH);
          }
        }
      } catch (Exception e) {
        logger.log(Level.ERROR, " Error parsing multipartform " + e);
      }
View Full Code Here

            // multipart request
            try {
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iter = upload.getItemIterator(request);
                while (iter.hasNext()) {
                    FileItemStream item = iter.next();
                    String name = item.getFieldName();
                    InputStream stream = item.openStream();
                    if (item.isFormField()) {
                        requestParams.put(name, Streams.asString(stream));
                    } else {
                        String fileName = item.getName();
                        if (fileName != null && !"".equals(fileName.trim())) {
                            listFiles.add(item);

                            ByteArrayOutputStream os = new ByteArrayOutputStream();
                            IOUtils.copy(stream, os);
View Full Code Here

      // 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")) {
View Full Code Here

        Lang lang = null ;

        try {
            FileItemIterator iter = upload.getItemIterator(action.request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String fieldName = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField())
                {
                    // Graph name.
                    String value = Streams.asString(stream, "UTF-8") ;
                    if ( fieldName.equals(HttpNames.paramGraph) )
                    {
                        graphName = value ;
                        if ( graphName != null && ! graphName.equals("") && ! graphName.equals(HttpNames.valueDefault) )
                        {
                            IRI iri = IRIResolver.parseIRI(value) ;
                            if ( iri.hasViolation(false) )
                                errorBadRequest("Bad IRI: "+graphName) ;
                            if ( iri.getScheme() == null )
                                errorBadRequest("Bad IRI: no IRI scheme name: "+graphName) ;
                            if ( iri.getScheme().equalsIgnoreCase("http") || iri.getScheme().equalsIgnoreCase("https"))
                            {
                                // Redundant??
                                if ( iri.getRawHost() == null )
                                    errorBadRequest("Bad IRI: no host name: "+graphName) ;
                                if ( iri.getRawPath() == null || iri.getRawPath().length() == 0 )
                                    errorBadRequest("Bad IRI: no path: "+graphName) ;
                                if ( iri.getRawPath().charAt(0) != '/' )
                                    errorBadRequest("Bad IRI: Path does not start '/': "+graphName) ;
                            }
                        }
                    }
                    else if ( fieldName.equals(HttpNames.paramDefaultGraphURI) )
                        graphName = null ;
                    else
                        // Add file type?
                        log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName)) ;
                } else {
                    // Process the input stream
                    name = item.getName() ;
                    if ( name == null || name.equals("") || name.equals("UNSET FILE NAME") )
                        errorBadRequest("No name for content - can't determine RDF syntax") ;

                    String contentTypeHeader = item.getContentType() ;
                    ct = ContentType.create(contentTypeHeader) ;

                    lang = RDFLanguages.contentTypeToLang(ct.getContentType()) ;

                    if ( lang == null ) {
View Full Code Here

          ServletFileUpload upload = new ServletFileUpload();
      FileItemIterator iterator = upload.getItemIterator(request);
            byte[] image = null;
            String contentType = null;
      while (iterator.hasNext()) {
              FileItemStream fileItem = iterator.next();
              InputStream stream = fileItem.openStream();

                if (fileItem.isFormField()) {
                  switch (fileItem.getFieldName()) {
            case "thought":
              userThought = Streams.asString(stream);
              break;
            case "name":
              name = Streams.asString(stream);
              break;
            default: break;
          }
                } else {
                    if ("image".equals(fileItem.getFieldName())) {
                      contentType = fileItem.getContentType();
                      ByteArrayOutputStream out = new ByteArrayOutputStream();
                        IOUtils.copy(stream, out);
                        IOUtils.closeQuietly(stream);
                        IOUtils.closeQuietly(out);
                        image = out.toByteArray();
View Full Code Here

          ServletFileUpload upload = new ServletFileUpload();
      FileItemIterator iterator = upload.getItemIterator(request);
            byte[] image = null;
            String contentType = null;
      while (iterator.hasNext()) {
              FileItemStream fileItem = iterator.next();
              InputStream stream = fileItem.openStream();

                if (fileItem.isFormField()) {
                  switch (fileItem.getFieldName()) {
            case "thought":
              userThought = Streams.asString(stream);
              break;
            case "name":
              name = Streams.asString(stream);
              break;
            case "id":
              id = NumberUtils.toLong(Streams.asString(stream), 0L);
              break;
            default: break;
          }
                } else {
                    if ("image".equals(fileItem.getFieldName())) {
                      contentType = fileItem.getContentType();
                      ByteArrayOutputStream out = new ByteArrayOutputStream();
                        IOUtils.copy(stream, out);
                        IOUtils.closeQuietly(stream);
                        IOUtils.closeQuietly(out);
                        image = out.toByteArray();
View Full Code Here

     * @return parameters and files
     */
    private MultipartParameters parseFileItems(FileItemIterator iterator) throws FileUploadException, IOException {
        MultipartParameters multipartParameters = new MultipartParameters();
        while (iterator.hasNext()) {
            FileItemStream fileItemStream = iterator.next();
            String fieldName = fileItemStream.getFieldName();
            if (fileItemStream.getContentType() == null) {
                // The FileItemStream represents a simple String parameter when there is no content type
                String fieldValue = FileCopyUtils.copyToString(new InputStreamReader(fileItemStream.openStream()));
                multipartParameters.addStringParameter(fieldName, fieldValue);
            } else {
                // The FileItemStream represents an actual file
                MultipartFile multipartFile = new CommonsStreamMultipartFile(fileItemStream);
                multipartParameters.addMultipartFileParameter(fieldName, multipartFile);
View Full Code Here

TOP

Related Classes of org.apache.commons.fileupload.FileItemStream

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.