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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:net.morphbank.mbsvc3.webservices.RestServiceExcelUpload.java

private String saveTempFile(FileItem item) {
    FileOutputStream outputStream;
    String filename = "";
    filename = folderPath + item.getName();
    try {//from w w w  . j a  va 2  s .  c  o m
        File file = new File(filename);
        if (file.exists())
            file.delete();
        outputStream = new FileOutputStream(filename);
        outputStream.write(item.get());
        outputStream.close();
        return folderPath;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Test creation of a field for which the amount of data falls above the
 * configured threshold.//  www .  jav  a  2  s  .  c o m
 */
@Test
public void testAboveThreshold() throws Exception {
    // Create the FileItem
    byte[] testFieldValueBytes = createContentBytes(threshold + 1);
    FileItem item = createFileItem(testFieldValueBytes);

    // Check state is as expected
    assertFalse("Initial: in memory", item.isInMemory());
    assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
    compareBytes("Initial", item.get(), testFieldValueBytes);

    // Serialize & Deserialize
    FileItem newItem = (FileItem) serializeDeserialize(item);

    // Test deserialized content is as expected
    assertFalse("Check in memory", newItem.isInMemory());
    compareBytes("Check", testFieldValueBytes, newItem.get());

    // Compare FileItem's (except byte[])
    compareFileItems(item, newItem);

    item.delete();
    newItem.delete();
}

From source file:com.github.davidcarboni.encryptedfileupload.EncryptedFileItemSerializeTest.java

/**
 * Helper method to test creation of a field when a repository is used.
 *//*from w  ww  .j  a  v  a  2s . co  m*/
public void testInMemoryObject(byte[] testFieldValueBytes, File repository) {
    FileItem item = createFileItem(testFieldValueBytes, repository);

    // Check state is as expected
    assertTrue("Initial: in memory", item.isInMemory());
    assertEquals("Initial: size", item.getSize(), testFieldValueBytes.length);
    compareBytes("Initial", item.get(), testFieldValueBytes);

    // Serialize & Deserialize
    FileItem newItem = (FileItem) serializeDeserialize(item);

    // Test deserialized content is as expected
    assertTrue("Check in memory", newItem.isInMemory());
    compareBytes("Check", testFieldValueBytes, newItem.get());

    // Compare FileItem's (except byte[])
    compareFileItems(item, newItem);
}

From source file:com.bibisco.filters.FileFilter.java

/**
 * Example of how to get useful things with the uploaded file structure.
  * Generally speaking, this method should be overrided by framework's users.
 * /*from  w  w  w .  j a  v  a  2 s  .c o  m*/
 * <p>Here we demostrate how to extract useful infos 
 * (<code>name, value, isInMemory, size, etc) </code>)
 * plus how to deal with memory- or disk-persisted cases.
 * 
 * <li><p>We pass the whole <code>FileItem</code> structure
 * to the next <code>jsp</code> page, which gains the ability to extract 
 * infos as well: via Request, under name: "file-" + fieldname
 * 
 * <li><p>The file content can be retrieved here or later, <code>FileItem</code>
 * object can use its data-getters in <code>.jsp</code>s! 
 * <p>In this code, we retrieve file content and pass it in Request 
 * for next uses under the a general format of 
 * array of bytes (<code>byte []</code>);  with name equal to "file-" + fieldname.  
 *  
 * @param pItem
 * @throws IOException
 */
protected void processUploadedFile(FileItem pItem, ServletRequest pRequest) throws IOException {
    String name = pItem.getFieldName();
    boolean isInMemory = pItem.isInMemory();
    pRequest.setAttribute("file-" + name, pItem);

    if (isInMemory) {
        mLog.debug("the file ", name, " is in memory under the request attribute file-content-", name);
        byte[] data = pItem.get();
        pRequest.setAttribute("file-content-" + name, data);
    } else {
        mLog.debug("the file ", name, " is in the file system and under the request attribute file-content-",
                name);
        InputStream uploadedStream = pItem.getInputStream();
        byte[] data = (new StreamTokenizer(new BufferedReader(new InputStreamReader(uploadedStream))))
                .toString().getBytes();
        uploadedStream.close();
        pRequest.setAttribute("file-content-" + name, data);
    }
}

From source file:at.gv.egiz.pdfas.web.servlets.VerifyServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/* ww w . j a  v  a  2s.c o m*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    logger.info("Post verify request");

    String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request);
    PdfAsHelper.setErrorURL(request, response, errorUrl);

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.VERIFY);
    statisticEvent.setUserAgent(UserAgentFilter.getUserAgent());

    try {
        byte[] filecontent = null;

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // No Uploaded data!
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                doGet(request, response);
                return;
            } else {
                throw new PdfAsWebException("No Signature data defined!");
            }
        } else {
            // configures upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(THRESHOLD_SIZE);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE);

            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<?> formItems = upload.parseRequest(request);
            logger.debug(formItems.size() + " Items in form data");
            if (formItems.size() < 1) {
                // No Uploaded data!
                // Try do get
                // No Uploaded data!
                if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                    doGet(request, response);
                    return;
                } else {
                    throw new PdfAsWebException("No Signature data defined!");
                }
            } else {
                for (int i = 0; i < formItems.size(); i++) {
                    Object obj = formItems.get(i);
                    if (obj instanceof FileItem) {
                        FileItem item = (FileItem) obj;
                        if (item.getFieldName().equals(UPLOAD_PDF_DATA)) {
                            filecontent = item.get();
                            try {
                                File f = new File(item.getName());
                                String name = f.getName();
                                logger.debug("Got upload: " + item.getName());
                                if (name != null) {
                                    if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) {
                                        name += ".pdf";
                                    }

                                    logger.debug("Setting Filename in session: " + name);
                                    PdfAsHelper.setPDFFileName(request, name);
                                }
                            } catch (Throwable e) {
                                logger.warn("In resolving filename", e);
                            }
                            if (filecontent.length < 10) {
                                filecontent = null;
                            } else {
                                logger.debug("Found pdf Data! Size: " + filecontent.length);
                            }
                        } else {
                            request.setAttribute(item.getFieldName(), item.getString());
                            logger.debug("Setting " + item.getFieldName() + " = " + item.getString());
                        }
                    } else {
                        logger.debug(obj.getClass().getName() + " - " + obj.toString());
                    }
                }
            }
        }

        if (filecontent == null) {
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request));
            }
        }

        if (filecontent == null) {
            Object sourceObj = request.getAttribute("source");
            if (sourceObj != null) {
                String source = sourceObj.toString();
                if (source.equals("internal")) {
                    request.setAttribute("FILEERR", true);
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                    statisticEvent.setStatus(Status.ERROR);
                    statisticEvent.setException(new Exception("No file uploaded"));
                    statisticEvent.setEndNow();
                    statisticEvent.setTimestampNow();
                    StatisticFrontend.getInstance().storeEvent(statisticEvent);
                    statisticEvent.setLogged(true);

                    return;
                }
            }
            throw new PdfAsException("No Signature data available");
        }

        doVerify(request, response, filecontent, statisticEvent);
    } catch (Throwable e) {

        statisticEvent.setStatus(Status.ERROR);
        statisticEvent.setException(e);
        if (e instanceof PDFASError) {
            statisticEvent.setErrorCode(((PDFASError) e).getCode());
        }
        statisticEvent.setEndNow();
        statisticEvent.setTimestampNow();
        StatisticFrontend.getInstance().storeEvent(statisticEvent);
        statisticEvent.setLogged(true);

        logger.warn("Generic Error: ", e);
        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}

From source file:com.slamd.admin.RequestInfo.java

/**
 * Creates a new set of request state information using the provided request
 * and response./* w w  w. j av a  2  s. c o m*/
 *
 * @param  request   Information about the HTTP request issued by the client.
 * @param  response  Information about the HTTP response that will be returned
 *                   to the client.
 */
public RequestInfo(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;

    generateHTML = true;
    debugInfo = new StringBuilder();
    htmlBody = new StringBuilder();
    infoMessage = new StringBuilder();

    if (request != null) {
        servletBaseURI = request.getRequestURI();
        userIdentifier = request.getRemoteUser();

        if (FileUpload.isMultipartContent(request)) {
            try {
                FileUpload fileUpload = new FileUpload(new DefaultFileItemFactory());
                multipartFieldList = fileUpload.parseRequest(request);
                Iterator iterator = multipartFieldList.iterator();

                while (iterator.hasNext()) {
                    FileItem fileItem = (FileItem) iterator.next();
                    String name = fileItem.getFieldName();
                    if (name.equals(Constants.SERVLET_PARAM_SECTION)) {
                        section = new String(fileItem.get());
                    } else if (name.equals(Constants.SERVLET_PARAM_SUBSECTION)) {
                        subsection = new String(fileItem.get());
                    }
                }
            } catch (FileUploadException fue) {
                fue.printStackTrace();
            }
        } else {
            section = request.getParameter(Constants.SERVLET_PARAM_SECTION);
            subsection = request.getParameter(Constants.SERVLET_PARAM_SUBSECTION);
        }
    }

    if (section == null) {
        section = "";
    }

    if (subsection == null) {
        subsection = "";
    }
}

From source file:fr.paris.lutece.portal.web.stylesheet.StyleSheetJspBean.java

/**
 * Reads stylesheet's data/*from  w w w  .  j ava  2 s.  c o  m*/
 * @param multipartRequest The request
 * @param stylesheet The style sheet
 * @return An error message URL or null if no error
 */
private String getData(MultipartHttpServletRequest multipartRequest, StyleSheet stylesheet) {
    String strErrorUrl = null;
    String strDescription = multipartRequest.getParameter(Parameters.STYLESHEET_NAME);
    String strStyleId = multipartRequest.getParameter(Parameters.STYLES);
    String strModeId = multipartRequest.getParameter(Parameters.MODE_STYLESHEET);

    FileItem fileSource = multipartRequest.getFile(Parameters.STYLESHEET_SOURCE);
    byte[] baXslSource = fileSource.get();
    String strFilename = FileUploadService.getFileNameOnly(fileSource);

    // Mandatory fields
    if (strDescription.equals("") || (strFilename == null) || strFilename.equals("")) {
        return AdminMessageService.getMessageUrl(multipartRequest, Messages.MANDATORY_FIELDS,
                AdminMessage.TYPE_STOP);
    }

    //test the existence of style or mode already associate with this stylesheet
    int nStyleId = Integer.parseInt(strStyleId);
    int nModeId = Integer.parseInt(strModeId);
    int nCount = StyleSheetHome.getStyleSheetNbPerStyleMode(nStyleId, nModeId);

    // Do not create a stylesheet of there is already one
    if ((nCount >= 1) && (stylesheet.getId() == 0 /* creation */ )) {
        return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_STYLESHEET_ALREADY_EXISTS,
                AdminMessage.TYPE_STOP);
    }

    // Check the XML validity of the XSL stylesheet
    if (isValid(baXslSource) != null) {
        Object[] args = { isValid(baXslSource) };

        return AdminMessageService.getMessageUrl(multipartRequest, MESSAGE_STYLESHEET_NOT_VALID, args,
                AdminMessage.TYPE_STOP);
    }

    stylesheet.setDescription(strDescription);
    stylesheet.setStyleId(Integer.parseInt(strStyleId));
    stylesheet.setModeId(Integer.parseInt(strModeId));
    stylesheet.setSource(baXslSource);
    stylesheet.setFile(strFilename);

    return strErrorUrl;
}

