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

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

Introduction

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

Prototype

String getString();

Source Link

Document

Returns the contents of the file item as a String, using the default character encoding.

Usage

From source file:com.gtwm.pb.servlets.ServletUtilMethods.java

/**
 * Replacement for and wrapper around/*w  ww.  ja  va 2 s  .  c om*/
 * HttpServletRequest.getParameter(String) which works for multi-part form
 * data as well as normal requests
 */
public static String getParameter(HttpServletRequest request, String parameterName,
        List<FileItem> multipartItems) {
    if (FileUpload.isMultipartContent(new ServletRequestContext(request))) {
        for (FileItem item : multipartItems) {
            if (item.getFieldName().equals(parameterName)) {
                if (item.isFormField()) {
                    return item.getString();
                } else {
                    return item.getName();
                }
            }
        }
        return null;
    } else {
        return request.getParameter(parameterName);
    }
}

From source file:com.krawler.esp.servlets.SuperAdminServlet.java

public static String createCompany(Connection conn, HttpServletRequest request, HttpServletResponse response)
        throws ServiceException {
    String status = "";
    DiskFileUpload fu = new DiskFileUpload();
    ResultSet frs = null, ars = null;
    PreparedStatement pstmt = null, fpstmt = null, apstmt = null;
    double val = 0.0;
    List fileItems = null;/*from w ww.j  av  a 2  s .  co m*/
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e);
    }

    HashMap arrParam = new HashMap();
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        FileItem fi1 = (FileItem) k.next();
        arrParam.put(fi1.getFieldName(), fi1.getString());
    }
    String companyid = UUID.randomUUID().toString();
    /*DbUtil
    .executeUpdate(
          conn,
          "insert into company(companyid, companyname, createdon, address, city, state, country, phone, fax, zip, "
                + "timezone, website) values (?, ?, now(), ?, ?, ?, ?, ?, ?, ?, ?, ?);",
          new Object[] { companyid, arrParam.get("companyname"),
                arrParam.get("address"), arrParam.get("city"),
                arrParam.get("state"), arrParam.get("country"),
                arrParam.get("phone"), arrParam.get("fax"),
                arrParam.get("zip"), arrParam.get("timezone"),
                arrParam.get("website") });*/
    java.util.Date d = new java.util.Date();
    java.sql.Timestamp today = new Timestamp(d.getTime());
    DbUtil.executeUpdate(conn,
            "INSERT INTO company(companyid, companyname, address, createdon, website) values (?,?,?,?,?);",
            new Object[] { companyid, arrParam.get("companyname"), arrParam.get("address"), today,
                    arrParam.get("website") });
    String userid = UUID.randomUUID().toString();
    String newPass = AuthHandler.generateNewPassword();
    String newPassSHA1 = AuthHandler.getSHA1(newPass);
    DbUtil.executeUpdate(conn, "insert into userlogin(userid, username, password, authkey) values (?,?,?,?);",
            new Object[] { userid, arrParam.get("username"), newPassSHA1, newPass });
    DbUtil.executeUpdate(conn, "insert into users(userid, companyid, image) values (?,?,?);",
            new Object[] { userid, companyid, "" });
    try {
        fpstmt = conn.prepareStatement("SELECT featureid FROM featurelist");
        frs = fpstmt.executeQuery();
        while (frs.next()) {
            apstmt = conn.prepareStatement("SELECT activityid FROM activitieslist WHERE featureid=?");
            apstmt.setInt(1, frs.getInt("featureid"));
            ars = apstmt.executeQuery();
            while (ars.next()) {
                val += Math.pow(2, Double.parseDouble(ars.getString("activityid")));
            }
            pstmt = conn.prepareStatement(
                    "INSERT INTO userpermissions (userid, featureid, permissions) VALUES (?,?,?)");
            pstmt.setString(1, userid);
            pstmt.setInt(2, frs.getInt("featureid"));
            pstmt.setInt(3, (int) val);
            pstmt.executeUpdate();

            val = 0.0;
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("signup.confirmSignup", e);
    } finally {
        DbPool.closeStatement(pstmt);
    }
    if (arrParam.get("image").toString().length() != 0) {
        genericFileUpload uploader = new genericFileUpload();
        try {
            uploader.doPost(fileItems, companyid, StorageHandler.GetProfileImgStorePath());
        } catch (ConfigurationException e) {
            throw ServiceException.FAILURE("SuperAdminHandler.createCompany", e);
        }
        if (uploader.isUploaded()) {
            DbUtil.executeUpdate(conn, "update company set image=? where companyid = ?", new Object[] {
                    ProfileImageServlet.ImgBasePath + companyid + uploader.getExt(), companyid, companyid });
        }
    }
    status = "success";
    return status;
}

