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:org.jbpm.console.ng.documents.backend.server.DocumentViewServlet.java

private void uploadFile(final FileItem uploadItem, String folder) throws IOException {
    InputStream fileData = uploadItem.getInputStream();
    // GAV gav = uploadItem.getGav();

    try {//from  w  ww.j  a  v a2s.  co  m
        // if ( gav == null ) {
        if (!fileData.markSupported()) {
            fileData = new BufferedInputStream(fileData);
        }

        // is available() safe?
        fileData.mark(fileData.available());

        byte[] bytes = IOUtils.toByteArray(fileData);
        DocumentSummary documenSummary = new DocumentSummary(uploadItem.getName(), "", folder);
        documenSummary.setContent(bytes);
        this.documentService.createDocument(documenSummary);
    } catch (Exception e) {

    }
}

From source file:org.jbpm.formbuilder.server.RESTFileService.java

protected byte[] readItem(FileItem item) throws IOException {
    return IOUtils.toByteArray(item.getInputStream());
}

From source file:org.jbpm.web.ProcessUploadServlet.java

private String handleRequest(HttpServletRequest request) {
    //check if request is multipart content
    log.debug("Handling upload request");
    if (!FileUpload.isMultipartContent(request)) {
        log.debug("Not a multipart request");
        return "Not a multipart request";
    }// www.java 2 s  . c  o  m

    try {
        DiskFileUpload fileUpload = new DiskFileUpload();
        List list = fileUpload.parseRequest(request);
        log.debug("Upload from GPD");
        Iterator iterator = list.iterator();
        if (!iterator.hasNext()) {
            log.debug("No process file in the request");
            return "No process file in the request";
        }
        FileItem fileItem = (FileItem) iterator.next();
        if (fileItem.getContentType().indexOf("application/x-zip-compressed") == -1) {
            log.debug("Not a process archive");
            return "Not a process archive";
        }
        try {
            log.debug("Deploying process archive " + fileItem.getName());
            ZipInputStream zipInputStream = new ZipInputStream(fileItem.getInputStream());
            JbpmContext jbpmContext = JbpmContext.getCurrentJbpmContext();
            log.debug("Preparing to parse process archive");
            ProcessDefinition processDefinition = ProcessDefinition.parseParZipInputStream(zipInputStream);
            log.debug("Created a processdefinition : " + processDefinition.getName());
            jbpmContext.deployProcessDefinition(processDefinition);
            zipInputStream.close();
            return "Deployed archive " + processDefinition.getName() + " successfully";
        } catch (IOException e) {
            log.debug("Failed to read process archive", e);
            return "IOException";
        }
    } catch (FileUploadException e) {
        log.debug("Failed to parse HTTP request", e);
        return "FileUploadException";
    }
}

From source file:org.jcommon.com.facebook.servlet.Uploader.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");

    String errormsg = null;//from  w  w  w. j av  a  2s .c  om
    List<FileItem> list = new ArrayList<FileItem>();
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItem item = null;
        try {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                item = it.next();
                if (!item.isFormField()) {
                    list.add(item);
                }
            }
        } catch (Throwable e) {
            logger.error("", e);
            errormsg = "transfer exception";
        }
    } else {
        errormsg = "not found multipart content";
        return;
    }
    if (errormsg != null) {
        error(response, errormsg);
        return;
    }
    for (FileItem item : list) {
        try {
            String file_name = item.getName();
            String file_id = org.jcommon.com.util.BufferUtils.generateRandom(20);
            String file_type = file_name.indexOf(".") != -1 ? file_name.substring(file_name.lastIndexOf("."))
                    : "";

            FileOutputStream out_file = null;
            java.io.File file = new java.io.File(upload_path);
            if (!file.exists())
                if (!file.mkdirs()) {
                    throw new Exception("file mkdir fail! -->" + file.getName());
                }
            String save_name = file_id + file_type;
            file = new java.io.File(upload_path, save_name);
            if (!file.exists())
                if (!file.createNewFile()) {
                    throw new Exception("file createNewFile fail! -->" + file.getName());
                }

            out_file = new FileOutputStream(file);
            InputStream is = item.getInputStream();
            logger.info("uploading...........");
            byte[] b = new byte[1024];
            int nRead;
            while ((nRead = is.read(b, 0, 1024)) > 0) {
                out_file.write(b, 0, nRead);
            }
            try {
                out_file.close();
                out_file.flush();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                file.delete();
                throw e1;
            }
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw e;
            }
            logger.info("done...............");
            String msg = "{\"id\":\"" + file_id + "\"}";
            logger.info(msg);
            response.getWriter().println(msg);
        } catch (Throwable e) {
            logger.error("", e);
            errormsg = "transfer exception";
        }
    }
    if (errormsg != null) {
        error(response, errormsg);
        return;
    }
}

