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

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

Introduction

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

Prototype

InputStream openStream() throws IOException;

Source Link

Document

Creates an InputStream , which allows to read the items contents.

Usage

From source file:org.geowe.server.upload.FileUploadZipServlet.java

private ZipFile createZipFile(FileItemStream item) {
    ZipFile zipFile = null;//from w w  w. ja v a 2 s  .  c  o  m
    try {
        File f = new File("zipFile");
        InputStream inputStream = item.openStream();
        OutputStream outputStream = new FileOutputStream(f);
        int len;
        byte[] buffer = new byte[1000000];
        while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();

        zipFile = new ZipFile(f);

    } catch (Exception e) {
        LOG.error(e.getMessage());
    }

    return zipFile;
}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * A method for handling multipart POST requests for uploading
 * files from browser-based JavaScript clients.
 *
 * @param request the HTTP request/*w  w  w .  jav a2  s. com*/
 * @param response the HTTP response
 * @param path the resource path
 * @throws IOException in case an error occurs writing to the
 *       response stream
 */
private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Multipart POST for resource: " + path);

    User owner = getOwner(request);
    boolean exists = true;
    Object resource = null;
    FileHeader file = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader) {
            file = (FileHeader) resource;
            if (file.isDeleted()) {
                response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }

    Object parent;
    String parentPath = null;
    try {
        parentPath = getParentPath(path);
        parent = getService().getResourceAtPath(owner.getId(), parentPath, true);
    } catch (ObjectNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath);
        return;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    if (!(parent instanceof Folder)) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }
    final Folder folderLocal = (Folder) parent;
    final String fileName = getLastElement(path);

    if (!isValidResourceName(fileName)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    FileItemIterator iter;
    File uploadedFile = null;
    try {
        // Create a new file upload handler.
        ServletFileUpload upload = new ServletFileUpload();
        StatusProgressListener progressListener = new StatusProgressListener(getService());
        upload.setProgressListener(progressListener);
        iter = upload.getItemIterator(request);
        String dateParam = null;
        String auth = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                final String value = Streams.asString(stream);
                if (name.equals(DATE_PARAMETER))
                    dateParam = value;
                else if (name.equals(AUTHORIZATION_PARAMETER))
                    auth = value;

                if (logger.isDebugEnabled())
                    logger.debug(name + ":" + value);
            } else {
                // Fetch the timestamp used to guard against replay attacks.
                if (dateParam == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter");
                    return;
                }

                long timestamp;
                try {
                    timestamp = DateUtil.parseDate(dateParam).getTime();
                } catch (DateParseException e) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
                    return;
                }

                // Fetch the Authorization parameter and find the user specified in it.
                if (auth == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter");
                    return;
                }
                String[] authParts = auth.split(" ");
                if (authParts.length != 2) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                String username = authParts[0];
                String signature = authParts[1];
                User user = null;
                try {
                    user = getService().findUser(username);
                } catch (RpcException e) {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }
                if (user == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                request.setAttribute(USER_ATTRIBUTE, user);

                // Remove the servlet path from the request URI.
                String p = request.getRequestURI();
                String servletPath = request.getContextPath() + request.getServletPath();
                p = p.substring(servletPath.length());
                // Validate the signature in the Authorization parameter.
                String data = request.getMethod() + dateParam + p;
                if (!isSignatureValid(signature, user, data)) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }

                progressListener.setUserId(user.getId());
                progressListener.setFilename(fileName);
                final String contentType = item.getContentType();

                try {
                    uploadedFile = getService().uploadFile(stream, user.getId());
                } catch (IOException ex) {
                    throw new GSSIOException(ex, false);
                }
                FileHeader fileLocal = null;
                final File upf = uploadedFile;
                final FileHeader f = file;
                final User u = user;
                if (file == null)
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().createFile(u.getId(), folderLocal.getId(), fileName,
                                    contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                else
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().updateFileContents(u.getId(), f.getId(), contentType,
                                    upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize());
                getService().removeFileUploadProgress(user.getId(), fileName);
            }
        }
        // We can't return 204 here since GWT's onSubmitComplete won't fire.
        response.setContentType("text/html");
        response.getWriter().print("<pre></pre>");
    } catch (FileUploadException e) {
        String error = "Error while uploading file";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (GSSIOException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Error while uploading file";
        if (e.logAsError())
            logger.error(error, e);
        else
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (DuplicateNameException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "The specified file name already exists in this folder";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_CONFLICT, error);

    } catch (InsufficientPermissionsException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "You don't have the necessary permissions";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error);

    } catch (QuotaExceededException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Not enough free space available";
        if (logger.isDebugEnabled())
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error);

    } catch (ObjectNotFoundException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "A specified object was not found";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, error);
    } catch (RpcException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An error occurred while communicating with the service";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (Exception e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An internal server error occurred";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    }
}

