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

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

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:edu.uniminuto.servlets.GuardarDisco.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w ww . j a  va2 s . com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String nombre = "";
    long precio = 0;
    int anhio = 0;
    short genero = 1;
    int interprete = 1;

    //        String nombre = getParameter(request, "nombre");
    //        long precio = Long.valueOf(getParameter(request, "precio"));
    //        int anhio = Integer.valueOf(getParameter(request, "anhio"));
    //
    //        int genero = Integer.valueOf(getParameter(request, "genero"));
    //        int interprete = Integer.valueOf(getParameter(request, "interprete"));

    String url = "";
    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        String imagen = "images/";

        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 4, new File("c;//tmp"));

        // Configure a repository (to ensure a secure temp location is used)
        ServletContext servletContext = this.getServletConfig().getServletContext();
        File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
        factory.setRepository(repository);

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();

            if (item.isFormField()) {
                if (item.getFieldName().equals("nombre")) {
                    nombre = item.getString();
                } else if (item.getFieldName().equals("anhio")) {
                    anhio = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("genero")) {
                    genero = Short.valueOf(item.getString());
                } else if (item.getFieldName().equals("interprete")) {
                    interprete = Integer.valueOf(item.getString());
                } else if (item.getFieldName().equals("precio")) {
                    precio = Long.valueOf(item.getString());
                }

            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();

                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                //                    InputStream uploadedStream = item.getInputStream();
                //                    uploadedStream.close();
                imagen = imagen + fileName;
                File uploadedFile = new File(RUTA + fileName);

                item.write(uploadedFile);
                //                    } else {
                //                        
                //                    }
            }
        }

        java.util.Calendar cl = java.util.Calendar.getInstance();
        cl.set(anhio, 0, 0, 0, 0, 0);

        Disco disco = new Disco();
        disco.setGenero(generoFacade.find(genero));
        disco.setInterprete(interpreteFacade.find(interprete));
        disco.setNombre(nombre);
        disco.setImagen(imagen);
        disco.setAnhio(cl.getTime());

        discoFacade.create(disco);

        if (disco.getId() != null) {

            Discopropietario dp = new Discopropietario();
            dp.setDisco(disco);
            dp.setPropietario((Persona) request.getSession().getAttribute("usuario"));
            dp.setPrecio(precio);
            dp.setVendido(false);

            dpFacade.create(dp);

            url = "disco?id=" + disco.getId();

        } else {
            url = "fdisco?nombre=" + nombre + "&precio=" + precio + "&anhio=" + anhio + "&genero=" + genero
                    + "&interprete=" + interprete;
        }

    } catch (FileUploadException ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(GuardarDisco.class.getName()).log(Level.SEVERE, null, ex);
    }

    response.sendRedirect(url);

}

From source file:com.exedio.cope.live.Bar.java

