Example usage for org.apache.commons.fileupload FileItemIterator hasNext

List of usage examples for org.apache.commons.fileupload FileItemIterator hasNext

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemIterator hasNext.

Prototype

boolean hasNext() throws FileUploadException, IOException;

Source Link

Document

Returns, whether another instance of FileItemStream is available.

Usage

From source file:org.kie.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in/*from   w  w  w  .j  a v  a  2s  .  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, "UTF-8"),
                                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
    }
}

From source file:org.kimios.controller.UploadManager.java

private String startUploadFile(HttpServletRequest req) throws Exception {
    DiskFileItemFactory fp = new DiskFileItemFactory();
    fp.setRepository(new File(ConfigurationManager.getValue(Config.DM_TMP_FILES_PATH)));
    ServletFileUpload sfu = new ServletFileUpload(fp);
    QProgressListener pp = new QProgressListener(uploads);
    sfu.setProgressListener(pp);//from ww w . j  a v a 2 s.c  om
    String uploadId = "";
    String name = "";
    String sec = "";
    String metaValues = "";
    String docTypeUid = "";
    String action = "";
    String documentUid = ""; //used for import
    String newVersion = "";
    boolean isSecurityInherited = false;
    long folderUid = 0;
    String mimeType = "";
    String extension = "";
    FileItemIterator t = sfu.getItemIterator(req);
    while (t.hasNext()) {

        FileItemStream st = t.next();
        if (st.isFormField()) {
            String tmpVal = Streams.asString(st.openStream(), "UTF-8");
            log.debug(st.getFieldName() + " --> " + tmpVal);
            if (st.getFieldName().equalsIgnoreCase("actionUpload")) {
                action = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("newVersion")) {
                newVersion = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("documentUid")) {
                documentUid = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("UPLOAD_ID")) {
                uploadId = tmpVal;
                pp.setUploadId(uploadId);
            }
            if (st.getFieldName().equalsIgnoreCase("name")) {
                name = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("sec")) {
                sec = StringEscapeUtils.unescapeHtml(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("documentTypeUid")) {
                docTypeUid = tmpVal;
            }
            if (st.getFieldName().equalsIgnoreCase("metaValues")) {
                metaValues = StringEscapeUtils.unescapeHtml(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("folderUid")) {
                folderUid = Long.parseLong(tmpVal);
            }
            if (st.getFieldName().equalsIgnoreCase("inheritedPermissions")) {
                isSecurityInherited = (tmpVal != null && tmpVal.equalsIgnoreCase("on"));
            }
        } else {
            InputStream in = st.openStream();
            mimeType = st.getContentType();
            extension = st.getName().substring(st.getName().lastIndexOf('.') + 1);
            int transferChunkSize = Integer.parseInt(ConfigurationManager.getValue(Config.DM_CHUNK_SIZE));

            if (action.equalsIgnoreCase("AddDocument")) {
                Document d = new Document();
                d.setCreationDate(Calendar.getInstance());
                d.setExtension(extension);
                d.setFolderUid(folderUid);
                d.setCheckedOut(false);
                d.setMimeType(mimeType);
                d.setName(name);
                d.setOwner("");
                d.setUid(-1);
                long docUid = documentController.createDocument(sessionUid, d, isSecurityInherited);
                if (!isSecurityInherited) {
                    securityController.updateDMEntitySecurities(sessionUid, docUid, 3, false,
                            DMEntitySecuritiesParser.parseFromJson(sec, docUid, 3));
                }

                fileTransferController.uploadFileFirstVersion(sessionUid, docUid, in, false);
                long documentTypeUid = -1;
                try {
                    documentTypeUid = Long.parseLong(docTypeUid);
                } catch (Exception e) {
                }
                if (documentTypeUid > 0) {
                    Map<Meta, String> mMetasValues = DMEntitySecuritiesParser
                            .parseMetasValuesFromJson(sessionUid, metaValues, documentVersionController);
                    String xmlMeta = XMLGenerators.getMetaDatasDocumentXMLDescriptor(mMetasValues,
                            "MM/dd/yyyy");
                    documentVersionController.updateDocumentVersion(sessionUid, docUid, documentTypeUid,
                            xmlMeta);
                }
            } else {

                if (action.equalsIgnoreCase("Import")) {
                    documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid));
                    fileTransferController.uploadFileNewVersion(sessionUid, Long.parseLong(documentUid), in,
                            false);
                    documentController.checkinDocument(sessionUid, Long.parseLong(documentUid));
                } else if (action.equalsIgnoreCase("UpdateCurrent")) {
                    documentController.checkoutDocument(sessionUid, Long.parseLong(documentUid));
                    fileTransferController.uploadFileUpdateVersion(sessionUid, Long.parseLong(documentUid), in,
                            false);
                    documentController.checkinDocument(sessionUid, Long.parseLong(documentUid));
                }
            }

        }
    }
    return "{success: true}";
}

From source file:org.kuali.kfs.sys.web.servlet.BatchFileUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    checkAuthorization(request);// w  ww  .  j  a va  2  s . c om
    ServletFileUpload upload = new ServletFileUpload();

    String destPath = null;
    String fileName = null;
    String tempDir = System.getProperty("java.io.tmpdir");
    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            fileName = item.getName();
            LOG.info("Processing Item: " + item.getFieldName());
            if (item.isFormField()) {
                if (item.getFieldName().equals("uploadDir")) {
                    Reader str = new InputStreamReader(item.openStream());
                    StringWriter sw = new StringWriter();
                    char buf[] = new char[100];
                    int len;
                    while ((len = str.read(buf)) > 0) {
                        sw.write(buf, 0, len);
                    }
                    destPath = sw.toString();
                }
            } else {
                InputStream stream = item.openStream();
                fileName = item.getName();
                LOG.info("Uploading to Directory: " + tempDir);
                // Process the input stream
                FileOutputStream fos = new FileOutputStream(new File(tempDir, fileName));
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024 * 1024);
                byte buf[] = new byte[10240];
                int len;
                while ((len = stream.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                }
                bos.close();
                stream.close();
            }
        }
        LOG.info("Copying to Directory: " + destPath);

        if (!getBatchDirectories().contains(destPath)) {
            new File(tempDir, fileName).delete();
            throw new RuntimeException("Illegal Attempt to upload to an unauthorized path: '" + destPath + "'");
        }

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File(tempDir, fileName)));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(destPath, fileName)),
                1024 * 1024);
        byte buf[] = new byte[10240];
        int len;
        while ((len = bis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        bos.close();
        bis.close();
    } catch (FileUploadException ex) {
        LOG.error("Problem Uploading file", ex);
    }
    if (fileName != null) {
        request.setAttribute("message", "Successfully uploaded " + fileName + " to " + destPath);
    } else {
        request.setAttribute("message", "Upload Failed");
    }
    doGet(request, response);
}

From source file:org.kuali.student.core.document.ui.server.upload.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    UploadStatus status = new UploadStatus();
    request.getSession().setAttribute(request.getParameter("uploadId"), status);
    try {//  w  w  w  .ja  v a2  s.  c o  m

        ServletFileUpload upload = new ServletFileUpload();
        upload.setProgressListener(
                new DocumentProgressListener(request.getParameter("uploadId"), request.getSession()));
        FileItemIterator iter = upload.getItemIterator(request);
        DocumentInfo info = new DocumentInfo();

        boolean fileError = false;
        int currentItem = 0;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                String value = Streams.asString(stream);
                if (name.equals("documentDescription")) {
                    RichTextInfo text = new RichTextInfo();
                    text.setPlain(value);
                    info.setDescr(text);
                }
            } else {
                String fullFileName = item.getName();
                if (fullFileName != null) {
                    String filename = FilenameUtils.getName(fullFileName);
                    FileStatus fileStatus = new FileStatus();
                    fileStatus.setFileName(filename);
                    status.getFileStatusList().add(currentItem, fileStatus);
                    DocumentBinaryInfo bInfo = new DocumentBinaryInfo();
                    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                    byte[] buffer = new byte[4096];
                    while (true) {
                        int read = stream.read(buffer);
                        if (read == -1) {
                            break;
                        } else {
                            bytes.write(buffer, 0, read);
                            fileStatus.setProgress(fileStatus.getProgress() + read);
                        }
                    }
                    bytes.flush();
                    fileStatus.setStatus(FileTransferStatus.UPLOAD_FINISHED);
                    bInfo.setBinary(new String(Base64.encodeBase64(bytes.toByteArray())));

                    info.setDocumentBinary(bInfo);
                    info.setStateKey(DtoState.ACTIVE.toString());
                    info.setFileName(filename);

                    int extSeperator = filename.lastIndexOf(".");
                    info.setName(filename.substring(0, extSeperator));

                    //FIXME Probably temporary solution for type on document info
                    String type = "documentType." + filename.substring(extSeperator + 1).toLowerCase();
                    info.setTypeKey(type);
                } else {
                    //No file specified error
                    status.setStatus(UploadTransferStatus.ERROR);
                }
            }

            if (info.getDescr() != null && info.getDocumentBinary() != null && info.getType() != null) {
                //FileStatus fileStatus = status.getFileStatusMap().get(info.getFileName());
                FileStatus fileStatus = status.getFileStatusList().get(currentItem);
                try {
                    DocumentInfo createdDoc = documentService.createDocument(info.getTypeKey(),
                            "documentCategory.proposal", info, ContextUtils.getContextInfo());
                    fileStatus.setStatus(FileTransferStatus.COMMIT_FINISHED);
                    if (createdDoc != null) {
                        status.getCreatedDocIds().add(createdDoc.getId());
                        fileStatus.setDocId(createdDoc.getId());
                    }

                    RefDocRelationInfo relationInfo = new RefDocRelationInfo();
                    relationInfo.setStateKey(DtoState.ACTIVE.toString());
                    relationInfo.setDescr(info.getDescr());
                    relationInfo.setRefObjectId(request.getParameter("referenceId"));
                    relationInfo.setRefObjectTypeKey(request.getParameter("refObjectTypeKey"));
                    relationInfo.setTitle(info.getFileName());
                    relationInfo.setDocumentId(createdDoc.getId());
                    relationInfo.setType(request.getParameter("refDocRelationTypeKey"));
                    documentService.createRefDocRelation(relationInfo.getRefObjectTypeKey(),
                            relationInfo.getRefObjectId(), relationInfo.getDocumentId(),
                            relationInfo.getTypeKey(), relationInfo, ContextUtils.getContextInfo());
                } catch (Exception e) {
                    fileError = true;
                    LOG.error("Exception occurred", e);
                    fileStatus.setStatus(FileTransferStatus.ERROR);
                }
                info = new DocumentInfo();
                currentItem++;
            }
        }

        if (fileError) {
            status.setStatus(UploadTransferStatus.ERROR);
        } else {
            status.setStatus(UploadTransferStatus.COMMIT_FINISHED);
        }

    } catch (Exception e) {
        status.setStatus(UploadTransferStatus.ERROR);
        LOG.error("Exception occurred", e);
    }

}

From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java

private void uploadMultipart(HttpServletRequest req, HttpServletResponse resp, OutputStream repoItemOutputStrem)
        throws IOException {

    log.debug("Multipart detected");

    ServletFileUpload upload = new ServletFileUpload();

    try {/*from ww w .  j ava 2  s. c  om*/

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            try (InputStream stream = item.openStream()) {
                if (item.isFormField()) {
                    // TODO What to do with this?
                    log.debug("Form field {} with value {} detected.", name, Streams.asString(stream));
                } else {

                    // TODO Must we support multiple files uploading?
                    log.debug("File field {} with file name detected.", name, item.getName());

                    log.debug("Start to receive bytes (estimated bytes)",
                            Integer.toString(req.getContentLength()));
                    int bytes = IOUtils.copy(stream, repoItemOutputStrem);
                    resp.setStatus(SC_OK);
                    log.debug("Bytes received: {}", Integer.toString(bytes));
                }
            }
        }

    } catch (FileUploadException e) {
        throw new IOException(e);
    }
}