From source file:com.silverpeas.util.i18n.I18NHelper.java

static private String getParameterValue(List<FileItem> items, String parameterName) {
    for (FileItem item : items) {
        if (item.isFormField() && parameterName.equals(item.getFieldName())) {
            return item.getString();
        }//ww  w  .  ja va 2s  .  c  o  m
    }
    return null;
}

From source file:com.aaasec.sigserv.csspserver.utility.SpServerLogic.java

public static String processFileUpload(HttpServletRequest request, HttpServletResponse response,
        RequestModel req) {/*from  w  w  w . jav  a2s .c om*/
    // Create a factory for disk-based file items
    Map<String, String> paraMap = new HashMap<String, String>();
    File uploadedFile = null;
    boolean uploaded = false;
    DiskFileItemFactory factory = new DiskFileItemFactory();
    String uploadDirName = FileOps.getfileNameString(SpModel.getDataDir(), "uploads");
    FileOps.createDir(uploadDirName);
    File storageDir = new File(uploadDirName);
    factory.setRepository(storageDir);

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                paraMap.put(name, value);
            } else {
                String fieldName = item.getFieldName();
                String fileName = item.getName();
                if (fileName.length() > 0) {
                    String contentType = item.getContentType();
                    boolean isInMemory = item.isInMemory();
                    long sizeInBytes = item.getSize();
                    uploadedFile = new File(storageDir, fileName);
                    try {
                        item.write(uploadedFile);
                        uploaded = true;
                    } catch (Exception ex) {
                        LOG.log(Level.SEVERE, null, ex);
                    }
                }
            }

        }
        if (uploaded) {
            return SpServerLogic.getDocUploadResponse(req, uploadedFile);
        } else {
            if (paraMap.containsKey("xmlName")) {
                return SpServerLogic.getServerDocResponse(req, paraMap.get("xmlName"));
            }
        }
    } catch (FileUploadException ex) {
        LOG.log(Level.SEVERE, null, ex);
    }
    response.setStatus(HttpServletResponse.SC_NO_CONTENT);
    return "";
}

From source file:dataMappers.PictureDataMapper.java

