Example usage for org.apache.commons.fileupload FileItemStream getName

List of usage examples for org.apache.commons.fileupload FileItemStream getName

Introduction

In this page you can find the example usage for org.apache.commons.fileupload FileItemStream getName.

Prototype

String getName();

Source Link

Document

Returns the original filename in the client's filesystem, as provided by the browser (or other client software).

Usage

From source file:org.jahia.tools.files.FileUpload.java

/**
 * Init the MultiPartReq object if it's actually null
 *
 * @exception IOException//from   w  w  w  . j  av  a 2s .  co  m
 */
protected void init() throws IOException {

    params = new HashMap<String, List<String>>();
    paramsContentType = new HashMap<String, String>();
    files = new HashMap<String, DiskFileItem>();
    filesByFieldName = new HashMap<String, DiskFileItem>();

    parseQueryString();

    if (checkSavePath(savePath)) {
        try {
            final ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(req);
            DiskFileItemFactory factory = null;
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    final String name = item.getFieldName();
                    final List<String> v;
                    if (params.containsKey(name)) {
                        v = params.get(name);
                    } else {
                        v = new ArrayList<String>();
                        params.put(name, v);
                    }
                    v.add(Streams.asString(stream, encoding));
                    paramsContentType.put(name, item.getContentType());
                } else {
                    if (factory == null) {
                        factory = new DiskFileItemFactory();
                        factory.setSizeThreshold(1);
                        factory.setRepository(new File(savePath));
                    }
                    DiskFileItem fileItem = (DiskFileItem) factory.createItem(item.getFieldName(),
                            item.getContentType(), item.isFormField(), item.getName());
                    try {
                        Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
                    } catch (FileUploadIOException e) {
                        throw (FileUploadException) e.getCause();
                    } catch (IOException e) {
                        throw new IOFileUploadException("Processing of " + FileUploadBase.MULTIPART_FORM_DATA
                                + " request failed. " + e.getMessage(), e);
                    }
                    final FileItemHeaders fih = item.getHeaders();
                    fileItem.setHeaders(fih);
                    if (fileItem.getSize() > 0) {
                        files.put(fileItem.getStoreLocation().getName(), fileItem);
                        filesByFieldName.put(fileItem.getFieldName(), fileItem);
                    }
                }
            }
        } catch (FileUploadException ioe) {
            logger.error("Error while initializing FileUpload class:", ioe);
            throw new IOException(ioe.getMessage());
        }
    } else {
        logger.error("FileUpload::init storage path does not exists or can write");
        throw new IOException("FileUpload::init storage path does not exists or cannot write");
    }
}

From source file:org.jasig.portal.utils.web.FileUploadLogger.java