void doRequest(final HttpServletRequest request, final HttpSession httpSession,
        final HttpServletResponse response, final Anchor anchor) throws IOException {
    if (!Cop.isPost(request)) {
        try {//from w ww.j  av a 2  s. c o  m
            startTransaction("redirectHome");
            anchor.redirectHome(request, response);
            model.commit();
        } finally {
            model.rollbackIfNotCommitted();
        }
        return;
    }

    final String referer;

    if (isMultipartContent(request)) {
        final HashMap<String, String> fields = new HashMap<String, String>();
        final HashMap<String, FileItem> files = new HashMap<String, FileItem>();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding(UTF_8.name());
        try {
            for (final Iterator<?> i = upload.parseRequest(request).iterator(); i.hasNext();) {
                final FileItem item = (FileItem) i.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString(UTF_8.name()));
                else
                    files.put(item.getFieldName(), item);
            }
        } catch (final FileUploadException e) {
            throw new RuntimeException(e);
        }

        final String featureID = fields.get(FEATURE);
        if (featureID == null)
            throw new NullPointerException();

        final Media feature = (Media) model.getFeature(featureID);
        if (feature == null)
            throw new NullPointerException(featureID);

        final String itemID = fields.get(ITEM);
        if (itemID == null)
            throw new NullPointerException();

        final FileItem file = files.get(FILE);

        try {
            startTransaction("publishFile(" + featureID + ',' + itemID + ')');

            final Item item = model.getItem(itemID);

            if (fields.get(PUBLISH_NOW) != null) {
                for (final History history : History.getHistories(item.getCopeType())) {
                    final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(), false);
                    event.createFeature(feature, feature.getName(),
                            feature.isNull(item) ? null
                                    : ("file type=" + feature.getContentType(item) + " size="
                                            + feature.getLength(item)),
                            "file name=" + file.getName() + " type=" + file.getContentType() + " size="
                                    + file.getSize());
                }

                // TODO use more efficient setter with File or byte[]
                feature.set(item, file.getInputStream(), file.getContentType());
            } else {
                anchor.modify(file, feature, item);
            }

            model.commit();
        } catch (final NoSuchIDException e) {
            throw new RuntimeException(e);
        } finally {
            model.rollbackIfNotCommitted();
        }

        referer = fields.get(REFERER);
    } else // isMultipartContent
    {
        if (request.getParameter(BORDERS_ON) != null || request.getParameter(BORDERS_ON_IMAGE) != null) {
            anchor.borders = true;
        } else if (request.getParameter(BORDERS_OFF) != null
                || request.getParameter(BORDERS_OFF_IMAGE) != null) {
            anchor.borders = false;
        } else if (request.getParameter(CLOSE) != null || request.getParameter(CLOSE_IMAGE) != null) {
            httpSession.removeAttribute(LoginServlet.ANCHOR);
        } else if (request.getParameter(SWITCH_TARGET) != null) {
            anchor.setTarget(servlet.getTarget(request.getParameter(SWITCH_TARGET)));
        } else if (request.getParameter(SAVE_TARGET) != null) {
            try {
                startTransaction("saveTarget");
                anchor.getTarget().save(anchor);
                model.commit();
            } finally {
                model.rollbackIfNotCommitted();
            }
            anchor.notifyPublishedAll();
        } else {
            final String featureID = request.getParameter(FEATURE);
            if (featureID == null)
                throw new NullPointerException();

            final Feature featureO = model.getFeature(featureID);
            if (featureO == null)
                throw new NullPointerException(featureID);

            final String itemID = request.getParameter(ITEM);
            if (itemID == null)
                throw new NullPointerException();

            if (featureO instanceof StringField) {
                final StringField feature = (StringField) featureO;
                final String value = request.getParameter(TEXT);

                try {
                    startTransaction("barText(" + featureID + ',' + itemID + ')');

                    final Item item = model.getItem(itemID);

                    if (request.getParameter(PUBLISH_NOW) != null) {
                        String v = value;
                        if ("".equals(v))
                            v = null;
                        for (final History history : History.getHistories(item.getCopeType())) {
                            final History.Event event = history.createEvent(item, anchor.getHistoryAuthor(),
                                    false);
                            event.createFeature(feature, feature.getName(), feature.get(item), v);
                        }
                        feature.set(item, v);
                        anchor.notifyPublished(feature, item);
                    } else {
                        anchor.modify(value, feature, item);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            } else {
                final IntegerField feature = (IntegerField) featureO;
                final String itemIDFrom = request.getParameter(ITEM_FROM);
                if (itemIDFrom == null)
                    throw new NullPointerException();

                try {
                    startTransaction("swapPosition(" + featureID + ',' + itemIDFrom + ',' + itemID + ')');

                    final Item itemFrom = model.getItem(itemIDFrom);
                    final Item itemTo = model.getItem(itemID);

                    final Integer positionFrom = feature.get(itemFrom);
                    final Integer positionTo = feature.get(itemTo);
                    feature.set(itemFrom, feature.getMinimum());
                    feature.set(itemTo, positionFrom);
                    feature.set(itemFrom, positionTo);

                    for (final History history : History.getHistories(itemFrom.getCopeType())) {
                        final History.Event event = history.createEvent(itemFrom, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionFrom, positionTo);
                    }
                    for (final History history : History.getHistories(itemTo.getCopeType())) {
                        final History.Event event = history.createEvent(itemTo, anchor.getHistoryAuthor(),
                                false);
                        event.createFeature(feature, feature.getName(), positionTo, positionFrom);
                    }

                    model.commit();
                } catch (final NoSuchIDException e) {
                    throw new RuntimeException(e);
                } finally {
                    model.rollbackIfNotCommitted();
                }
            }
        }

        referer = request.getParameter(REFERER);
    }

    if (referer != null)
        response.sendRedirect(response.encodeRedirectURL(referer));
}

From source file:com.uniquesoft.uidl.servlet.UploadServlet.java

/**
 * Get an uploaded file item.//from   ww  w . j  ava  2  s .com
 * 
 * @param request
 * @param response
 * @throws IOException
 */
public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String parameter = request.getParameter(UConsts.PARAM_SHOW);
    FileItem item = findFileItem(getMySessionFileItems(request), parameter);
    if (item != null) {
        logger.debug("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize()
                + " bytes");
        response.setContentType(item.getContentType());
        copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream());
    } else {
        logger.info("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " file isn't in session.");
        renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
    }
}