public static void addPictureToReport(DBConnector dbconnector, HttpServletRequest request)
        throws FileUploadException, IOException, SQLException {

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("Invalid upload request");
        return;/*from   ww  w.  j  a v  a  2 s  .c o m*/
    }

    // Define limits for disk item
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);

    // Define limit for servlet upload
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(MAX_REQUEST_SIZE);

    FileItem itemFile = null;
    int reportID = 0;

    // Get list of items in request (parameters, files etc.)
    List formItems = upload.parseRequest(request);
    Iterator iter = formItems.iterator();

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

        if (!item.isFormField()) {
            itemFile = item; // If not form field, must be item
        } else if (item.getFieldName().equalsIgnoreCase("reportID")) { // else it is a form field
            try {
                System.out.println(item.getString());
                reportID = Integer.parseInt(item.getString());
            } catch (NumberFormatException e) {
                reportID = 0;
            }
        }
    }

    // This will be null if no fields were declared as image/upload.
    // Also, reportID must be > 0
    if (itemFile != null || reportID == 0) {

        try {

            // Create credentials from final vars
            BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);

            // Create client with credentials
            AmazonS3 s3client = new AmazonS3Client(awsCredentials);
            // Set region
            s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));

            // Set content length (size) of file
            ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(itemFile.getSize());

            // Get extension for file
            String ext = FilenameUtils.getExtension(itemFile.getName());
            // Generate random filename
            String keyName = UUID.randomUUID().toString() + '.' + ext;

            // This is the actual upload command
            s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME, keyName, itemFile.getInputStream(), om));

            // Picture was uploaded to S3 if we made it this far. Now we insert the row into the database for the report.
            PreparedStatement stmt = dbconnector.getCon()
                    .prepareStatement("INSERT INTO reports_pictures" + "(REPORTID, PICTURE) VALUES (?,?)");

            stmt.setInt(1, reportID);
            stmt.setString(2, keyName);

            stmt.executeUpdate();

            stmt.close();

        } catch (AmazonServiceException ase) {

            System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                    + "to Amazon S3, but was rejected with an error response" + " for some reason.");
            System.out.println("Error Message:    " + ase.getMessage());
            System.out.println("HTTP Status Code: " + ase.getStatusCode());
            System.out.println("AWS Error Code:   " + ase.getErrorCode());
            System.out.println("Error Type:       " + ase.getErrorType());
            System.out.println("Request ID:       " + ase.getRequestId());

        } catch (AmazonClientException ace) {

            System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                    + "an internal error while trying to " + "communicate with S3, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ace.getMessage());

        }

    }
}

From source file:com.exilant.exility.core.XLSHandler.java

/**
 * @param req//from   ww  w  .j a v a  2s  .co m
 * @param container
 * @return whether we are able to parse it
 */
@SuppressWarnings("unchecked")
public static boolean parseMultiPartData(HttpServletRequest req, ServiceData container) {
    /**
     * I didnt check here for multipart request ?. caller should check.
     */
    DiskFileItemFactory factory = new DiskFileItemFactory();
    /*
     * we can increase the in memory size to hold the file data but its
     * inefficient so ignoring to factory.setSizeThreshold(20*1024);
     */
    ServletFileUpload sFileUpload = new ServletFileUpload(factory);
    List<FileItem> items = null;

    try {
        items = sFileUpload.parseRequest(req);
    } catch (FileUploadException e) {
        container.addMessage("fileUploadFailed", e.getMessage());
        Spit.out(e);
        return false;
    }

    /*
     * If user is asked for multiple file upload with filesPathGridName then
     * create a grid with below columns and send to the client/DC
     */
    String filesPathGridName = req.getHeader("filesPathGridName");
    OutputColumn[] columns = { new OutputColumn("fileName", DataValueType.TEXT, "fileName"),
            new OutputColumn("fileSize", DataValueType.INTEGRAL, "fileSize"),
            new OutputColumn("filePath", DataValueType.TEXT, "filePath") };
    Value[] columnValues = null;

    FileItem f = null;
    String allowMultiple = req.getHeader("allowMultiple");

    List<Value[]> rows = new ArrayList<Value[]>();

    String fileNameWithPath = "";
    String rootPath = getResourcePath();

    String fileName = null;

    int fileCount = 0;

    for (FileItem item : items) {
        if (item.isFormField()) {
            String name = item.getFieldName();
            container.addValue(name, item.getString());
        } else {
            f = item;
            if (allowMultiple != null) {
                fileCount++;
                fileName = item.getName();
                fileNameWithPath = rootPath + getUniqueName(fileName);

                String path = XLSHandler.write(item, fileNameWithPath, container);
                if (path == null) {
                    return false;
                }

                if (filesPathGridName != null && filesPathGridName.length() > 0) {
                    columnValues = new Value[3];
                    columnValues[0] = Value.newValue(fileName);
                    columnValues[1] = Value.newValue(f.getSize());
                    columnValues[2] = Value.newValue(fileNameWithPath);
                    rows.add(columnValues);
                    fileNameWithPath = "";
                    continue;
                }

                container.addValue("file" + fileCount + "_ExilityPath", fileNameWithPath);
                fileNameWithPath = "";
            }

        }
    }

    if (f != null && allowMultiple == null) {
        fileNameWithPath = rootPath + getUniqueName(f.getName());
        String path = XLSHandler.write(f, fileNameWithPath, container);
        if (path == null) {
            return false;
        }
        container.addValue(container.getValue("fileFieldName"), path);
        return true;
    }

    /**
     * If user asked for multiple file upload and has supplied gridName for
     * holding the file path then create a grid
     */

    if (rows.size() > 0) {
        Grid aGrid = new Grid(filesPathGridName);
        aGrid.setValues(columns, rows, null);

        container.addGrid(filesPathGridName, aGrid.getRawData());
    }
    return true;
}

