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

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

Introduction

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

Prototype

InputStream getInputStream() throws IOException;

Source Link

Document

Returns an java.io.InputStream InputStream that can be used to retrieve the contents of the file.

Usage

From source file:de.micromata.genome.gwiki.controls.GWikiMountedWeb.java

public void initialize(GWikiContext wikiContext, FileItem dataFile, String pathPrefix) {
    if (dataFile == null) {
        wikiContext.addSimpleValidationError("No Zip available");
        return;/*w  w w  .  j av  a  2  s. co  m*/
    }
    try {

        mountZipFileSystem(dataFile.getInputStream(), wikiContext, pathPrefix);
    } catch (Exception ex) {
        wikiContext.addSimpleValidationError("Failure while mounting Zip File System: " + ex.getMessage());
        return;
    }
}

From source file:fr.opensagres.xdocreport.document.web.UploadXDocReportServlet.java

/**
 * Handles all requests (by default).//ww w . ja  v a 2 s .  c  o  m
 * 
 * @param request HttpServletRequest object containing client request
 * @param response HttpServletResponse object for the response
 */
protected void doUpload(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

        // 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 {
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            for (Iterator<FileItem> iterator = items.iterator(); iterator.hasNext();) {

                FileItem fileItem = (FileItem) iterator.next();

                if ("uploadfile".equals(fileItem.getFieldName())) {

                    InputStream in = fileItem.getInputStream();
                    try {
                        String reportId = generateReportId(fileItem, request);
                        IXDocReport report = getRegistryForUpload(request).loadReport(in, reportId);

                        // Check if report id exists in global registry
                        getRegistry(request).checkReportId(report.getId());
                        reportLoaded(report, request);
                        doForward(report, request, response);
                        break;
                    } catch (XDocReportException e) {
                        throw new ServletException(e);
                    }
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException(e);
        }

    }
}

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

/**
 * store new Snowprofile in Database// w  ww  .ja  v a2 s .c o m
 * 
 * @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:ccc.plugins.multipart.apache.MultipartForm.java

/** {@inheritDoc} */
@Override/*from  w w w. j  av  a2 s . c  o m*/
public InputStream getInputStream(final String string) throws IOException {
    final FileItem item = getFormItem(string);
    return (null == item) ? null : item.getInputStream();
}

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

/**
 * The doPost method of the servlet. <br>
 *
 * This method is called when a form has its tag value method equals to
 * post./*from www . j a v a2 s. c  o  m*/
 *
 * @param request
 *            the request send by the client to the server
 * @param response
 *            the response send by the server to the client
 * @throws ServletException
 *             if an error occurred
 * @throws IOException
 *             if an error occurred
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Connection conn = null;
    BufferedReader reader = null;
    try {
        MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);

        long clientTime = multipartRequest.getLongParameter("clientTime");
        long serverTime = System.currentTimeMillis();
        // Compute the "skew" between client and server in minutes.
        // This implicitly throw out things that are < 1 min so we lose the
        // regular
        // lagtime it takes to upload the submission and post the launch
        // events.
        int skew = (int) ((serverTime - clientTime) / 1000 / 60);

        StudentRegistration registration = (StudentRegistration) request.getAttribute("studentRegistration");
        Project project = (Project) request.getAttribute("project");

        FileItem fileItem = multipartRequest.getFileItem();
        reader = new BufferedReader(new InputStreamReader(fileItem.getInputStream()));
        String prevLine = null;
        conn = getConnection();
        PreparedStatement stmt = EclipseLaunchEvent.makeInsertStatement(conn);
        int count = 0;
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            if (line.equals(prevLine))
                continue;
            prevLine = line;
            // eclipseLaunchEvent date timestamp projectName event
            String tokens[] = line.split("\t");
            String timestampStr = tokens[1];
            String md5sum = tokens[2];
            String projectName = tokens[3];
            String event = tokens[4];

            getSubmitServerServletLog().debug(timestampStr + "\t" + md5sum + "\t" + projectName + "\t" + event);

            EclipseLaunchEvent eclipseLaunchEvent = new EclipseLaunchEvent();
            eclipseLaunchEvent.setStudentRegistrationPK(registration.getStudentRegistrationPK());
            eclipseLaunchEvent.setProjectNumber(projectName);
            eclipseLaunchEvent.setProjectPK(project.getProjectPK());
            eclipseLaunchEvent.setEvent(event);
            long timestamp = Long.valueOf(timestampStr);
            eclipseLaunchEvent.setTimestamp(new Timestamp(timestamp));
            eclipseLaunchEvent.setMd5sum(md5sum);
            eclipseLaunchEvent.setSkew(skew);
            eclipseLaunchEvent.fillInInsertStatement(stmt);
            stmt.addBatch();
            count++;
        }
        if (count > 0) {
            stmt.executeBatch();
            StudentSubmitStatus status = StudentSubmitStatus.lookupByStudentRegistrationPKAndProjectPK(
                    registration.getStudentRegistrationPK(), project.getProjectPK(), conn);
            if (status != null) {
                int totalEclipseLaunchEvents = EclipseLaunchEvent
                        .countEclipseLaunchEventsByProjectPKAndStudentRegistration(

                                project, registration, conn);
                status.setNumberRuns(totalEclipseLaunchEvents);
                status.update(conn);
            }
        }

    } catch (InvalidRequiredParameterException e) {
        ServletExceptionFilter.logErrorAndSendServerError(conn, ServerError.Kind.BAD_PARAMETERS, request, null,
                "LogEclipseLaunchEvent missing required parameter", "", e);
    } catch (SQLException e) {
        ServletExceptionFilter.logErrorAndSendServerError(conn, ServerError.Kind.EXCEPTION, request, null,
                "LogEclipseLaunchEvent missing required parameter", "", e);
    } finally {
        releaseConnection(conn);
        if (reader != null)
            reader.close();
    }
}

