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.vectorcast.plugins.vectorcastexecution.job.NewMultiJobTest.java

@Test
public void testNoReporting() throws Exception {
    StaplerRequest request = Mockito.mock(StaplerRequest.class);
    StaplerResponse response = Mockito.mock(StaplerResponse.class);
    JSONObject jsonForm = new JSONObject();
    jsonForm.put("manageProjectName", "/home/jenkins/vcast/project.vcm");
    jsonForm.put("optionUseReporting", false);
    jsonForm.put("optionClean", false);
    when(request.getSubmittedForm()).thenReturn(jsonForm);

    FileItem fileItem = Mockito.mock(FileItem.class);
    when(request.getFileItem("manageProject")).thenReturn(fileItem);
    when(fileItem.getString()).thenReturn(PROJECTFILE14);

    NewMultiJob job = new NewMultiJob(request, response, false);
    Assert.assertEquals("project", job.getBaseName());
    job.create(false);//from   ww  w  . j a  va 2 s  . co m
    Assert.assertTrue(job.getTopProject() != null);
    Assert.assertEquals(project, job.getTopProject());

    // Check build wrappers - main project...
    Assert.assertEquals(0, bldWrappersList.size());
    // No cleanup

    // Check build actions - main project...
    Assert.assertEquals(5, bldrsList.size());
    Assert.assertTrue(bldrsList.get(0) instanceof VectorCASTSetup);
    Assert.assertTrue(bldrsList.get(1) instanceof MultiJobBuilder);
    Assert.assertTrue(bldrsList.get(2) instanceof CopyArtifact);
    Assert.assertTrue(bldrsList.get(3) instanceof CopyArtifact);
    Assert.assertTrue(bldrsList.get(4) instanceof VectorCASTCommand);

    // Check publishers - main project...
    Assert.assertEquals(0, publisherList.size());

    // Now check the additional build/report projects

    // Build/execute - project 1
    checkBuildExecuteSteps2(bldrsList1);

    Assert.assertEquals(1, publisherList1.size());
    Assert.assertTrue(publisherList1.get(0) instanceof GroovyPostbuildRecorder);

    // Build/execute - project 2
    checkBuildExecuteSteps2(bldrsList2);

    Assert.assertEquals(1, publisherList2.size());
    Assert.assertTrue(publisherList2.get(0) instanceof GroovyPostbuildRecorder);
}

