Example usage for org.apache.commons.fileupload FileItem getFieldName

List of usage examples for org.apache.commons.fileupload FileItem getFieldName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItem getFieldName.

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

From source file:at.ac.dbisinformatik.snowprofile.web.ListSnowProfileResource.java

/**
 * store new Snowprofile in Database/*from   w  w w. j a  v  a2s  .  c om*/
 * 
 * @param entity
 * @return
 * @throws Exception
 */
@Post
public String storeJson(Representation entity) throws Exception {
    String rep = "";
    if (entity != null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1000240);

            RestletFileUpload upload = new RestletFileUpload(factory);
            List<FileItem> items;

            items = upload.parseRequest(getRequest());

            boolean found = false;
            for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) {
                FileItem fi = it.next();
                String snowprofile = "";
                if (fi.getFieldName().equals("import")) {
                    snowprofile = IOUtils.toString(fi.getInputStream());
                    JSONObject snowprofileJSON = XML.toJSONObject(snowprofile);

                    snowprofile = snowprofileJSON.toString().replace("caaml:", "");
                    snowprofile = snowprofile.replace("gml:", "gml_");
                    snowprofile = snowprofile.replace("xmlns:", "xmlns_");
                    snowprofile = snowprofile.replace("xsi:", "xsi_");

                    snowprofileJSON = new JSONObject(snowprofile);

                    snowprofile = db.store("SnowProfile",
                            new JSONObject(snowprofileJSON.get("SnowProfile").toString()));
                    rep = "{\"success\": \"true\", \"id\": \"" + snowprofile + "\"}";
                } else {
                    rep = new StringRepresentation("no file uploaded", MediaType.TEXT_PLAIN).toString();
                }
            }
        } else {
            rep = db.store("SnowProfile", new JSONObject(entity.getText()));
        }
    }

    return rep;
}

From source file:fr.gael.dhus.api.UploadController.java

@SuppressWarnings("unchecked")
@PreAuthorize("hasRole('ROLE_UPLOAD')")
@RequestMapping(value = "/upload", method = { RequestMethod.POST })
public void upload(Principal principal, HttpServletRequest req, HttpServletResponse res) throws IOException {
    // process only multipart requests
    if (ServletFileUpload.isMultipartContent(req)) {
        User user = (User) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();
        // Create a factory for disk-based file items
        FileItemFactory factory = new DiskFileItemFactory();
        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        try {/*w  w w .j  a va  2s. c  om*/
            ArrayList<Long> collectionIds = new ArrayList<>();
            FileItem product = null;

            List<FileItem> items = upload.parseRequest(req);
            for (FileItem item : items) {
                if (COLLECTIONSKEY.equals(item.getFieldName())) {
                    if (item.getString() != null && !item.getString().isEmpty()) {
                        for (String cid : item.getString().split(",")) {
                            collectionIds.add(new Long(cid));
                        }
                    }
                } else if (PRODUCTKEY.equals(item.getFieldName())) {
                    product = item;
                }
            }
            if (product == null) {
                res.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Your request is missing a product file to upload.");
                return;
            }
            productUploadService.upload(user.getId(), product, collectionIds);
            res.setStatus(HttpServletResponse.SC_CREATED);
            res.getWriter().print("The file was created successfully.");
            res.flushBuffer();
        } catch (FileUploadException e) {
            logger.error("An error occurred while parsing request.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while parsing request : " + e.getMessage());
        } catch (UserNotExistingException e) {
            logger.error("You need to be connected to upload a product.", e);
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You need to be connected to upload a product.");
        } catch (UploadingException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (RootNotModifiableException e) {
            logger.error("An error occurred while uploading the product.", e);
            res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    "An error occurred while uploading the product : " + e.getMessage());
        } catch (ProductNotAddedException e) {
            logger.error("Your product can not be read by the system.", e);
            res.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE, "Your product can not be read by the system.");
        }
    } else {
        res.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE,
                "Request contents type is not supported by the servlet.");
    }
}

From source file:edu.um.umflix.stubs.UploadServletStub.java