public static void logFileUploadInfo(HttpServletRequest request) {
    final boolean multipartContent = ServletFileUpload.isMultipartContent(request);
    System.out.println("multipartContent=" + multipartContent);
    if (!multipartContent) {
        return;// w ww.  j  av  a 2s  .co m
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
    final ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

    try {
        final FileItemIterator itemIterator = servletFileUpload.getItemIterator(request);
        while (itemIterator.hasNext()) {
            final FileItemStream next = itemIterator.next();
            System.out.println("FileItemStream: " + next.getName());
            System.out.println("\t" + next.getContentType());
            System.out.println("\t" + next.getFieldName());

            final FileItemHeaders headers = next.getHeaders();
            if (headers != null) {
                System.out.println(
                        "\t" + Arrays.toString(Iterators.toArray(headers.getHeaderNames(), String.class)));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.jbpm.designer.web.server.menu.connector.AbstractConnectorServlet.java

/**
 * Parse request parameters and files.// w  ww  . j a va 2  s. c o m
 * @param request
 * @param response
 */
protected void parseRequest(HttpServletRequest request, HttpServletResponse response) {
    requestParams = new HashMap<String, Object>();
    listFiles = new ArrayList<FileItemStream>();
    listFileStreams = new ArrayList<ByteArrayOutputStream>();

    // Parse the request
    if (ServletFileUpload.isMultipartContent(request)) {
        // multipart request
        try {
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    requestParams.put(name, Streams.asString(stream));
                } else {
                    String fileName = item.getName();
                    if (fileName != null && !"".equals(fileName.trim())) {
                        listFiles.add(item);

                        ByteArrayOutputStream os = new ByteArrayOutputStream();
                        IOUtils.copy(stream, os);
                        listFileStreams.add(os);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Unexpected error parsing multipart content", e);
        }
    } else {
        // not a multipart
        for (Object mapKey : request.getParameterMap().keySet()) {
            String mapKeyString = (String) mapKey;

            if (mapKeyString.endsWith("[]")) {
                // multiple values
                String values[] = request.getParameterValues(mapKeyString);
                List<String> listeValues = new ArrayList<String>();
                for (String value : values) {
                    listeValues.add(value);
                }
                requestParams.put(mapKeyString, listeValues);
            } else {
                // single value
                String value = request.getParameter(mapKeyString);
                requestParams.put(mapKeyString, value);
            }
        }
    }
}

From source file:org.jbpm.designer.web.server.menu.connector.commands.AbstractCommand.java

public JSONObject uploadFiles(IDiagramProfile profile, String current, List<FileItemStream> listFiles,
        List<ByteArrayOutputStream> listFileStreams, boolean tree) throws Exception {
    if (current == null || current.length() < 1) {
        current = "/";
    } else if (!current.startsWith("/")) {
        current = "/" + current;
    }/* w  ww  .j a v a2s.  c o  m*/
    if (current.startsWith("//")) {
        current = current.substring(1, current.length());
    }

    if (profile.getRepository().directoryExists(current)) {
        try {
            int i = 0;
            for (FileItemStream uplFile : listFiles) {
                String fileName = uplFile.getName();
                String fileContentType = uplFile.getContentType();

                ByteArrayOutputStream os = listFileStreams.get(i);
                checkUploadFile(fileName, os);
                checkAlreadyExists(profile, fileName, current);

                String[] fileParts = fileName.split("\\.");
                String fileType = fileParts[fileParts.length - 1];
                String fileNameOnly = fileName.substring(0, fileName.length() - (fileType.length() + 1));

                AssetBuilder assetBuilder = AssetBuilderFactory.getAssetBuilder(Asset.AssetType.Byte);
                assetBuilder.content(os.toByteArray()).location(current).name(fileNameOnly).type(fileType)
                        .version("1.0");
                Asset newAsset = assetBuilder.getAsset();
                profile.getRepository().createAsset(newAsset);
                i++;
            }
        } catch (Exception e) {
            logger.error("Unable to upload file: " + e.getMessage());
        }
    } else {
        logger.error("Directory does not exist: " + current);
    }

    JSONObject retObj = new JSONObject();
    retObj.put("cwd", getCwd(profile, current, tree));
    retObj.put("cdc", getCdc(profile, current, tree));
    retObj.put("tree", getTree(profile, current, tree));
    retObj.put("select", current);
    addParams(retObj);
    return retObj;
}

From source file:org.jdesktop.wonderland.modules.contentrepo.web.servlet.BrowserServlet.java

protected ContentNode handleUpload(HttpServletRequest request, HttpServletResponse response, ContentNode node,
        String action) throws ServletException, IOException, ContentRepositoryException {
    if (!(node instanceof ContentCollection)) {
        error(request, response, "Not a directory");
        return null;
    }// ww w  . j a va  2 s. co  m

    ContentCollection dir = (ContentCollection) node;

    /* Check that we have a file upload request */
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart == false) {
        logger.warning("[Runner] UPLOAD Bad request");
        String message = "Unable to recognize upload request. Please " + "try again.";
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, message);
        return null;
    }

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

    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext() == true) {
            FileItemStream item = iter.next();
            String name = item.getName();
            InputStream stream = item.openStream();
            if (item.isFormField() == false) {
                ContentResource child = (ContentResource) dir.createChild(name, ContentNode.Type.RESOURCE);

                File tmp = File.createTempFile("contentupload", "tmp");
                RunUtil.writeToFile(stream, tmp);
                child.put(tmp);
                tmp.delete();
            }
        }

        return node;
    } catch (FileUploadException excp) {
        /* Log an error to the log and write an error message back */
        logger.log(Level.WARNING, "[Runner] UPLOAD Failed", excp);
        String message = "Unable to upload runner for some reason.";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return null;
    } catch (IOException excp) {
        /* Log an error to the log and write an error message back */
        logger.log(Level.WARNING, "[Runner] UPLOAD Failed", excp);
        String message = "Unable to upload runner for some reason.";
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message);
        return null;
    }
}

From source file:org.jdesktop.wonderland.modules.servlets.ModuleUploadServlet.java

/** 
* Handles the HTTP <code>POST</code> method.
* @param request servlet request//from  w  ww .  j  a  v a  2s. c o  m
* @param response servlet response
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    /*
     * Create a factory for disk-base file items to handle the request. Also
     * place the file in add/.
     */
    String redirect = "/installFailed.jsp";
    ModuleManager manager = ModuleManager.getModuleManager();

    /* Check that we have a file upload request */
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart == false) {
        LOGGER.warning("Failed to upload module, isMultipart=false");
        String msg = "Unable to recognize upload request. Please try again.";
        request.setAttribute("errorMessage", msg);
        RequestDispatcher rd = request.getRequestDispatcher(redirect);
        rd.forward(request, response);
        return;
    }

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

    // Parse the request
    try {
        FileItemIterator iter = upload.getItemIterator(request);
        while (iter.hasNext() == true) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            if (item.isFormField() == false) {
                /*
                 * The name given should have a .jar extension. Check this here. If
                 * not, return an error. If so, parse out just the module name.
                 */
                String moduleJar = item.getName();
                if (moduleJar.endsWith(".jar") == false) {
                    /* Log an error to the log and write an error message back */
                    LOGGER.warning("Upload is not a jar file " + moduleJar);
                    String msg = "The file " + moduleJar + " needs to be" + " a jar file. Please try again.";
                    request.setAttribute("errorMessage", msg);
                    RequestDispatcher rd = request.getRequestDispatcher(redirect);
                    rd.forward(request, response);
                    return;
                }
                String moduleName = moduleJar.substring(0, moduleJar.length() - 4);

                LOGGER.info("Upload Install module " + moduleName + " with file name " + moduleJar);

                /*
                 * Write the file a temporary file
                 */
                File tmpFile = null;
                try {
                    tmpFile = File.createTempFile(moduleName + "_tmp", ".jar");
                    tmpFile.deleteOnExit();
                    RunUtil.writeToFile(stream, tmpFile);
                } catch (java.lang.Exception excp) {
                    /* Log an error to the log and write an error message back */
                    LOGGER.log(Level.WARNING, "Failed to save file", excp);
                    String msg = "Internal error installing the module.";
                    request.setAttribute("errorMessage", msg);
                    RequestDispatcher rd = request.getRequestDispatcher(redirect);
                    rd.forward(request, response);
                    return;
                }

                /* Add the new module */
                Collection<File> moduleFiles = new LinkedList<File>();
                moduleFiles.add(tmpFile);
                Collection<Module> result = manager.addToInstall(moduleFiles);
                if (result.isEmpty() == true) {
                    /* Log an error to the log and write an error message back */
                    LOGGER.warning("Failed to install module " + moduleName);
                    String msg = "Internal error installing the module.";
                    request.setAttribute("errorMessage", msg);
                    RequestDispatcher rd = request.getRequestDispatcher(redirect);
                    rd.forward(request, response);
                    return;
                }
            }
        }
    } catch (FileUploadException excp) {
        /* Log an error to the log and write an error message back */
        LOGGER.log(Level.WARNING, "File upload failed", excp);
        String msg = "Failed to upload the file. Please try again.";
        request.setAttribute("errorMessage", msg);
        RequestDispatcher rd = request.getRequestDispatcher(redirect);
        rd.forward(request, response);
        return;
    }

    /* Install all of the modules that are possible */
    manager.installAll();

    /* If we have reached here, then post a simple message */
    LOGGER.info("Added module successfully");
    RequestDispatcher rd = request.getRequestDispatcher("/installSuccess.jsp");
    rd.forward(request, response);
}