From source file:org.locationtech.geogig.rest.repository.UploadCommandResource.java

/**
 * Consumes the data sent from the client and stores it into a temporary file to be processed.
 * This method is just looking through the request entity for form data named
 * {@value #UPLOAD_FILE_KEY}. If present, we will consume the data stream from the request and
 * store it in a temporary file.//from   www .  jav  a2s  .c o  m
 *
 * @param entity POSTed entity containing binary data to be processed.
 *
 * @return local File representation of the data streamed form the client.
 */
private File consumeFileUpload(Representation entity) {
    File uploadedFile = null;
    // get a File item factory
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    // set the threshold
    factory.setSizeThreshold(UPLOAD_THRESHOLD);
    // build a Restlet file upload with the factory
    final RestletFileUpload fileUploadUtil = new RestletFileUpload(factory);
    // try to extract the uploaded file entity
    try {
        // build a RepresentaionContext of the request entity
        final RepresentationContext context = new RepresentationContext(entity);
        // get an iterator to loop through the entity for the upload data
        final FileItemIterator iterator = fileUploadUtil.getItemIterator(context);
        // look for the the "fileUpload" form data
        while (iterator.hasNext()) {
            final FileItemStream fis = iterator.next();
            // see if this is the data we are looking for
            if (UPLOAD_FILE_KEY.equals(fis.getFieldName())) {
                // if we've already ingested a fileUpload, then the request had more than one.
                Preconditions.checkState(uploadedFile == null, FILE_UPLOAD_ERROR_TMPL, UPLOAD_FILE_KEY);
                // found it, create a temp file
                uploadedFile = File.createTempFile("geogig-" + UPLOAD_FILE_KEY + "-", ".tmp");
                uploadedFile.deleteOnExit();
                // consume the streamed contetn into the temp file
                try (FileOutputStream fos = new FileOutputStream(uploadedFile)) {
                    ByteUtils.write(fis.openStream(), fos);
                    // flush the output stream
                    fos.flush();
                }
            }
        }
        // if we don't have an uploaded file, we can't continue
        Preconditions.checkNotNull(uploadedFile, FILE_UPLOAD_ERROR_TMPL, UPLOAD_FILE_KEY);
    } catch (Exception ex) {
        // delete the temp file if it exists
        if (uploadedFile != null) {
            uploadedFile.delete();
        }
        // null out the file
        uploadedFile = null;
    }
    // return the uploaded entity data as a file
    return uploadedFile;
}