From source file:org.intermine.webservice.server.lists.ListUploadService.java

/**
 * Get the reader for the identifiers uploaded with this request.
 * @param request The request object./*  w w  w .j  av  a2 s  .  co  m*/
 * @return A buffered reader for reading the identifiers.
 */
protected BufferedReader getReader(final HttpServletRequest request) {
    BufferedReader r = null;

    if (ServletFileUpload.isMultipartContent(request)) {
        final ServletFileUpload upload = new ServletFileUpload();
        try {
            final FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                final FileItemStream item = iter.next();
                final String fieldName = item.getFieldName();
                if (!item.isFormField() && "identifiers".equalsIgnoreCase(fieldName)) {
                    final InputStream stream = item.openStream();
                    final InputStreamReader in = new InputStreamReader(stream);
                    r = new BufferedReader(in);
                    break;
                }
            }
        } catch (FileUploadException e) {
            throw new InternalErrorException("Could not read request body", e);
        } catch (IOException e) {
            throw new InternalErrorException(e);
        }
    } else {
        if (!requestIsOfSuitableType()) {
            throw new BadRequestException("Bad content type - " + request.getContentType() + USAGE);
        }
        try {
            r = request.getReader();
        } catch (IOException e) {
            throw new InternalErrorException(e);
        }
    }
    if (r == null) {
        throw new BadRequestException("No identifiers found in request." + USAGE);
    }
    return r;
}