protected List<FileItem> getFileItems(HttpServletRequest request) throws FileUploadException {
    if (error.equals("fileUpload"))
        new FileUploadException();

    File file = null;//from www .  j  a  va 2  s  .c o m
    FileItem item1 = null;
    List<FileItem> list = new ArrayList<FileItem>();
    for (int i = 0; i < fields.length; i++) {
        FileItem item = Mockito.mock(FileItem.class);
        Mockito.when(item.isFormField()).thenReturn(true);
        Mockito.when(item.getFieldName()).thenReturn(fields[i]);
        if (fields[i].equals("premiere") || fields[i].equals("endDate") || fields[i].equals("startDate")) {
            Mockito.when(item.getString()).thenReturn("2013-06-01");
        } else {
            Mockito.when(item.getString()).thenReturn("11");
        }
        if (fields[i].equals("premiere") && error.equals("date"))
            Mockito.when(item.getString()).thenReturn("11");
        if (fields[i].equals("clipduration0")) {
            Mockito.when(item.getString()).thenReturn("01:22:01");
        }
        list.add(item);
    }
    try {
        file = File.createTempFile("aaaa", "aaaatest");
        item1 = Mockito.mock(FileItem.class);
        Mockito.when(item1.getInputStream()).thenReturn(new FileInputStream(file));

    } catch (IOException e) {
        e.printStackTrace();
    }

    list.add(item1);
    FileItem token = Mockito.mock(FileItem.class);
    Mockito.when(token.isFormField()).thenReturn(true);
    Mockito.when(token.getFieldName()).thenReturn("token");
    if (error.equals("token")) {
        Mockito.when(token.getString()).thenReturn("invalidToken");
    } else
        Mockito.when(token.getString()).thenReturn("validToken");

    list.add(token);

    return list;
}

From source file:com.surevine.alfresco.audit.listeners.PerishableUploadDocumentAuditEventListener.java

@Override
protected void populateSecondaryAuditItems(List<Auditable> events, HttpServletRequest request,
        HttpServletResponse response, JSONObject postContent) throws JSONException {
    // Create a ServletFileUpload instance to parse the form
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    upload.setHeaderEncoding("UTF-8");

    if (ServletFileUpload.isMultipartContent(request)) {
        try {//ww  w .j  a  va  2s .c o m
            String perishableReason = null;
            String tags = null;

            for (final Object o : upload.parseRequest(request)) {
                FileItem item = (FileItem) o;

                if (item.isFormField() && "perishable".equals(item.getFieldName())) {
                    perishableReason = item.getString();
                } else if (item.isFormField() && "tags".equals(item.getFieldName())) {
                    tags = item.getString();
                }
            }

            Auditable primaryEvent = events.get(0);

            // If this is a site with perish reasons configured...
            if (_perishabilityLogic.getPerishReasons(primaryEvent.getSite()).size() > 0) {
                AuditItem item = new AuditItem();

                setGenericAuditMetadata(item, request);

                // Copy any relevant fields from the primary audit event
                item.setNodeRef(primaryEvent.getNodeRef());
                item.setVersion(primaryEvent.getVersion());
                item.setSecLabel(primaryEvent.getSecLabel());
                item.setSource(primaryEvent.getSource());

                item.setAction(MarkPerishableAuditEventListener.ACTION);

                if (!StringUtils.isBlank(perishableReason)) {
                    item.setDetails(perishableReason);
                } else {
                    item.setDetails(MarkPerishableAuditEventListener.NO_PERISHABLE_MARK);
                }

                if (tags != null) {
                    item.setTags(StringUtils.join(tags.trim().split(" "), ','));
                }

                events.add(item);
            }
        } catch (FileUploadException e) {
            logger.error("Error while parsing request form", e);
        }
    }
}

From source file:com.linkedin.pinot.controller.api.restlet.resources.LLCSegmentCommit.java

boolean uploadSegment(final String instanceId, final String segmentNameStr) {
    // 1/ Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory();

    // 2/ Create a new file upload handler based on the Restlet
    // FileUpload extension that will parse Restlet requests and
    // generates FileItems.
    final RestletFileUpload upload = new RestletFileUpload(factory);
    final List<FileItem> items;

    try {//from   ww  w.  ja va  2  s .  co m
        // The following statement blocks until the entire segment is read into memory.
        items = upload.parseRequest(getRequest());

        boolean found = false;
        File dataFile = null;

        for (final Iterator<FileItem> it = items.iterator(); it.hasNext() && !found;) {
            final FileItem fi = it.next();
            if (fi.getFieldName() != null && fi.getFieldName().equals(segmentNameStr)) {
                found = true;
                dataFile = new File(tempDir, segmentNameStr);
                fi.write(dataFile);
            }
        }

        if (!found) {
            LOGGER.error("Segment not included in request. Instance {}, segment {}", instanceId,
                    segmentNameStr);
            return false;
        }
        // We will not check for quota here. Instead, committed segments will count towards the quota of a
        // table
        LLCSegmentName segmentName = new LLCSegmentName(segmentNameStr);
        final String rawTableName = segmentName.getTableName();
        final File tableDir = new File(baseDataDir, rawTableName);
        final File segmentFile = new File(tableDir, segmentNameStr);

        synchronized (_pinotHelixResourceManager) {
            if (segmentFile.exists()) {
                LOGGER.warn("Segment file {} exists. Replacing with upload from {}", segmentNameStr,
                        instanceId);
                FileUtils.deleteQuietly(segmentFile);
            }
            FileUtils.moveFile(dataFile, segmentFile);
        }

        return true;
    } catch (Exception e) {
        LOGGER.error("File upload exception from instance {} for segment {}", instanceId, segmentNameStr, e);
    }
    return false;
}