From source file:org.jcommon.com.wechat.servlet.MediaServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");

    String errormsg = null;//from  w  w  w . j av  a  2 s  . com
    List<FileItem> list = new ArrayList<FileItem>();
    List<UrlObject> urls = new ArrayList<UrlObject>();
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItem item = null;
        try {
            ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);
            Iterator<FileItem> it = items.iterator();
            while (it.hasNext()) {
                item = it.next();
                if (!item.isFormField()) {
                    list.add(item);
                }
            }
        } catch (Throwable e) {
            logger.error("", e);
            errormsg = "transfer exception";
        }
    } else {
        errormsg = "not found multipart content";
    }
    if (errormsg != null) {
        error(response, errormsg);
        return;
    }
    for (FileItem item : list) {
        try {
            String file_name = item.getName();
            String file_id = org.jcommon.com.util.BufferUtils.generateRandom(20);
            String content_type = item.getContentType();

            Media media = new Media();
            media.setContent_type(content_type);
            media.setMedia_id(file_id);
            media.setMedia_name(file_name);

            FileOutputStream out_file = null;
            java.io.File file = MediaManager.getMedia_factory().createEmptyFile(media);
            media.setMedia(file);
            out_file = new FileOutputStream(file);
            InputStream is = item.getInputStream();
            logger.info("uploading...........");
            byte[] b = new byte[1024];
            int nRead;
            while ((nRead = is.read(b, 0, 1024)) > 0) {
                out_file.write(b, 0, nRead);
            }
            try {
                out_file.close();
                out_file.flush();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                file.delete();
                throw e1;
            }
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                throw e;
            }
            String url = MediaManager.getMedia_factory().createUrl(media).getUrl();
            logger.info(url);
            urls.add(new UrlObject(url));

        } catch (Throwable e) {
            logger.error("", e);
            errormsg = "transfer exception";
        }
    }
    if (errormsg != null) {
        error(response, errormsg);
        return;
    } else {
        String msg = "";
        if (urls.size() > 0) {
            if (urls.size() == 1)
                msg = urls.get(0).toJson();
            else
                msg = org.jcommon.com.util.JsonObject.list2Json(urls);
        }
        logger.info(msg);
        response.getWriter().println(msg);
    }
}

From source file:org.jcrportlet.jcr.JCRBrowser.java