From source file:org.myjerry.web.multipart.StreamingMultipartResolver.java

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();
    upload.setFileSizeMax(maxUploadSize);

    String encoding = determineEncoding(request);

    Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
    Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

    // MultiValueMap multipartFiles = new MultiValueMap();

    // Parse the request
    try {/*from  w  w  w.  j  a  va  2 s. c  o  m*/
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {

                String value = Streams.asString(stream, encoding);

                String[] curParam = (String[]) multipartParameters.get(name);
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(name, new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = StringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(name, newParam);
                }

            } else {

                // Process the input stream
                MultipartFile file = new StreamingMultipartFile(item);
                multipartFiles.put(name, file);
            }
        }
    } catch (IOException e) {
        throw new MultipartException("something went wrong here", e);
    } catch (FileUploadException e) {
        throw new MultipartException("something went wrong here", e);
    }

    return new DefaultMultipartHttpServletRequest(request, multipartFiles, multipartParameters);
}

From source file:org.nema.medical.mint.server.controller.JobsController.java

public void handleUpload(HttpServletRequest request, File jobFolder, List<File> files,
        Map<String, String> params) throws IOException, FileUploadException {

    byte buf[] = new byte[32 * 1024];

    int fileCount = 0;
    LOG.info("creating local files");

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

        if (item.isFormField()) {
            String value = Streams.asString(in);
            LOG.debug("found form field " + name + " = " + value);
            params.put(name, value);/*from w  ww .java 2s  .  co  m*/
        } else {
            File file;

            // special handling for first file - must be metadata!
            if (files.isEmpty()) {
                String filename = item.getName();

                LOG.info("loading metadata from " + filename);
                outer: {
                    for (String extension : supportedMetadataExtensions) {
                        if (filename.endsWith(extension)) {
                            filename = "metadata" + extension;
                            break outer;
                        }
                    }

                    //At this point, no proper filename has been established. Last resort, use content type!
                    String contentType = item.getContentType();
                    if ("text/xml".equals(contentType)) {
                        filename = "metadata.xml";
                    } else if ("application/octet-stream".equals(contentType)) {
                        filename = "metadata.gpb";
                    } else {
                        // dump out and write the content... will fail later
                        LOG.error("unable to determine metadata type for " + item.getName());
                        filename = "metadata.dat";
                    }
                }

                file = new File(jobFolder, filename);
            } else {
                final String msgPartName = item.getFieldName();
                try {
                    if (!msgPartName.startsWith("binary")) {
                        throw new Exception();
                    }
                    final String itemIdStr = msgPartName.substring("binary".length());
                    final int itemId = Integer.parseInt(itemIdStr);
                    file = new File(jobFolder, String.format("%d.dat", itemId));
                } catch (final Exception e) {
                    throw new IOException("Invalid message part name for binary data: '" + msgPartName
                            + "'; must start with 'binary', followed by a number");
                }
            }

            if (file.exists()) {
                throw new IOException("File for message part already exists: '" + file.getName() + "'");
            }
            FileOutputStream out = null;
            out = new FileOutputStream(file);
            try {
                while (true) {
                    int len = in.read(buf);
                    if (len < 0)
                        break;
                    out.write(buf, 0, len);
                }
            } finally {
                if (out != null) {
                    out.close();
                    files.add(file);
                    fileCount++;
                }
            }
        }
    }
    LOG.info("created " + fileCount + " files.");
}