From source file:org.jlibrary.web.servlet.JLibraryForwardServlet.java

private void upload(HttpServletRequest req, HttpServletResponse resp) {

    ServletFileUpload upload = new ServletFileUpload();
    boolean sizeExceeded = false;
    String repositoryName = req.getParameter("repository");
    ConfigurationService conf = (ConfigurationService) context.getBean("template");
    upload.setSizeMax(conf.getOperationInputBandwidth());

    try {/*  w ww . ja  v a  2s .c o  m*/
        params = new HashMap();
        FileItemIterator iter = upload.getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(stream));
            } else {
                params.put("filename", item.getName());
                uploadDocumentStructure(req, resp, repositoryName, stream);
            }
        }
    } catch (SizeLimitExceededException e) {
        sizeExceeded = true;
        if (repositoryName == null || "".equals(repositoryName)) {
            repositoryName = (String) params.get("repository");
        }
        logErrorAndForward(req, resp, repositoryName, e, "Bandwith exceeded");
    } catch (FileUploadException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document.");
    } catch (IOException e) {
        logErrorAndForward(req, resp, repositoryName, e, "There was a problem uploading the document.");
    } catch (Exception t) {
        logErrorAndForward(req, resp, repositoryName, t, "There was a problem uploading the document.");
    }

}

