Package org.apache.commons.fileupload

Examples of org.apache.commons.fileupload.FileItemStream


            Lang lang = null ;
            int tripleCount = 0 ;
           
            FileItemIterator iter = upload.getItemIterator(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(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) ;
                            }
                            gn = Node.createURI(graphName) ;
                        }
                    }
                    else if ( fieldName.equals(HttpNames.paramDefaultGraphURI) )
                        graphName = null ;
                    else
                        // Add file type?
                        log.info(format("[%d] Upload: Field="+fieldName+" - ignored")) ;
                } 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.parse(contentTypeHeader) ;
                   
                    lang = FusekiLib.langFromContentType(ct.getContentType()) ;
                    if ( lang == null )
                        lang = Lang.guess(name) ;
View Full Code Here


        try {

            // Parse the request
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    System.out.println("Form field " + name + " with value "
                                       + Streams.asString(stream) + " detected.");
                } else {
                    System.out.println("File field " + name + " with file name "
                                       + item.getName() + " detected.");
                    // Process the input stream
                    response.setContentType("text/plain") ;

                    Sink<Triple> sink = new SinkTripleOutput(response.getOutputStream()) ;
                    LangRIOT parser = RiotReader.createParserTurtle(stream, null, sink) ;
View Full Code Here

            FileItemIterator i = servletFileUpload.getItemIterator(request);

            // Iterate the file items
            while (i.hasNext()) {
                try {
                    FileItemStream itemStream = i.next();

                    // If the file item stream is a form field, delegate to the
                    // field item stream handler
                    if (itemStream.isFormField()) {
                        processFileItemStreamAsFormField(itemStream);
                    }

                    // Delegate the file item stream for a file field to the
                    // file item stream handler, but delegation is skipped
                    // if the requestSizePermitted check failed based on the
                    // complete content-size of the request.
                    else {

                        // prevent processing file field item if request size not allowed.
                        // also warn user in the logs.
                        if (!requestSizePermitted) {
                            addFileSkippedError(itemStream.getName(), request);
                            LOG.warn("Skipped stream '#0', request maximum size (#1) exceeded.", itemStream.getName(), maxSize);
                            continue;
                        }

                        processFileItemStreamAsFileField(itemStream, saveDir);
                    }
View Full Code Here

                // Parse the request
                FileItemIterator iter = null;
                try {
                    iter = upload.getItemIterator(request);
                    while (iter.hasNext()) {
                        FileItemStream item = iter.next();
                        String name = item.getFieldName();
                        InputStream stream = null;
                        try {
                            stream = item.openStream();

                            if (item.isFormField()) {
                                LOGGER.debug("Form field " + name + " with value " + Streams.asString(stream) + " detected.");
                                incrementStringsProcessed();
                            } else {
                                LOGGER.debug("File field " + name + " with file name " + item.getName() + " detected.");
                                // Process the input stream
                                OutputStream os = null;
                                try {
                                    File tmpFile = File.createTempFile(UUID.randomUUID().toString() + "_MockUploadServlet", ".tmp");
                                    tmpFile.deleteOnExit();
View Full Code Here

                FileUpload upload = new FileUpload();
                FileItemIterator iter = upload.getItemIterator(requestContextWrapper);
                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();
                        if (log.isDebugEnabled()) {
                            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);

                        String value = FileUpload.FORM_DATA + ";" + " name=\"" + item.getFieldName() + "\";" + " filename=\""
                                + item.getName() + "\"";
                        NamedString mimeAttribute = WSRPTypeFactory.createNamedString(FileUpload.CONTENT_DISPOSITION, value);
                        mimeAttributes.add(mimeAttribute);

                        mimeAttribute = WSRPTypeFactory.createNamedString(FileUpload.CONTENT_TYPE, item.getContentType());
                        mimeAttributes.add(mimeAttribute);

                        uploadContext.getMimeAttributes().addAll(mimeAttributes);

                        uploadContexts.add(uploadContext);
                    } else {
                        NamedString formParameter = WSRPTypeFactory.createNamedString(item.getFieldName(),
                                Streams.asString(stream));
                        formParameters.add(formParameter);
                    }
                }
View Full Code Here

                Map<String, String[]> params = new HashMap<String, String[]>();
                InputStream fileStream = null;
                ServletFileUpload upload = new ServletFileUpload();
                FileItemIterator iter = upload.getItemIterator(request);
                while (iter.hasNext()) {
                    FileItemStream fileItemStream = iter.next();
                    if (fileItemStream.isFormField()) {
                        String fieldName = fileItemStream.getFieldName();
                        if ("content".equals(fieldName)) {
                            utf8 = true;
                            String[] parser = params.get("parser");
                            if (parser != null && parser[0].startsWith("xml")) {
                                contentType = "application/xml";
                            } else {
                                contentType = "text/html";
                            }
                            request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.type", "textarea");
                            fileStream = fileItemStream.openStream();
                            break;
                        } else {
                            putParam(
                                    params,
                                    fieldName,
                                    utf8ByteStreamToString(fileItemStream.openStream()));
                        }
                    } else {
                        String fileName = fileItemStream.getName();
                        if (fileName != null) {
                            putParam(params, fileItemStream.getFieldName(),
                                    fileName);
                            request.setAttribute(
                                    "nu.validator.servlet.MultipartFormDataFilter.filename",
                                    fileName);
                            Matcher m = EXTENSION.matcher(fileName);
                            if (m.matches()) {
                                contentType = EXTENSION_TO_TYPE.get(m.group(1));
                            }
                        }
                        if (contentType == null) {
                            contentType = fileItemStream.getContentType();
                        }
                        request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.type", "file");
                        fileStream = fileItemStream.openStream();
                        break;
                    }
                }
                if (fileStream == null) {
                    fileStream = new ByteArrayInputStream(new byte[0]);
View Full Code Here

            FileItemIterator fileItemIterator;
            String contentItemId = null;
            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
                        if(fis.getName() != null && !fis.getName().isEmpty()){
                            contentItemId = 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 = new InMemoryContentItem(id,
                        IOUtils.toByteArray(fis.openStream()),
                        fis.getContentType(), metadata);
                } else {
                    Blob blob = new InMemoryBlob(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

        ServletFileUpload upload = new ServletFileUpload();
        upload.setFileSizeMax(maxFileSize);
        try {
            FileItemIterator it = upload.getItemIterator(target);
            while (it.hasNext()) {
                FileItemStream item = it.next();
                if (item.isFormField()) {
                    InputStream input = null;
                    try {
                        input = item.openStream();
                        String fieldName = item.getFieldName();
                        String encode = request.getCharacterEncoding();
                        String fieldValue = encode==null ? Streams.asString(input) : Streams.asString(input, encode);
                        addFormItem(fieldName, fieldValue);
                    }
                    finally {
View Full Code Here

          try {
            totalFiles++;

            // Get the stream of field data from the request.
            FileItemStream fieldStream = (FileItemStream) fileItemIterator.next();

            // Get field name from the field stream.
            String fieldName = fieldStream.getFieldName();

            // If namespace optimization is enabled and the namespace is present in the field name,
            // then remove the portlet namespace from the field name.
            if (optimizeNamespace) {
              int pos = fieldName.indexOf(namespace);

              if (pos >= 0) {
                fieldName = fieldName.substring(pos + namespace.length());
              }
            }

            // Get the content-type, and file-name from the field stream.
            String contentType = fieldStream.getContentType();
            boolean formField = fieldStream.isFormField();

            String fileName = null;

            try {
              fileName = fieldStream.getName();
            }
            catch (InvalidFileNameException e) {
              fileName = e.getName();
            }

            // Copy the stream of file data to a temporary file. NOTE: This is necessary even if the
            // current field is a simple form-field because the call below to diskFileItem.getString()
            // will fail otherwise.
            DiskFileItem diskFileItem = (DiskFileItem) diskFileItemFactory.createItem(fieldName,
                contentType, formField, fileName);
            Streams.copy(fieldStream.openStream(), diskFileItem.getOutputStream(), true);

            // If the current field is a simple form-field, then save the form field value in the map.
            if (diskFileItem.isFormField()) {
              String characterEncoding = clientDataRequest.getCharacterEncoding();
              String requestParameterValue = null;

              if (characterEncoding == null) {
                requestParameterValue = diskFileItem.getString();
              }
              else {
                requestParameterValue = diskFileItem.getString(characterEncoding);
              }

              facesRequestParameterMap.addValue(fieldName, requestParameterValue);
            }
            else {

              File tempFile = diskFileItem.getStoreLocation();

              // If the copy was successful, then
              if (tempFile.exists()) {

                // Copy the commons-fileupload temporary file to a file in the same temporary
                // location, but with the filename provided by the user in the upload. This has two
                // benefits: 1) The temporary file will have a nice meaningful name. 2) By copying
                // the file, the developer can have access to a semi-permanent file, because the
                // commmons-fileupload DiskFileItem.finalize() method automatically deletes the
                // temporary one.
                String tempFileName = tempFile.getName();
                String tempFileAbsolutePath = tempFile.getAbsolutePath();

                String copiedFileName = stripIllegalCharacters(fileName);

                String copiedFileAbsolutePath = tempFileAbsolutePath.replace(tempFileName,
                    copiedFileName);
                File copiedFile = new File(copiedFileAbsolutePath);
                FileUtils.copyFile(tempFile, copiedFile);

                // If present, build up a map of headers.
                Map<String, List<String>> headersMap = new HashMap<String, List<String>>();
                FileItemHeaders fileItemHeaders = fieldStream.getHeaders();

                if (fileItemHeaders != null) {
                  Iterator<String> headerNameItr = fileItemHeaders.getHeaderNames();

                  if (headerNameItr != null) {
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.