From source file:com.fredck.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * /*from   w  w w  .ja va  2 s . com*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("ConnectorServlet.doPost");
    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }
    System.out.println("1111111111111111111111");
    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:com.acciente.commons.htmlform.Parser.java

private static Map parsePOSTMultiPart(HttpServletRequest oRequest, int iStoreFileOnDiskThresholdInBytes,
        File oUploadedFileStorageDir) throws FileUploadException, IOException, ParserException {
    Map oMultipartParams = new HashMap();

    // we have multi-part content, we process it with apache-commons-fileupload

    ServletFileUpload oMultipartParser = new ServletFileUpload(
            new DiskFileItemFactory(iStoreFileOnDiskThresholdInBytes, oUploadedFileStorageDir));

    List oFileItemList = oMultipartParser.parseRequest(oRequest);

    for (Iterator oIter = oFileItemList.iterator(); oIter.hasNext();) {
        FileItem oFileItem = (FileItem) oIter.next();

        // we support the variable name to use the full syntax allowed in non-multipart forms
        // so we use parseParameterSpec() to support array and map variable syntaxes in multi-part mode
        Reader oParamNameReader = null;
        ParameterSpec oParameterSpec = null;

        try {//w w  w.j a  v  a  2  s .c  om
            oParamNameReader = new StringReader(oFileItem.getFieldName());

            oParameterSpec = Parser.parseParameterSpec(oParamNameReader,
                    oFileItem.isFormField() ? Symbols.TOKEN_VARTYPE_STRING : Symbols.TOKEN_VARTYPE_FILE);
        } finally {
            if (oParamNameReader != null) {
                oParamNameReader.close();
            }
        }

        if (oFileItem.isFormField()) {
            Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem.getString(), false);
        } else {
            Parser.addParameter2Form(oMultipartParams, oParameterSpec, oFileItem);
        }
    }

    return oMultipartParams;
}

From source file:com.orinus.script.safe.jetty.SRequest.java

public void parseMultipartContent() {
    if (formFields != null && formFiles != null && formFileData != null)
        return;/*from   ww  w .  j a v a  2s  .  c om*/
    formFields = new HashMap<String, String>();
    formFiles = new HashMap<String, FileEntry>();
    formFileData = new HashMap<String, String>();
    try {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        Controller controller = new Controller();
        factory.setRepository(new File(controller.getTempDir()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = upload.parseRequest(req);
        for (int i = 0; i < items.size(); i++) {
            FileItem item = (FileItem) items.get(i);
            if (item.isFormField()) {
                formFields.put(item.getFieldName(), item.getString());
            } else {
                FileEntry fe = new FileEntry();
                fe.fieldName = item.getFieldName();
                fe.contentType = item.getContentType();
                fe.filename = new File(item.getName()).getName();
                fe.fileSize = item.getSize();
                String filename = new File(controller.getTempDir(), fe.filename).getAbsolutePath();
                item.write(new File(filename));
                formFiles.put(fe.fieldName, fe);
                formFileData.put(fe.fieldName, filename);
            }
        }
    } catch (Exception e) {
    }
}

From source file:com.flaptor.clusterfest.deploy.DeployModule.java

@SuppressWarnings("unchecked")
public String doPage(String page, HttpServletRequest request, HttpServletResponse response) {
    List<NodeDescriptor> nodes = new ArrayList<NodeDescriptor>();
    String[] nodesParam = request.getParameterValues("node");
    if (nodesParam != null) {
        for (String idx : nodesParam) {
            nodes.add(ClusterManager.getInstance().getNodes().get(Integer.parseInt(idx)));
        }/* www  .ja va2s .co  m*/
    }
    request.setAttribute("nodes", nodes);

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

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

        String name = null;
        byte[] content = null;
        String path = null;
        // Parse the request
        try {
            List<FileItem> items = upload.parseRequest(request);
            String message = "";
            for (FileItem item : items) {
                String fieldName = item.getFieldName();
                if (fieldName.equals("node")) {
                    NodeDescriptor node = ClusterManager.getInstance().getNodes()
                            .get(Integer.parseInt(item.getString()));
                    if (!node.isReachable())
                        message += node + " is unreachable<br/>";
                    if (getModuleNode(node) != null)
                        nodes.add(node);
                    else
                        message += node + " is not registered as deployable<br/>";
                }
                if (fieldName.equals("path"))
                    path = item.getString();

                if (fieldName.equals("file")) {
                    name = item.getName();
                    content = IOUtil.readAllBinary(item.getInputStream());
                }
            }
            List<Pair<NodeDescriptor, Throwable>> errors = deployFiles(nodes, path, name, content);
            if (errors != null && errors.size() > 0) {
                request.setAttribute("deployCorrect", false);
                request.setAttribute("deployErrors", errors);
            } else
                request.setAttribute("deployCorrect", true);
            request.setAttribute("message", message);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return "deploy.vm";
}

From source file:com.aquest.emailmarketing.web.controllers.ImportController.java

/**
 * Import list.//www.  j  av  a2 s  . co  m
 *
 * @param model the model
 * @param request the request
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws FileNotFoundException the file not found exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws TransformerException the transformer exception
 * @throws ServletException the servlet exception
 * @throws FileUploadException the file upload exception
 */
@RequestMapping(value = "/importList", method = RequestMethod.POST)
public String ImportList(Model model, HttpServletRequest request) throws IOException, FileNotFoundException,
        ParserConfigurationException, TransformerException, ServletException, FileUploadException {
    List<String> copypaste = new ArrayList<String>();
    String listfilename = "";
    String separator = "";
    String broadcast_id = "";
    String old_broadcast_id = "";
    String listType = "";
    EmailListForm emailListForm = new EmailListForm();

    InputStream fileContent = null;

    List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
    for (FileItem item : items) {
        if (item.isFormField()) {
            // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
            String fieldName = item.getFieldName();
            String fieldValue = item.getString();
            if (fieldName.equals("listType")) {
                listType = fieldValue;
                System.out.println(listType);
            } else if (fieldName.equals("copypaste")) {
                for (String line : fieldValue.split("\\n")) {
                    copypaste.add(line);
                    System.out.println(line);
                }
            } else if (fieldName.equals("listfilename")) {
                listfilename = fieldValue;
            } else if (fieldName.equals("separator")) {
                separator = fieldValue;
            } else if (fieldName.equals("broadcast_id")) {
                broadcast_id = fieldValue;
            } else if (fieldName.equals("old_broadcast_id")) {
                old_broadcast_id = fieldValue;
            }
        } else {
            // Process form file field (input type="file").
            String fieldName = item.getFieldName();
            String fileName = FilenameUtils.getName(item.getName());
            fileContent = item.getInputStream();
        }
        System.out.println(listfilename);
        System.out.println(separator);
    }
    int importCount = 0;
    if (listType.equals("copy")) {
        if (!copypaste.isEmpty()) {
            List<EmailList> eList = emailListService.importEmailfromCopy(copypaste, broadcast_id);
            emailListForm.setEmailList(eList);
            importCount = eList.size();
        } else {
            // sta ako je prazno
        }
    }
    if (listType.equals("fromfile")) {
        List<EmailList> eList = emailListService.importEmailfromFile(fileContent, separator, broadcast_id);
        emailListForm.setEmailList(eList);
        importCount = eList.size();
    }

    System.out.println(broadcast_id);
    model.addAttribute("importCount", importCount);
    model.addAttribute("emailListForm", emailListForm);
    Broadcast broadcast = broadcastService.getBroadcast(broadcast_id);
    System.out.println("Old broadcast: " + old_broadcast_id);
    if (!old_broadcast_id.isEmpty()) {
        model.addAttribute("old_broadcast_id", old_broadcast_id);
    }
    String message = null;
    if (broadcast.getBcast_template_id() != null) {
        message = "template";
    }
    model.addAttribute("message", message);
    model.addAttribute("broadcast_id", broadcast_id);
    return "importlistreport";
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.Uploader.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w  ww .j a v  a  2s.  c o m
 * @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 {
    InputStream dafFileContent = null;
    String dafName = "";
    String dafType = "";

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    dafName = new File(item.getName()).getName();
                    dafFileContent = item.getInputStream();

                } else {

                    String fieldName = item.getFieldName();
                    String fieldValue = item.getString();

                    if (fieldName.equals("type")) {
                        dafType = fieldValue;
                    }

                    // String log = "att name: " + fieldname + " - value: " + fieldvalue;
                    // Logger.getLogger(Uploader.class.getName()).log(Level.INFO, log);

                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }

    if (!dafName.equals("")) {

        DafStore dafStore = new DafStore();
        dafStore.insertDAF(dafName, dafType, dafFileContent);
        Logger.getLogger(Uploader.class.getName()).log(Level.INFO, dafName);
    }

    response.sendRedirect("daf.jsp");
}

From source file:com.baobao121.baby.common.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 * /*from  w  w w. j  av  a  2  s . co m*/
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br>
 * <br>
 * It store the file (renaming it in case a file with the same name exists)
 * and then return an HTML file with a javascript command in it.
 * 
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (debug)
        System.out.println("--- BEGIN DOPOST ---");

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    if (debug)
        System.out.println(currentDirPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');
            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

    if (debug)
        System.out.println("--- END DOPOST ---");

}

From source file:gov.nih.nci.evs.browser.servlet.UploadServlet.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 *
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet exception occurs
 *///ww  w .  jav a2s .co m

public void execute(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    // Determine request by attributes
    String action = (String) request.getParameter("action");
    String type = (String) request.getParameter("type");

    System.out.println("(*) UploadServlet ...action " + action);
    if (action == null) {
        action = "upload_data";
    }

    DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
    /*
     *Set the size threshold, above which content will be stored on disk.
     */
    fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
    /*
     * Set the temporary directory to store the uploaded files of size above threshold.
     */
    //fileItemFactory.setRepository(tmpDir);

    ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
    try {
        /*
         * Parse the request
         */
        List items = uploadHandler.parseRequest(request);
        Iterator itr = items.iterator();
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            /*
             * Handle Form Fields.
             */
            if (item.isFormField()) {
                System.out.println("File Name = " + item.getFieldName() + ", Value = " + item.getString());
                //String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

            } else {
                //Handle Uploaded files.
                System.out.println("Field Name = " + item.getFieldName() + ", File Name = " + item.getName()
                        + ", Content type = " + item.getContentType() + ", File Size = " + item.getSize());

                String s = convertStreamToString(item.getInputStream(), item.getSize());
                //System.out.println(s);

                request.getSession().setAttribute("action", action);

                if (action.compareTo("upload_data") == 0) {
                    request.getSession().setAttribute("codes", s);
                } else {
                    Mapping mapping = new Mapping().toMapping(s);

                    System.out.println("Mapping " + mapping.getMappingName() + " uploaded.");
                    System.out.println("Mapping version: " + mapping.getMappingVersion());

                    MappingObject obj = mapping.toMappingObject();
                    HashMap mappings = (HashMap) request.getSession().getAttribute("mappings");
                    if (mappings == null) {
                        mappings = new HashMap();
                    }
                    mappings.put(obj.getKey(), obj);
                    request.getSession().setAttribute("mappings", mappings);
                }
            }
        }
    } catch (FileUploadException ex) {
        log("Error encountered while parsing the request", ex);
    } catch (Exception ex) {
        log("Error encountered while uploading file", ex);
    }

    //long ms = System.currentTimeMillis();

    if (action.compareTo("upload_data") == 0) {
        if (type.compareTo("codingscheme") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/codingscheme_data.jsf"));
        } else if (type.compareTo("ncimeta") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/ncimeta_data.jsf"));
        } else if (type.compareTo("valueset") == 0) {
            response.sendRedirect(
                    response.encodeRedirectURL(request.getContextPath() + "/pages/valueset_data.jsf"));
        }
    } else {
        response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/pages/home.jsf"));
    }

}

From source file:crds.pub.FCKeditor.connector.ConnectorServlet.java

/**
 * Manage the Post requests (FileUpload).<br>
 *
 * The servlet accepts commands sent in the following format:<br>
 * connector?Command=FileUpload&Type=ResourceType&CurrentFolder=FolderPath<br><br>
 * It store the file (renaming it in case a file with the same name exists) and then return an HTML file
 * with a javascript command in it./*  ww  w.  j  a v  a  2 s .  com*/
 *
 */
@SuppressWarnings({ "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FormUserOperation formUser = Constant.getFormUserOperation(request);
    String fck_task_id = (String) request.getSession().getAttribute("fck_task_id");
    if (fck_task_id == null) {
        fck_task_id = "temp_task_id";
    }

    response.setContentType("text/html; charset=UTF-8");
    response.setHeader("Cache-Control", "no-cache");
    PrintWriter out = response.getWriter();

    String commandStr = request.getParameter("Command");
    String typeStr = request.getParameter("Type");
    String currentFolderStr = request.getParameter("CurrentFolder");

    String currentPath = baseDir + formUser.getCompany_code() + currentFolderStr + fck_task_id
            + currentFolderStr + typeStr + currentFolderStr;
    String currentDirPath = getServletContext().getRealPath(currentPath);

    String retVal = "0";
    String newName = "";

    if (!commandStr.equals("FileUpload"))
        retVal = "203";
    else {
        DiskFileUpload upload = new DiskFileUpload();
        try {
            List items = upload.parseRequest(request);

            Map fields = new HashMap();

            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (item.isFormField())
                    fields.put(item.getFieldName(), item.getString());
                else
                    fields.put(item.getFieldName(), item);
            }
            FileItem uplFile = (FileItem) fields.get("NewFile");
            String fileNameLong = uplFile.getName();
            fileNameLong = fileNameLong.replace('\\', '/');

            String[] pathParts = fileNameLong.split("/");
            String fileName = pathParts[pathParts.length - 1];

            String nameWithoutExt = getNameWithoutExtension(fileName);
            String ext = getExtension(fileName);
            File pathToSave = new File(currentDirPath, fileName);
            int counter = 1;
            while (pathToSave.exists()) {
                newName = nameWithoutExt + "(" + counter + ")" + "." + ext;
                retVal = "201";
                pathToSave = new File(currentDirPath, newName);
                counter++;
            }
            uplFile.write(pathToSave);
        } catch (Exception ex) {
            retVal = "203";
        }

    }

    out.println("<script type=\"text/javascript\">");
    out.println("window.parent.frames['frmUpload'].OnUploadCompleted(" + retVal + ",'" + newName + "');");
    out.println("</script>");
    out.flush();
    out.close();

}