From source file:org.jolokia.osgish.upload.UploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!ServletFileUpload.isMultipartContent(request)) {
        throw new ServletException("Request has no multipart content");
    }//from  ww  w . ja v  a 2  s .com
    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter;
    try {
        iter = upload.getItemIterator(request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            InputStream in = item.openStream();
            if (item.isFormField()) {
                throw new ServletException("A Form field is not expected here");
            } else {
                File dest = new File(uploadDirectory, item.getName());
                try {
                    OutputStream out = new FileOutputStream(dest);
                    copy(in, out);
                    LogService log = (LogService) logTracker.getService();
                    if (log != null) {
                        log.log(LogService.LOG_INFO,
                                "Uploaded " + dest.getName() + " (size: " + dest.length() + ")");
                    }
                    // TODO: Return internal location/url of this bundle
                } catch (IOException exp) {
                    throw new ServletException(
                            "Cannot copy uploaded file to " + dest.getAbsolutePath() + ": " + exp, exp);
                }
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Upload failed: " + e, e);
    }
    response.setStatus(HttpServletResponse.SC_OK);
}

From source file:org.jumpmind.symmetric.web.FileSyncPushUriHandler.java

public void handle(HttpServletRequest req, HttpServletResponse res)
        throws IOException, ServletException, FileUploadException {
    String nodeId = ServletUtils.getParameter(req, WebConstants.NODE_ID);

    if (StringUtils.isBlank(nodeId)) {
        ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "Node must be specified");
        return;//  w w  w .  java 2  s.c om
    } else if (!ServletFileUpload.isMultipartContent(req)) {
        ServletUtils.sendError(res, HttpServletResponse.SC_BAD_REQUEST, "We only handle multipart requests");
        return;
    } else {
        log.debug("File sync push request received from {}", nodeId);
    }

    ServletFileUpload upload = new ServletFileUpload();

    // Parse the request
    FileItemIterator iter = upload.getItemIterator(req);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String name = item.getFieldName();
        if (!item.isFormField()) {
            log.debug("Processing upload file field " + name + " with file name " + item.getName()
                    + " detected.");
            engine.getFileSyncService().loadFilesFromPush(nodeId, item.openStream(), res.getOutputStream());

        }
    }

    res.flushBuffer();

}

From source file:org.jwifisd.eyefi.Main3.java

public static void main(String[] args) throws Exception {
    MultipartStream stream = new MultipartStream(
            new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430"),
            "---------------------------02468ace13579bdfcafebabef00d".getBytes());
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String readHeaders = stream.readHeaders();
    System.out.println(readHeaders.toString());
    stream.readBodyData(output);/*w  w  w.java2s.c  o m*/
    output = new ByteArrayOutputStream();
    readHeaders = stream.readHeaders();
    System.out.println(readHeaders.toString());
    stream.readBodyData(output);

    final InputStream in = new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430");

    FileItemIterator iter = new FileUpload().getItemIterator(new RequestContext() {

        @Override
        public InputStream getInputStream() throws IOException {
            return in;
        }

        @Override
        public String getContentType() {
            // TODO Auto-generated method stub
            return "multipart/form-data; boundary=---------------------------02468ace13579bdfcafebabef00d";
        }

        @Override
        public int getContentLength() {
            return 4237763;
        }

        @Override
        public String getCharacterEncoding() {
            // TODO Auto-generated method stub
            return "UTF-8";
        }
    });

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

        System.out.println("name:" + item.getName());
        System.out.println("name:" + item.getContentType());
        //item.openStream();

    }
}