From source file:de.micromata.genome.gwiki.plugin.confluenceimporter_1_0.GWikiMountedConfluenceWeb.java

public void initialize(GWikiContext wikiContext, FileItem dataFile, String pathPrefix) {
    if (dataFile == null) {
        wikiContext.addSimpleValidationError("Kein Zip vorhanden");
        return;/*from   ww  w.j  a  v  a  2  s  .  c  o m*/
    }
    try {
        mountZipFileSystem(dataFile.getInputStream(), wikiContext, pathPrefix);
    } catch (Exception ex) {
        wikiContext.addSimpleValidationError("Failure while mounting Zip File System: " + ex.getMessage());
        return;
    }
}

From source file:com.kodemore.servlet.control.ScDropzone.java

private void tryHandleUpload() {
    try {//from   w w w .j  a  v a2s.c o m
        KmList<FileItem> files = getData().getUploadedFiles();

        for (FileItem item : files)
            try (BufferedInputStream in = Kmu.toBufferedInputStream(item.getInputStream())) {
                String fileName = FilenameUtils.getName(item.getName());
                byte[] data = Kmu.readBytesFrom(in);

                getUploadHandler().upload(fileName, data);
            }
    } catch (IOException ex) {
        KmLog.error(ex, "Dropzone upload failure.");
    }
}

From source file:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * Detect HTML in the first KB to prevent against potential security issue with IE/Safari/Opera file type auto detection bug. Returns
 * true if file contain insecure HTML code at the beginning.
 *
 * @param item file upload item//from ww w.  j ava  2 s  .c om
 * @return true if detected.
 * @throws IOException when io error occurs.
 */
public static boolean detectHtml(final FileItem item) throws IOException {
    byte[] buff = new byte[MAX_BUFFER_SIZE];
    InputStream is = null;
    try {
        is = item.getInputStream();
        is.read(buff, 0, MAX_BUFFER_SIZE);
        String content = new String(buff);
        content = content.toLowerCase().trim();

        if (Pattern
                .compile("<!DOCTYPE\\W+X?HTML.+", Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).matches()) {
            return true;
        }

        String[] tags = { "<body", "<head", "<html", "<img", "<pre", "<script", "<table", "<title" };

        for (String tag : tags) {
            if (content.indexOf(tag) != -1) {
                return true;
            }
        }

        if (Pattern
                .compile("type\\s*=\\s*[\'\"]?\\s*(?:\\w*/)?(?:ecma|java)",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).find()) {
            return true;
        }

        if (Pattern
                .compile("(?:href|src|data)\\s*=\\s*[\'\"]?\\s*(?:ecma|java)script:",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).find()) {
            return true;
        }

        if (Pattern
                .compile("url\\s*\\(\\s*[\'\"]?\\s*(?:ecma|java)script:",
                        Pattern.CASE_INSENSITIVE | Pattern.DOTALL | Pattern.MULTILINE)
                .matcher(content).find()) {
            return true;
        }
    } catch (IOException e) {
        throw e;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return false;
}

From source file:eml.studio.server.file.FileUploadServlet.java

/**
 * save file upload to server/*from ww  w .ja  va  2  s  .  c  om*/
 * @param request HttpServletRequest
 * @param response HttpServletResponse
 * @throws ServletException
 */

public void saveUploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
    List items = null;
    List items_findId = null;
    try {
        items = upload.parseRequest(request);
        items_findId = items;
    } catch (FileUploadException ex) {
        ex.printStackTrace();
    }
    String ID = new String();
    Iterator iter_findId = items_findId.iterator();
    while (iter_findId.hasNext()) {
        FileItem item_findId = (FileItem) iter_findId.next();
        if (item_findId.isFormField()) {
            String fieldName = item_findId.getFieldName();
            String fieldValue;
            try {
                fieldValue = item_findId.getString("UTF-8");

                if ("Fileuuid".equals(fieldName)) {
                    ID = Constants.MODULE_PATH + "/" + fieldValue;

                } else
                    ID = Constants.DATASET_PATH + "/" + fieldValue;
                logger.info("[UUID]:" + fieldName + ":" + ID);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
    Iterator iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();
        if (item.isFormField()) {
        } else {
            InputStream in;
            try {
                in = item.getInputStream();
                if (item.getName().endsWith(".zip")) {
                    unZipFiles(in, ID);
                    HDFSIO.uploadfile("/" + ID + "/", item, item.getName());
                } else {
                    if (ID.contains("Data")) {
                        HDFSIO.uploadfile("/" + ID + "/", item, ID.split("Data")[1]);
                    } else
                        HDFSIO.uploadfile("/" + ID + "/", item, item.getName());
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

From source file:com.ibm.bluemix.samples.UploadServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Upload Servlet");

    try {//from  w  w w.j  a  v a2s.  co m
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                // item is the file (and not a field), read it in and add to List
                Scanner scanner = new Scanner(new InputStreamReader(item.getInputStream(), "UTF-8"));
                List<String> lines = new ArrayList<String>();
                while (scanner.hasNextLine()) {
                    String line = scanner.nextLine().trim();
                    if (line.length() > 0) {
                        lines.add(line);
                    }
                }
                scanner.close();

                // add lines to database
                int rows = db.addPosts(lines);
                String msg = "Added " + rows + " rows.";
                request.setAttribute("msg", msg);
                break;
            }
        }

        request.setAttribute("posts", db.getResults());
    } catch (Exception e) {
        request.setAttribute("msg", e.getMessage());
        e.printStackTrace(System.err);
    }

    response.setContentType("text/html");
    response.setStatus(200);
    request.getRequestDispatcher("/home.jsp").forward(request, response);
}