From source file:org.jahia.ajax.gwt.content.server.GWTFileManagerUploadServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);
    SettingsBean settingsBean = SettingsBean.getInstance();
    final long fileSizeLimit = settingsBean.getJahiaFileUploadMaxSize();
    upload.setHeaderEncoding("UTF-8");
    Map<String, FileItem> uploads = new HashMap<String, FileItem>();
    String location = null;/*  w  w  w  .  j  a  v  a2s .c o m*/
    String type = null;
    boolean unzip = false;
    response.setContentType("text/plain; charset=" + settingsBean.getCharacterEncoding());
    final PrintWriter printWriter = response.getWriter();
    try {
        FileItemIterator itemIterator = upload.getItemIterator(request);
        FileSizeLimitExceededException sizeLimitExceededException = null;
        while (itemIterator.hasNext()) {
            final FileItemStream item = itemIterator.next();
            if (sizeLimitExceededException != null) {
                continue;
            }
            FileItem fileItem = factory.createItem(item.getFieldName(), item.getContentType(),
                    item.isFormField(), item.getName());
            long contentLength = getContentLength(item.getHeaders());

            // If we have a content length in the header we can use it
            if (fileSizeLimit > 0 && contentLength != -1L && contentLength > fileSizeLimit) {
                throw new FileSizeLimitExceededException("The field " + item.getFieldName()
                        + " exceeds its maximum permitted size of " + fileSizeLimit + " bytes.", contentLength,
                        fileSizeLimit);
            }
            InputStream itemStream = item.openStream();

            InputStream limitedInputStream = null;
            try {
                limitedInputStream = fileSizeLimit > 0 ? new LimitedInputStream(itemStream, fileSizeLimit) {

                    @Override
                    protected void raiseError(long pSizeMax, long pCount) throws IOException {
                        throw new FileUploadIOException(new FileSizeLimitExceededException(
                                "The field " + item.getFieldName() + " exceeds its maximum permitted size of "
                                        + fileSizeLimit + " bytes.",
                                pCount, pSizeMax));
                    }
                } : itemStream;

                Streams.copy(limitedInputStream, fileItem.getOutputStream(), true);
            } catch (FileUploadIOException e) {
                if (e.getCause() instanceof FileSizeLimitExceededException) {
                    if (sizeLimitExceededException == null) {
                        sizeLimitExceededException = (FileSizeLimitExceededException) e.getCause();
                    }
                } else {
                    throw e;
                }
            } finally {
                IOUtils.closeQuietly(limitedInputStream);
            }

            if ("unzip".equals(fileItem.getFieldName())) {
                unzip = true;
            } else if ("uploadLocation".equals(fileItem.getFieldName())) {
                location = fileItem.getString("UTF-8");
            } else if ("asyncupload".equals(fileItem.getFieldName())) {
                String name = fileItem.getName();
                if (name.trim().length() > 0) {
                    uploads.put(extractFileName(name, uploads), fileItem);
                }
                type = "async";
            } else if (!fileItem.isFormField() && fileItem.getFieldName().startsWith("uploadedFile")) {
                String name = fileItem.getName();
                if (name.trim().length() > 0) {
                    uploads.put(extractFileName(name, uploads), fileItem);
                }
                type = "sync";
            }
        }
        if (sizeLimitExceededException != null) {
            throw sizeLimitExceededException;
        }
    } catch (FileUploadBase.FileSizeLimitExceededException e) {
        printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit, e, request) + "\n");
        return;
    } catch (FileUploadIOException e) {
        if (e.getCause() != null && (e.getCause() instanceof FileSizeLimitExceededException)) {
            printWriter.write("UPLOAD-SIZE-ISSUE: " + getSizeLimitErrorMessage(fileSizeLimit,
                    (FileSizeLimitExceededException) e.getCause(), request) + "\n");
        } else {
            logger.error("UPLOAD-ISSUE", e);
            printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
        }
        return;
    } catch (FileUploadException e) {
        logger.error("UPLOAD-ISSUE", e);
        printWriter.write("UPLOAD-ISSUE: " + e.getLocalizedMessage() + "\n");
        return;
    }

    if (type == null || type.equals("sync")) {
        response.setContentType("text/plain");

        final JahiaUser user = (JahiaUser) request.getSession().getAttribute(Constants.SESSION_USER);

        final List<String> pathsToUnzip = new ArrayList<String>();
        for (String fileName : uploads.keySet()) {
            final FileItem fileItem = uploads.get(fileName);
            try {
                StringBuilder name = new StringBuilder(fileName);
                final int saveResult = saveToJcr(user, fileItem, location, name);
                switch (saveResult) {
                case OK:
                    if (unzip && fileName.toLowerCase().endsWith(".zip")) {
                        pathsToUnzip.add(
                                new StringBuilder(location).append("/").append(name.toString()).toString());
                    }
                    printWriter.write("OK: " + UriUtils.encode(name.toString()) + "\n");
                    break;
                case EXISTS:
                    storeUploadedFile(request.getSession().getId(), fileItem);
                    printWriter.write("EXISTS: " + UriUtils.encode(fileItem.getFieldName()) + " "
                            + UriUtils.encode(fileItem.getName()) + " " + UriUtils.encode(fileName) + "\n");
                    break;
                case READONLY:
                    printWriter.write("READONLY: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                    break;
                default:
                    printWriter.write("UPLOAD-FAILED: " + UriUtils.encode(fileItem.getFieldName()) + "\n");
                    break;
                }
            } catch (IOException e) {
                logger.error("Upload failed for file \n", e);
            } finally {
                fileItem.delete();
            }
        }

        // direct blocking unzip
        if (unzip && pathsToUnzip.size() > 0) {
            try {
                ZipHelper zip = ZipHelper.getInstance();
                //todo : in which workspace do we upload ?
                zip.unzip(pathsToUnzip, true, JCRSessionFactory.getInstance().getCurrentUserSession(),
                        (Locale) request.getSession().getAttribute(Constants.SESSION_UI_LOCALE));
            } catch (RepositoryException e) {
                logger.error("Auto-unzipping failed", e);
            } catch (GWTJahiaServiceException e) {
                logger.error("Auto-unzipping failed", e);
            }
        }
    } else {
        response.setContentType("text/html");
        for (FileItem fileItem : uploads.values()) {
            storeUploadedFile(request.getSession().getId(), fileItem);
            printWriter.write("<html><body>");
            printWriter.write("<div id=\"uploaded\" key=\"" + fileItem.getName() + "\" name=\""
                    + fileItem.getName() + "\"></div>\n");
            printWriter.write("</body></html>");
        }
    }
}

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

/**
 * Init the MultiPartReq object if it's actually null
 *
 * @exception IOException/*from   w ww  .  ja va2s. c om*/
 */
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.jbpm.designer.server.StencilSetExtensionGeneratorServlet.java