From source file:com.openmeap.util.ServletUtils.java

/**
 * @param modelManager//from   w  w w.j  a v a  2s  .  c o m
 * @param request
 * @param map
 * @return
 * @throws FileUploadException
 */
static final public Boolean handleFileUploads(Integer maxFileUploadSize, String fileStoragePrefix,
        HttpServletRequest request, Map<Object, Object> map) throws FileUploadException {

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);
    factory.setRepository(new File(fileStoragePrefix));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxFileUploadSize);

    List fileItems = upload.parseRequest(request);
    for (FileItem item : (List<FileItem>) fileItems) {
        // we'll put this in the parameter map,
        // assuming the backing that is looking for it
        // knows what to expect
        String fieldName = item.getFieldName();
        Boolean isFormField = item.isFormField();
        Long size = item.getSize();
        if (isFormField) {
            if (size > 0) {
                map.put(fieldName, new String[] { item.getString() });
            }
        } else if (!isFormField) {
            map.put(fieldName, item);
        }
    }

    return true;
}

From source file:com.google.caja.ancillary.servlet.UploadPage.java

static void doUpload(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Process the uploaded items
    List<ObjectConstructor> uploads = Lists.newArrayList();

    if (ServletFileUpload.isMultipartContent(req)) {
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();

        int maxUploadSizeBytes = 1 << 18;
        factory.setSizeThreshold(maxUploadSizeBytes); // In-memory threshold
        factory.setRepository(new File("/dev/null")); // Do not store on disk
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(maxUploadSizeBytes);

        writeHeader(resp);/*  w ww.  j  a  v  a2 s.  c  om*/

        // Parse the request
        List<?> items;
        try {
            items = upload.parseRequest(req);
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            resp.getWriter().write(Nodes.encode(ex.getMessage()));
            return;
        }

        for (Object fileItemObj : items) {
            FileItem item = (FileItem) fileItemObj; // Written for pre-generic java.
            if (!item.isFormField()) { // Then is a file
                FilePosition unk = FilePosition.UNKNOWN;
                String ct = item.getContentType();
                uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                        StringLiteral.valueOf(unk, item.getString()), "ip",
                        StringLiteral.valueOf(unk, item.getName()), "it",
                        ct != null ? StringLiteral.valueOf(unk, ct) : null));
            }
        }
    } else if (req.getParameter("url") != null) {
        List<URI> toFetch = Lists.newArrayList();
        boolean failed = false;
        for (String value : req.getParameterValues("url")) {
            try {
                toFetch.add(new URI(value));
            } catch (URISyntaxException ex) {
                if (!failed) {
                    failed = true;
                    resp.setStatus(500);
                    resp.setContentType("text/html;charset=UTF-8");
                }
                resp.getWriter().write("<p>Bad URI: " + Nodes.encode(ex.getMessage()));
            }
        }
        if (failed) {
            return;
        }
        writeHeader(resp);
        FilePosition unk = FilePosition.UNKNOWN;
        for (URI uri : toFetch) {
            try {
                Content c = UriFetcher.fetch(uri);
                if (c.isText()) {
                    uploads.add((ObjectConstructor) QuasiBuilder.substV("({ i: @i, ip: @ip, it: @it? })", "i",
                            StringLiteral.valueOf(unk, c.getText()), "ip",
                            StringLiteral.valueOf(unk, uri.toString()), "it",
                            StringLiteral.valueOf(unk, c.type.mimeType)));
                }
            } catch (IOException ex) {
                resp.getWriter()
                        .write("<p>" + Nodes.encode("Failed to fetch URI: " + uri + " : " + ex.getMessage()));
            }
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        resp.getWriter().write("Content not multipart");
        return;
    }

    Expression notifyParent = (Expression) QuasiBuilder.substV(
            "window.parent.uploaded([@uploads*], window.name)", "uploads", new ParseTreeNodeContainer(uploads));
    StringBuilder jsBuf = new StringBuilder();
    RenderContext rc = new RenderContext(new JsMinimalPrinter(new Concatenator(jsBuf))).withEmbeddable(true);
    notifyParent.render(rc);
    rc.getOut().noMoreTokens();

    HtmlQuasiBuilder b = HtmlQuasiBuilder.getBuilder(DomParser.makeDocument(null, null));

    Writer out = resp.getWriter();
    out.write(Nodes.render(b.substV("<script>@js</script>", "js", jsBuf.toString())));
}