From source file:commands.SendAnalysisRequest.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response, Controller controller) {
    //http://commons.apache.org/proper/commons-fileupload/using.html
    //process only if its multipart content
    String page = "Problem.jsp";
    if (ServletFileUpload.isMultipartContent(request)) {
        try {//from w  ww  .j  a  v  a 2s  .  c  o m
            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Configure a repository (to ensure a secure temp location is used)
            ServletContext servletContext = controller.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            System.out.println("File repository absolute path: " + repository.getAbsolutePath());

            factory.setRepository(repository);

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

            //parametros chave-valor (path valor)
            HashMap<String, String[]> params = new HashMap<String, String[]>();
            //parametros chave-valor para multimedia (path e array de bytes)
            HashMap<String, byte[]> mediaParams = new HashMap<String, byte[]>();

            // Tratando todos os parametros/itens da pagina (arquivos e no-arquivos)
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                //key (path)
                FileItem item = iter.next();
                String key = item.getFieldName();

                if (item.isFormField()) {
                    //printFormField(item);
                    //value
                    String[] value = new String[1];
                    value[0] = item.getString();
                    params.put(key, value);
                } else {
                    //printUploadedFile(item);
                    byte[] value = item.get();
                    mediaParams.put(key, value);
                }
            }

            //File uploaded successfully
            //              request.setAttribute("message", "File Uploaded Successfully");
            long result = new ParamedicController().sendAnalysisRequest(params, 1, mediaParams);

            if (result == -1) {
                request.setAttribute("message", "Occurred a problem to sending analysis request");
            } else {
                request.setAttribute("idAnalysis", result);
                request.setAttribute("message", "Analysis request sent successfully");
                page = "AnalysisResponseSearch.jsp";
                //RequestDispatcher reqDispatcher = request.getRequestDispatcher("AnalysisResponseSearch.jsp");
                //reqDispatcher.forward(request, response);
            }

            //                request.getRequestDispatcher("AnalysisResponseSearch.jsp").forward(request, response);
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
            ex.printStackTrace();
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    try {
        request.getRequestDispatcher(page).forward(request, response);
    } catch (ServletException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:edu.umd.cs.submitServer.servlets.ReportTestOutcomes.java

/**
 * @param multipartRequest/*from w w w  . java  2 s. c  om*/
 * @return
 */
private byte[] getfileItemDataAndDelete(MultipartRequest multipartRequest) {
    // Get the fileItem
    FileItem fileItem = multipartRequest.getFileItem();
    byte[] data = fileItem.get();
    fileItem.delete();
    return data;
}

From source file:at.gv.egiz.pdfas.web.servlets.ExternSignServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)//ww  w .  j  a va  2 s.com
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //PdfAsHelper.regenerateSession(request);

    logger.debug("Post signing request");

    String errorUrl = PdfAsParameterExtractor.getInvokeErrorURL(request);
    PdfAsHelper.setErrorURL(request, response, errorUrl);

    StatisticEvent statisticEvent = new StatisticEvent();
    statisticEvent.setStartNow();
    statisticEvent.setSource(Source.WEB);
    statisticEvent.setOperation(Operation.SIGN);
    statisticEvent.setUserAgent(UserAgentFilter.getUserAgent());

    try {
        byte[] filecontent = null;

        // checks if the request actually contains upload file
        if (!ServletFileUpload.isMultipartContent(request)) {
            // No Uploaded data!
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                doGet(request, response);
                return;
            } else {
                throw new PdfAsWebException("No Signature data defined!");
            }
        } else {
            // configures upload settings
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(WebConfiguration.getFilesizeThreshold());
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(WebConfiguration.getMaxFilesize());
            upload.setSizeMax(WebConfiguration.getMaxRequestsize());

            // constructs the directory path to store upload file
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
            // creates the directory if it does not exist
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<?> formItems = upload.parseRequest(request);
            logger.debug(formItems.size() + " Items in form data");
            if (formItems.size() < 1) {
                // No Uploaded data!
                // Try do get
                // No Uploaded data!
                if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                    doGet(request, response);
                    return;
                } else {
                    throw new PdfAsWebException("No Signature data defined!");
                }
            } else {
                for (int i = 0; i < formItems.size(); i++) {
                    Object obj = formItems.get(i);
                    if (obj instanceof FileItem) {
                        FileItem item = (FileItem) obj;
                        if (item.getFieldName().equals(UPLOAD_PDF_DATA)) {
                            filecontent = item.get();
                            try {
                                File f = new File(item.getName());
                                String name = f.getName();
                                logger.debug("Got upload: " + item.getName());
                                if (name != null) {
                                    if (!(name.endsWith(".pdf") || name.endsWith(".PDF"))) {
                                        name += ".pdf";
                                    }

                                    logger.debug("Setting Filename in session: " + name);
                                    PdfAsHelper.setPDFFileName(request, name);
                                }
                            } catch (Throwable e) {
                                logger.warn("In resolving filename", e);
                            }
                            if (filecontent.length < 10) {
                                filecontent = null;
                            } else {
                                logger.debug("Found pdf Data! Size: " + filecontent.length);
                            }
                        } else {
                            request.setAttribute(item.getFieldName(), item.getString());
                            logger.debug("Setting " + item.getFieldName() + " = " + item.getString());
                        }
                    } else {
                        logger.debug(obj.getClass().getName() + " - " + obj.toString());
                    }
                }
            }
        }

        if (filecontent == null) {
            if (PdfAsParameterExtractor.getPdfUrl(request) != null) {
                filecontent = RemotePDFFetcher.fetchPdfFile(PdfAsParameterExtractor.getPdfUrl(request));
            }
        }

        if (filecontent == null) {
            Object sourceObj = request.getAttribute("source");
            if (sourceObj != null) {
                String source = sourceObj.toString();
                if (source.equals("internal")) {
                    request.setAttribute("FILEERR", true);
                    request.getRequestDispatcher("index.jsp").forward(request, response);

                    statisticEvent.setStatus(Status.ERROR);
                    statisticEvent.setException(new Exception("No file uploaded"));
                    statisticEvent.setEndNow();
                    statisticEvent.setTimestampNow();
                    StatisticFrontend.getInstance().storeEvent(statisticEvent);
                    statisticEvent.setLogged(true);

                    return;
                }
            }
            throw new PdfAsException("No Signature data available");
        }

        doSignature(request, response, filecontent, statisticEvent);
    } catch (Exception e) {
        logger.error("Signature failed", e);
        statisticEvent.setStatus(Status.ERROR);
        statisticEvent.setException(e);
        if (e instanceof PDFASError) {
            statisticEvent.setErrorCode(((PDFASError) e).getCode());
        }
        statisticEvent.setEndNow();
        statisticEvent.setTimestampNow();
        StatisticFrontend.getInstance().storeEvent(statisticEvent);
        statisticEvent.setLogged(true);

        PdfAsHelper.setSessionException(request, response, e.getMessage(), e);
        PdfAsHelper.gotoError(getServletContext(), request, response);
    }
}