From source file:org.odk.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
 * /*from w w  w.java  2 s . com*/
 * @param req
 *     an HTTP request from a multipart form 
        
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setFileSizeMax(ParserConsts.FILE_SIZE_MAX);

    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();
        }

        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) {
            // TODO: possible bug in ODK collect is truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameMap.put(fileName.substring(0, indexOfExtension), data);
            }
            fileNameMap.put(fileName, data);
        }
        formStream.close();
    }
}

From source file:org.odk.voice.storage.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
 * //from  w  ww .  jav  a 2 s .  c o  m
 * @param req
 *     an HTTP request from a multipart form 
        
 * @throws FileUploadException
 * @throws IOException
 */
public MultiPartFormData(HttpServletRequest req) throws FileUploadException, IOException {

    fieldNameMap = new HashMap<String, MultiPartFormItem>();
    fileNameMap = new HashMap<String, MultiPartFormItem>();

    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setFileSizeMax(FileConstants.MAX_FILE_SIZE);

    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();
        }

        MultiPartFormItem data = new MultiPartFormItem(item.getFieldName(), item.getName(),
                item.getContentType(), byteStream.toByteArray());

        String fieldName = item.getFieldName();
        if (fieldName != null) {
            fieldNameMap.put(fieldName, data);
        }

        String fileName = item.getName();
        if (fileName != null) {
            // TODO: possible bug in ODK collect is truncating file extension
            // may need to remove this code after ODK collect is fixed
            int indexOfExtension = fileName.lastIndexOf(".");
            if (indexOfExtension > 0) {
                fileNameMap.put(fileName.substring(0, indexOfExtension), data);
            }
            fileNameMap.put(fileName, data);
        }
    }
}