/**
 * Request parameters are documented in/*from www  . ja  va  2s . co  m*/
 * editor/test/examples/stencilset-extension-generator.xhtml
 * The parameter 'csvFile' is always required.
 * An example CSV file can be found in
 * editor/test/examples/design-thinking-example-data.csv
 * which has been exported using OpenOffice.org from
 * editor/test/examples/design-thinking-example-data.ods
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
    this.request = request;
    this.response = response;
    this.baseUrl = Repository.getBaseUrl(request);
    this.repository = new Repository(baseUrl);

    // parameters and their default values
    String modelNamePrefix = "Generated Model using ";
    String stencilSetExtensionNamePrefix = StencilSetExtensionGenerator.DEFAULT_STENCIL_SET_EXTENSION_NAME_PREFIX;
    String baseStencilSetPath = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET_PATH;
    String baseStencilSet = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL_SET;
    String baseStencil = StencilSetExtensionGenerator.DEFAULT_BASE_STENCIL;
    List<String> stencilSetExtensionUrls = new ArrayList<String>();
    String[] columnPropertyMapping = null;
    String[] csvHeader = null;
    List<Map<String, String>> stencilPropertyMatrix = new ArrayList<Map<String, String>>();
    String modelDescription = "The initial version of this model has been created by the Stencilset Extension Generator.";
    String additionalERDFContentForGeneratedModel = "";
    String[] modelTags = null;

    // Check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {

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

        // Parse the request
        FileItemIterator iterator;
        try {
            iterator = upload.getItemIterator(request);
            while (iterator.hasNext()) {
                FileItemStream item = iterator.next();
                String name = item.getFieldName();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // ordinary form field
                    String value = Streams.asString(stream);
                    //System.out.println("Form field " + name + " with value "
                    //    + value + " detected.");
                    if (name.equals("modelNamePrefix")) {
                        modelNamePrefix = value;
                    } else if (name.equals("stencilSetExtensionNamePrefix")) {
                        stencilSetExtensionNamePrefix = value;
                    } else if (name.equals("baseStencilSetPath")) {
                        baseStencilSetPath = value;
                    } else if (name.equals("baseStencilSet")) {
                        baseStencilSet = value;
                    } else if (name.equals("stencilSetExtension")) {
                        stencilSetExtensionUrls.add(value);
                    } else if (name.equals("baseStencil")) {
                        baseStencil = value;
                    } else if (name.equals("columnPropertyMapping")) {
                        columnPropertyMapping = value.split(",");
                    } else if (name.equals("modelDescription")) {
                        modelDescription = value;
                    } else if (name.equals("modelTags")) {
                        modelTags = value.split(",");
                    } else if (name.equals("additionalERDFContentForGeneratedModel")) {
                        additionalERDFContentForGeneratedModel = value;
                    }
                }
            }

            // generate stencil set
            Date creationDate = new Date(System.currentTimeMillis());
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss.SSS");
            String stencilSetExtensionName = stencilSetExtensionNamePrefix + " "
                    + dateFormat.format(creationDate);

            stencilSetExtensionUrls
                    .add(StencilSetExtensionGenerator.generateStencilSetExtension(stencilSetExtensionName,
                            stencilPropertyMatrix, columnPropertyMapping, baseStencilSet, baseStencil));

            // generate new model
            String modelName = modelNamePrefix + stencilSetExtensionName;
            String model = repository.generateERDF(UUID.randomUUID().toString(),
                    additionalERDFContentForGeneratedModel, baseStencilSetPath, baseStencilSet,
                    stencilSetExtensionUrls, modelName, modelDescription);
            String modelUrl = baseUrl + repository.saveNewModel(model, modelName, modelDescription,
                    baseStencilSet, baseStencilSetPath);

            // hack for reverse proxies:
            modelUrl = modelUrl.substring(modelUrl.lastIndexOf("http://"));

            // tag model
            if (modelTags != null) {
                for (String tagName : modelTags) {
                    repository.addTag(modelUrl, tagName.trim());
                }
            }

            // redirect client to editor with that newly generated model
            response.setHeader("Location", modelUrl);
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);

        } catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        // TODO Add some error message
    }
}

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

/**
 * Parse request parameters and files.//  ww w . j  av  a2s .  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.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;
    }//from   ww w . j  a  v a  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 www.j ava  2 s.  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. j ava 2  s  .co  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.");
    }

}