From source file:info.magnolia.cms.filters.CommonsFileUploadMultipartRequestFilter.java

/**
 * Add the <code>FileItem</code> as a document into the <code>MultipartForm</code>.
 *///from  w  ww .  jav a 2  s.  c om
private void addFile(FileItem item, MultipartForm form) throws Exception {
    String atomName = item.getFieldName();
    String fileName = item.getName();
    String type = item.getContentType();
    File file = File.createTempFile(atomName, null, this.tempDir);
    item.write(file);

    form.addDocument(atomName, fileName, type, file);
}

From source file:net.scran24.staff.server.services.UploadUserInfoService.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("text/html");
    ServletOutputStream outputStream = resp.getOutputStream();
    PrintWriter writer = new PrintWriter(outputStream);

    if (!ServletFileUpload.isMultipartContent(req)) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } else {/*from w  w w  . ja  v a2 s . c o  m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = upload.parseRequest(req);

            InputStream file = null;
            String role = null;
            Set<String> permissions = new HashSet<String>();
            String surveyId = req.getParameter("surveyId");

            for (FileItem i : items) {
                if (i.getFieldName().equals("file"))
                    file = i.getInputStream();
                else if (i.getFieldName().equals("role"))
                    role = i.getString();
                else if (i.getFieldName().equals("permission"))
                    permissions.add(i.getString());
            }

            if (file == null)
                throw new ServletException("file field not specified");
            if (role == null)
                throw new ServletException("role field not specified");
            if (surveyId == null)
                throw new ServletException("surveyId field not specified");

            List<UserRecord> userRecords = UserRecordCSV.fromCSV(file);

            try {
                Set<String> roles = new HashSet<String>();
                roles.add(role);

                dataStore.saveUsers(surveyId, mapToSecureUserRecords(userRecords, roles, permissions));
                writer.print("OK");
            } catch (DataStoreException e) {
                writer.print("ERR:" + e.getMessage());
            } catch (DuplicateKeyException e) {
                writer.print("ERR:" + e.getMessage());
            }

        } catch (FileUploadException e) {
            writer.print("ERR:" + e.getMessage());
        } catch (IOException e) {
            writer.print("ERR:" + e.getMessage());
        }
    }

    writer.close();
}

From source file:by.creepid.jsf.fileupload.UploadFilter.java

private void processFormField(FileItem formField, Map<String, String[]> parameterMap) {

    String name = formField.getFieldName();
    String value = formField.getString();
    String[] values = parameterMap.get(name);

    if (values == null) {
        // Not in parameter map yet, so add as new value.
        parameterMap.put(name, new String[] { value });
    } else {/*from  w w  w.j  a v a2s.co  m*/
        // Multiple field values, so add new value to existing array.
        int length = values.length;
        String[] newValues = new String[length + 1];

        System.arraycopy(values, 0, newValues, 0, length);

        newValues[length] = value;
        parameterMap.put(name, newValues);
    }
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from   w  w w  .j av  a2s . co  m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.form.upload.UploadFormPostRequestProcessor.java

public void process(List<FileItem> fileItems, Writer writer) throws IOException {
    assert fileItems != null;
    assert writer != null;

    Map<String, String> formParameters = new HashMap<String, String>();
    Map<String, FileItem> fileFields = new HashMap<String, FileItem>();
    for (FileItem item : fileItems) {
        if (item.isFormField()) {
            formParameters.put(item.getFieldName(), item.getString());
        } else {/*from ww  w.  j a va 2  s .c o m*/
            fileFields.put(item.getFieldName(), item);
        }
    }

    if (logger.isDebugEnabled()) { // Avoid expensive function calls if logging is not needed
        logger.debug("Request data (UPLOAD FORM)=>" + getFormParametersLogString(formParameters) + " FILES: "
                + getFileParametersLogString(fileFields));
    }
    String result = process(formParameters, fileFields);

    String resultString = "<html><body><textarea>";
    resultString += result;
    resultString += ("</textarea></body></html>");
    writer.write(resultString);
    if (logger.isDebugEnabled()) {
        logger.debug("ResponseData data (UPLOAD FORM)=>" + resultString);
    }
}