public Node uploadItem(String folderName, FileItem file) {
    Node folderNode, fileNode;/*from   ww w  .  j a v a 2  s. co  m*/
    folderNode = this.createNode(folderName);
    try {
        try {
            fileNode = folderNode.getNode(file.getName());
            if (fileNode != null)
                return fileNode;
        } catch (PathNotFoundException e) {
            //            String mimeType = new MimetypesFileTypeMap().getContentType(file);
            String mimeType = file.getContentType();
            fileNode = folderNode.addNode(file.getName(), NT_FILE);
            Node resNode = fileNode.addNode(JCR_CONTENT, NT_RESOURCE);
            resNode.setProperty(JCR_MIMETYPE, mimeType);
            resNode.setProperty(JCR_ENCODING, "");
            try {
                resNode.setProperty(JCR_DATA, file.getInputStream());
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Calendar lastModified = Calendar.getInstance();
            //            lastModified.setTimeInMillis(file.lastModified());
            resNode.setProperty(JCR_LAST_MODIFIED, lastModified);
            fileNode.getSession().save();
            resNode.getSession().save();
            return fileNode;
        }
    } catch (RepositoryException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.jdesktop.wonderland.artupload.ArtUploadServlet.java

/**
 * Write files to the art directory/*www  .j a v a  2s. co  m*/
 * @param items the list of items containing the files to write
 * @throws ServletException if there is an error writing the files
 */
protected void writeFiles(List<FileItem> items) throws IOException, ServletException {
    // get the value of the "name" field
    FileItem nameItem = findItem(items, "name");
    String name = nameItem.getString();

    // write the model file
    FileItem modelItem = findItem(items, "model");
    File modelsDir = new File(Util.getArtDir(getServletContext()), "models");
    File modelFile = new File(modelsDir, name + ".j3s.gz");

    try {
        modelItem.write(modelFile);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

    // unzip the textures
    FileItem texturesItem = findItem(items, "textures");
    ZipInputStream zin = new ZipInputStream(texturesItem.getInputStream());

    ZipEntry entry;
    File curDir = new File(Util.getArtDir(getServletContext()), "textures");
    while ((entry = zin.getNextEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(curDir, entry.getName());
            dir.mkdirs();
        } else {
            // write the unzipped texture data
            File texture = new File(curDir, entry.getName());
            FileOutputStream out = new FileOutputStream(texture);

            byte[] buffer;
            if (entry.getSize() > -1) {
                buffer = new byte[(int) entry.getSize()];
            } else {
                buffer = new byte[64 * 1024];
            }

            int read = 0;
            while ((read = zin.read(buffer, 0, buffer.length)) > -1) {
                out.write(buffer, 0, read);
            }
            out.close();
        }
    }
}

From source file:org.jdesktop.wonderland.artupload.UploadServlet.java

/**
 * Write files to the specified directory
 * @param items the list of items containing the files to write
 * @throws IOException if there is an error writing the files
 * @throws ServletException if there is an error writing the files
 *//*from  w w w .j  av a  2s  . com*/
private void writeFiles(List<FileItem> items) throws IOException, ServletException {
    // get the value of the "name" field
    FileItem nameItem = findItem(items, "name");
    String name = nameItem.getString();

    // write the model file
    FileItem modelItem = findItem(items, "model");
    File modelsDir = new File(Util.getArtDir(getServletContext()), "models");
    File modelFile = new File(modelsDir, name + ".j3s.gz");

    try {
        modelItem.write(modelFile);
    } catch (Exception ex) {
        throw new ServletException(ex);
    }

    // unzip the textures
    FileItem texturesItem = findItem(items, "textures");
    ZipInputStream zin = new ZipInputStream(texturesItem.getInputStream());

    ZipEntry entry;
    File curDir = new File(Util.getArtDir(getServletContext()), "textures");
    while ((entry = zin.getNextEntry()) != null) {
        if (entry.isDirectory()) {
            File dir = new File(curDir, entry.getName());
            dir.mkdirs();
        } else {
            // write the unzipped texture data
            File texture = new File(curDir, entry.getName());
            FileOutputStream out = new FileOutputStream(texture);

            byte[] buffer;
            if (entry.getSize() > -1) {
                buffer = new byte[(int) entry.getSize()];
            } else {
                buffer = new byte[64 * 1024];
            }

            int read = 0;
            while ((read = zin.read(buffer, 0, buffer.length)) > -1) {
                out.write(buffer, 0, read);
            }
            out.close();
        }
    }
}

From source file:org.jspresso.framework.server.remote.RemotePeerRegistryServlet.java

/**
 * {@inheritDoc}//from w  w  w  .  j  a  v  a2s  .c  o  m
 */
@SuppressWarnings("unchecked")
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String id = request.getParameter(ID_PARAMETER);

    if (id == null) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No state id specified.");
        return;
    }

    IRemotePeerRegistry peerRegistry = (IRemotePeerRegistry) request.getSession().getAttribute(PEER_REGISTRY);
    try {
        HttpRequestHolder.setServletRequest(request);
        byte[] content;
        if ("application/x-www-form-urlencoded".equals(request.getContentType())) {
            String data = request.getParameter("data");
            content = Base64.decodeBase64(data);
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            OutputStream out = new BufferedOutputStream(baos);
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            if (items.size() > 0) {
                FileItem item = items.get(0);
                IoHelper.copyStream(item.getInputStream(), out);
            }
            out.flush();
            out.close();
            content = baos.toByteArray();
        }

        if (content != null && content.length == 0) {
            content = null;
        }

        IRemoteStateOwner stateOwner = (IRemoteStateOwner) peerRegistry.getRegistered(id);
        stateOwner.setValueFromState(content);

    } catch (Exception ex) {
        if (peerRegistry instanceof IExceptionHandler) {
            ((IExceptionHandler) peerRegistry).handleException(ex, Collections.<String, Object>emptyMap());
        } else {
            LOG.error("An unexpected error occurred while uploading the content.", ex);
        }
    } finally {
        HttpRequestHolder.setServletRequest(null);
    }
}

From source file:org.komodo.web.backend.server.servlets.DataVirtUploadServlet.java

/**
 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *//*from   ww  w  .  j  a va 2s.  co  m*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse response)
        throws ServletException, IOException {
    // Extract the relevant content from the POST'd form
    if (ServletFileUpload.isMultipartContent(req)) {
        Map<String, String> responseMap;
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        // Parse the request
        String deploymentName = null;
        String fileName = null;
        InputStream fileContent = null;
        try {
            List<FileItem> items = upload.parseRequest(req);
            boolean isDriver = false;
            for (FileItem item : items) {
                // Deployment name for drivers
                if (item.isFormField()) {
                    if (item.getFieldName().equals("driverDeploymentName")) {
                        deploymentName = item.getString();
                        isDriver = true;
                    }
                    // File Content
                } else {
                    fileName = item.getName();
                    if (fileName != null)
                        fileName = FilenameUtils.getName(fileName);
                    fileContent = item.getInputStream();
                }
            }

            // Now that the content has been extracted, upload
            if (isDriver) {
                responseMap = uploadDriver(deploymentName, fileContent);
            } else {
                responseMap = uploadVdb(fileName, fileContent);
            }
        } catch (Throwable e) {
            responseMap = new HashMap<String, String>();
            responseMap.put("exception", "true"); //$NON-NLS-1$ //$NON-NLS-2$
            responseMap.put("exception-message", e.getMessage()); //$NON-NLS-1$
            //            responseMap.put("exception-stack", ExceptionUtils.getRootStackTrace(e)); //$NON-NLS-1$
        } finally {
            IOUtils.closeQuietly(fileContent);
        }
        writeToResponse(responseMap, response);
    } else {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Content type not supported"); //$NON-NLS-1$
    }
}