From source file:fr.paris.lutece.portal.web.admin.AdminPageJspBean.java

/**
 * Processes of the modification of the page informations
 *
 * @param request The http request//from   www  .j  a v a2  s  . com
 * @return The jsp url result of the process
 */
public String doModifyPage(HttpServletRequest request) {
    MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
    int nPageId = Integer.parseInt(mRequest.getParameter(Parameters.PAGE_ID));

    Page page = PageHome.getPage(nPageId);
    Integer nOldAutorisationNode = page.getIdAuthorizationNode();

    String strErrorUrl = getPageData(mRequest, page);

    if (strErrorUrl != null) {
        return strErrorUrl;
    }

    int nParentPageId = Integer.parseInt(mRequest.getParameter(Parameters.PARENT_ID));

    if (nParentPageId != page.getParentPageId()) {
        strErrorUrl = getNewParentPageId(mRequest, page, nParentPageId);

        if (strErrorUrl != null) {
            return strErrorUrl;
        }
    }

    //set the authorization node
    if (page.getNodeStatus() != 0) {
        Page parentPage = PageHome.getPage(page.getParentPageId());
        page.setIdAuthorizationNode(parentPage.getIdAuthorizationNode());
    } else {
        page.setIdAuthorizationNode(page.getId());
    }

    if ((page.getIdAuthorizationNode() == null)
            || !page.getIdAuthorizationNode().equals(nOldAutorisationNode)) {
        PageService.updateChildrenAuthorizationNode(page.getId(), page.getIdAuthorizationNode());
    }

    String strUpdatePicture = mRequest.getParameter(PARAMETER_PAGE_TEMPLATE_UPDATE_IMAGE);
    FileItem item = mRequest.getFile(PARAMETER_IMAGE_CONTENT);

    boolean bUpdatePicture = false;
    String strPictureName = FileUploadService.getFileNameOnly(item);

    if (strUpdatePicture != null) {
        if (strPictureName.equals("")) {
            return AdminMessageService.getMessageUrl(request, Messages.MANDATORY_FILE, AdminMessage.TYPE_STOP);
        } else {
            bUpdatePicture = true;
        }
    }

    if (bUpdatePicture) {
        byte[] bytes = item.get();
        String strMimeType = item.getContentType();
        page.setImageContent(bytes);
        page.setMimeType(strMimeType);
    }

    // Updates the page
    _pageService.updatePage(page);

    // Displays again the current page with the modifications
    return getUrlPage(nPageId);
}

From source file:com.github.podd.resources.UploadArtifactResourceImpl.java