From source file:com.krawler.esp.handlers.fileUploader.java

public static void parseRequest(HttpServletRequest request, HashMap<String, String> arrParam,
        ArrayList<FileItem> fi, boolean fileUpload) throws ServiceException {
    DiskFileUpload fu = new DiskFileUpload();
    FileItem fi1 = null;
    List fileItems = null;//w ww  .ja  v  a  2s . c o  m
    try {
        fileItems = fu.parseRequest(request);
    } catch (FileUploadException e) {
        throw ServiceException.FAILURE("Admin.createUser", e);
    }
    for (Iterator k = fileItems.iterator(); k.hasNext();) {
        fi1 = (FileItem) k.next();
        if (fi1.isFormField()) {
            arrParam.put(fi1.getFieldName(), fi1.getString());
        } else {
            try {
                String fileName = new String(fi1.getName().getBytes(), "UTF8");
                if (fi1.getSize() != 0) {
                    fi.add(fi1);
                    fileUpload = true;
                }
            } catch (UnsupportedEncodingException ex) {
            }
        }
    }
}

From source file:edu.umd.cs.submitServer.MultipartRequest.java

public static MultipartRequest parseRequest(HttpServletRequest request, int maxSize, Logger logger,
        boolean strictChecking, ServletContext servletContext) throws IOException, ServletException {

    DiskFileItemFactory factory = getFactory(servletContext);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setSizeMax(maxSize);/* w ww. j  a v a 2  s. co m*/
    MultipartRequest multipartRequest = new MultipartRequest(logger, strictChecking);
    try {
        // Parse the request
        List<FileItem> items = upload.parseRequest(request);

        for (FileItem item : items) {

            if (item.isFormField()) {
                multipartRequest.setParameter(item.getFieldName(), item.getString());
            } else {
                multipartRequest.addFileItem(item);
            }
        }
        return multipartRequest;
    } catch (FileUploadBase.SizeLimitExceededException e) {
        Debug.error("File upload is too big " + e.getActualSize() + " > " + e.getPermittedSize());
        Debug.error("upload info: " + multipartRequest);
        throw new ServletException(e);
    } catch (FileUploadException e) {
        Debug.error("FileUploadException: " + e);
        throw new ServletException(e);
    }
}