private InferredOWLOntologyID uploadFileAndLoadArtifactIntoPodd(final Representation entity)
        throws ResourceException {
    List<FileItem> items;// ww w.j  a v a  2  s .  c  o m
    Path filePath = null;
    String contentType = null;

    // 1: Create a factory for disk-based file items
    final DiskFileItemFactory factory = new DiskFileItemFactory(1000240, this.tempDirectory.toFile());

    // 2: Create a new file upload handler
    final RestletFileUpload upload = new RestletFileUpload(factory);
    final Map<String, String> props = new HashMap<String, String>();
    try {
        // 3: Request is parsed by the handler which generates a list of
        // FileItems
        items = upload.parseRequest(this.getRequest());

        for (final FileItem fi : items) {
            final String name = fi.getName();

            if (name == null) {
                props.put(fi.getFieldName(), new String(fi.get(), StandardCharsets.UTF_8));
            } else {
                // FIXME: Strip everything up to the last . out of the
                // filename so that
                // the filename can be used for content type determination
                // where
                // possible.
                // InputStream uploadedFileInputStream =
                // fi.getInputStream();
                try {
                    // Note: These are Java-7 APIs
                    contentType = fi.getContentType();
                    props.put("Content-Type", fi.getContentType());

                    filePath = Files.createTempFile(this.tempDirectory, "ontologyupload-", name);
                    final File file = filePath.toFile();
                    file.deleteOnExit();
                    fi.write(file);
                } catch (final IOException ioe) {
                    throw ioe;
                } catch (final Exception e) {
                    // avoid throwing a generic exception just because the
                    // apache
                    // commons library throws Exception
                    throw new IOException(e);
                }
            }
        }
    } catch (final IOException | FileUploadException e) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e);
    }

    this.log.info("props={}", props.toString());

    if (filePath == null) {
        throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST,
                "Did not submit a valid file and filename");
    }

    this.log.info("filename={}", filePath.toAbsolutePath().toString());
    this.log.info("contentType={}", contentType);

    RDFFormat format = null;

    // If the content type was application/octet-stream then use the file
    // name instead
    // Browsers attach this content type when they are not sure what the
    // real type is
    if (MediaType.APPLICATION_OCTET_STREAM.getName().equals(contentType)) {
        format = Rio.getParserFormatForFileName(filePath.getFileName().toString());

        this.log.info("octet-stream contentType filename format={}", format);
    }
    // Otherwise use the content type directly in preference to using the
    // filename
    else if (contentType != null) {
        format = Rio.getParserFormatForMIMEType(contentType);

        this.log.info("non-octet-stream contentType format={}", format);
    }

    // If the content type choices failed to resolve the type, then try the
    // filename
    if (format == null) {
        format = Rio.getParserFormatForFileName(filePath.getFileName().toString());

        this.log.info("non-content-type filename format={}", format);
    }

    // Or fallback to RDF/XML which at minimum is able to detect when the
    // document is
    // structurally invalid
    if (format == null) {
        this.log.warn("Could not determine RDF format from request so falling back to RDF/XML");
        format = RDFFormat.RDFXML;
    }

    try (final InputStream inputStream = new BufferedInputStream(
            Files.newInputStream(filePath, StandardOpenOption.READ));) {
        return this.uploadFileAndLoadArtifactIntoPodd(inputStream, format, DanglingObjectPolicy.REPORT,
                DataReferenceVerificationPolicy.DO_NOT_VERIFY);
    } catch (final IOException e) {
        throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "File IO error occurred", e);
    }

}

From source file:com.aes.controller.EmpireController.java

@RequestMapping(value = "addpresentation", method = RequestMethod.POST)
public String doAction5(HttpServletRequest request, HttpServletResponse response,
        @ModelAttribute Chapter chapter, @ModelAttribute UserDetails loggedUser, BindingResult result,
        Map<String, Object> map) throws ServletException, IOException {
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(MEMORY_THRESHOLD);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);
    Presentation tempPresentation = new Presentation();
    String chapterId = "";
    String description = "";
    try {//from   w w w  . j a  va2s .c o  m
        @SuppressWarnings("unchecked")
        List<FileItem> formItems = upload.parseRequest(request);

        if (formItems != null && formItems.size() > 0) {
            for (FileItem item : formItems) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = context.getRealPath("") + File.separator + "uploads" + File.separator
                            + fileName;
                    File storeFile = new File(filePath);
                    item.write(storeFile);
                    tempPresentation.setFilePath(filePath);
                    tempPresentation.setFileSize(item.getSize());
                    tempPresentation.setFileType(item.getContentType());
                    tempPresentation.setFileName(fileName);
                } else {
                    String name = item.getFieldName();
                    String value = item.getString();
                    if (name.equals("chapterId")) {
                        chapterId = value;
                    } else {
                        description = value;
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    tempPresentation.setRecordStatus(true);
    tempPresentation.setDescription(description);
    int id = Integer.parseInt(chapterId);
    tempPresentation.setChapter(this.service.getChapterById(id));
    service.addPresentation(tempPresentation);
    map.put("tempPresentation", new Presentation());
    map.put("chapterId", chapterId);
    map.put("presentations", service.getAllPresentationsByChapterId(Integer.parseInt(chapterId)));
    return "../../admin/add_presentation";
}

From source file:com.food.adminservlet.FoodServlet.java

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    int foodid = 0;
    String foodName = "";
    String fooddesc = "";
    Double foodprice = 0.0;/*from   ww  w. java  2  s  .c  om*/
    String foodCategory = "";
    PrintWriter out = response.getWriter();
    isMultipart = ServletFileUpload.isMultipartContent(request);
    FoodBean bkfood = new FoodBean();
    FoodBL foodbl = new FoodBL();
    try {

        response.setContentType("text/html");
        //java.io.PrintWriter out = response.getWriter( );

        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(maxMemSize);
        // Location to save data that is larger than maxMemSize.
        factory.setRepository(new File("c:\\temp"));

        // Create a new file upload handler
        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum file size to be uploaded.
        upload.setSizeMax(maxFileSize);

        // Parse the request to get file items.
        List fileItems = upload.parseRequest(request);

        // Process the uploaded file items
        Iterator i = fileItems.iterator();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet upload</title>");
        out.println("</head>");
        out.println("<body>");
        while (i.hasNext()) {

            FileItem fi = (FileItem) i.next();
            if (fi.isFormField()) {
                if (fi.getFieldName().equals("foodid")) {
                    foodid = Integer.parseInt(fi.getString());
                }
                if (fi.getFieldName().equals("foodname")) {
                    foodName = fi.getString();
                }
                if (fi.getFieldName().equals("fooddesc")) {
                    fooddesc = fi.getString();
                }
                if (fi.getFieldName().equals("foodprice")) {
                    foodprice = Double.parseDouble(fi.getString());
                }
                if (fi.getFieldName().equals("foodcate")) {
                    foodCategory = fi.getString();
                }

                out.println("<br>");
            }
            if (!fi.isFormField()) {
                // Get the uploaded file parameters
                String fieldName = fi.getFieldName();
                fileName = fi.getName();
                String contentType = fi.getContentType();
                boolean isInMemory = fi.isInMemory();
                long sizeInBytes = fi.getSize();
                // Write the file
                if (fileName.lastIndexOf("\\") >= 0) {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                } else {
                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                }
                fi.write(file);
                out.println("Uploaded Filename: " + fileName + "<br>");
            }
        }

        out.println(fileName);

        bkfood.setFoodId(foodid);
        bkfood.setFoodName(foodName);
        bkfood.setFoodPrice(foodprice);
        bkfood.setFoodCateg(foodCategory);
        bkfood.setFoodDesc(fooddesc);
        bkfood.setFoodRetreiveImage(fileName);
        // bkfood.setFoodimage(request.getPart("foodimage"));
        bkfood.setFoodstatus("Y");

        int chk = foodbl.addFoodItems(bkfood);
        out.println(chk);

        if (chk == 1) {
            response.sendRedirect("food.jsp");
        }

    } catch (Exception ex) {
        out.println(ex);
    }
}

From source file:com.duroty.application.mail.actions.SendAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {//from   w w  w . ja v  a 2 s .co  m
        boolean isMultipart = FileUpload.isMultipartContent(request);

        Mail mailInstance = getMailInstance(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector attachments = new Vector();

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

            //Process the uploaded items
            Iterator iter = items.iterator();

            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();

                if (item.isFormField()) {
                    if (item.getFieldName().equals("forwardAttachments")) {
                        String[] aux = item.getString().split(":");
                        MailPartObj part = mailInstance.getAttachment(aux[0], aux[1]);
                        attachments.addElement(part);
                    } else {
                        fields.put(item.getFieldName(), item.getString());
                    }
                } else {
                    if (!StringUtils.isBlank(item.getName())) {
                        ByteArrayOutputStream baos = null;

                        try {
                            baos = new ByteArrayOutputStream();

                            IOUtils.copy(item.getInputStream(), baos);

                            MailPartObj part = new MailPartObj();
                            part.setAttachent(baos.toByteArray());
                            part.setContentType(item.getContentType());
                            part.setName(item.getName());
                            part.setSize(item.getSize());

                            attachments.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            String body = "";

            if (fields.get("taBody") != null) {
                body = (String) fields.get("taBody");
            } else if (fields.get("taReplyBody") != null) {
                body = (String) fields.get("taReplyBody");
            }

            Preferences preferencesInstance = getPreferencesInstance(request);

            Send sendInstance = getSendInstance(request);

            String mid = (String) fields.get("mid");

            if (StringUtils.isBlank(mid)) {
                request.setAttribute("action", "compose");
            } else {
                request.setAttribute("action", "reply");
            }

            Boolean isHtml = null;

            if (StringUtils.isBlank((String) fields.get("isHtml"))) {
                isHtml = new Boolean(preferencesInstance.getPreferences().isHtmlMessage());
            } else {
                isHtml = Boolean.valueOf((String) fields.get("isHtml"));
            }

            sendInstance.send(mid, Integer.parseInt((String) fields.get("identity")), (String) fields.get("to"),
                    (String) fields.get("cc"), (String) fields.get("bcc"), (String) fields.get("subject"), body,
                    attachments, isHtml.booleanValue(), Charset.defaultCharset().displayName(),
                    (String) fields.get("priority"));
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
            request.setAttribute("exception", "The form is null");
            request.setAttribute("newLocation", null);
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:gwtupload.server.UploadServlet.java

/**
 * Get an uploaded file item./* w w w.  jav a  2s  .  c o m*/
 *
 * @param request
 * @param response
 * @throws IOException
 */
public void getUploadedFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String parameter = request.getParameter(UConsts.PARAM_SHOW);
    FileItem item = findFileItem(getMySessionFileItems(request), parameter);
    if (item != null) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " returning: " + item.getContentType() + ", " + item.getName() + ", " + item.getSize()
                + " bytes");
        response.setContentType(item.getContentType());
        copyFromInputStreamToOutputStream(item.getInputStream(), response.getOutputStream());
    } else {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") getUploadedFile: " + parameter
                + " file isn't in session.");
        renderXmlResponse(request, response, XML_ERROR_ITEM_NOT_FOUND);
    }
}

From source file:it.infn.ct.g_hmmer_portlet.java

/**
 * This method manages the user input fields managing two cases 
 * distinguished by the type of the input <form ... statement
 * The use of upload file controls needs the use of "multipart/form-data"
 * while the else condition of the isMultipartContent check manages the 
 * standard input case. The multipart content needs a manual processing of
 * all <form items/*from ww  w . ja v a2  s.c  o  m*/
 * All form' input items are identified by the 'name' input property
 * inside the jsp file
 * 
 * @param request   ActionRequest instance (processAction)
 * @param appInput  AppInput instance storing the jobSubmission data
 */
void getInputForm(ActionRequest request, AppInput appInput) {
    if (PortletFileUpload.isMultipartContent(request))
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            PortletFileUpload upload = new PortletFileUpload(factory);
            List items = upload.parseRequest(request);
            File repositoryPath = new File("/tmp");
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            diskFileItemFactory.setRepository(repositoryPath);
            Iterator iter = items.iterator();
            String logstring = "";
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                long sizeInBytes = item.getSize();
                // Prepare a log string with field list
                logstring += LS + "field name: '" + fieldName + "' - '" + item.getString() + "'";
                switch (inputControlsIds.valueOf(fieldName)) {
                case file_inputFile:
                    appInput.inputFileName = item.getString();
                    processInputFile(item, appInput);
                    break;
                case inputFile:
                    appInput.inputFileText = item.getString();
                    break;
                case JobIdentifier:
                    appInput.jobIdentifier = item.getString();
                    break;
                default:
                    _log.warn("Unhandled input field: '" + fieldName + "' - '" + item.getString() + "'");
                } // switch fieldName                                                   
            } // while iter.hasNext()   
            _log.info(LS + "Reporting" + LS + "---------" + LS + logstring + LS);
        } // try
        catch (Exception e) {
            _log.info("Caught exception while processing files to upload: '" + e.toString() + "'");
        }
    // The input form do not use the "multipart/form-data" 
    else {
        // Retrieve from the input form the given application values
        appInput.inputFileName = (String) request.getParameter("file_inputFile");
        appInput.inputFileText = (String) request.getParameter("inputFile");
        appInput.jobIdentifier = (String) request.getParameter("JobIdentifier");
    } // ! isMultipartContent

    // Show into the log the taken inputs
    _log.info(LS + "Taken input parameters:" + LS + "-----------------------" + LS + "inputFileName: '"
            + appInput.inputFileName + "'" + LS + "inputFileText: '" + appInput.inputFileText + "'" + LS
            + "jobIdentifier: '" + appInput.jobIdentifier + "'" + LS);
}