Example usage for org.apache.commons.fileupload FileUploadException FileUploadException

List of usage examples for org.apache.commons.fileupload FileUploadException FileUploadException

Introduction

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

Prototype

public FileUploadException(String msg) 

Source Link

Document

Constructs a new FileUploadException with specified detail message.

Usage

From source file:org.exoplatform.document.upload.handle.UploadMultipartHandler.java

private String writeFiles(FileItem fileItem, String fileName) throws FileUploadException {
    int lastIndexOf = fileName.lastIndexOf("\\");
    if (lastIndexOf < 0) {
        lastIndexOf += 1;//from  w ww.ja v a  2s  .com
    }

    File file = new File(FilePathUtils.RESOURCE_PATH + File.separator + fileName.substring(lastIndexOf));

    byte[] buffer = new byte[1024];
    int length = 0;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        inputStream = fileItem.getInputStream();
        outputStream = new FileOutputStream(file);
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
    } catch (FileNotFoundException ex) {
        throw new FileUploadException(ex.getMessage());
    } catch (IOException ex) {
        throw new FileUploadException(ex.getMessage());
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
    }
    return file.getAbsolutePath();
}

From source file:org.obiba.mica.file.rest.TempFilesResource.java

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Timed//from w w  w.j  ava  2s . com
public Response upload(@Context HttpServletRequest request, @Context UriInfo uriInfo)
        throws IOException, FileUploadException {

    FileItem fileItem = getUploadedFile(request);
    if (fileItem == null)
        throw new FileUploadException("Failed to extract file item from request");
    TempFile tempFile = tempFileService.addTempFile(fileItem.getName(), fileItem.getInputStream());
    URI location = uriInfo.getBaseUriBuilder().path(TempFilesResource.class)
            .path(TempFilesResource.class, "file").build(tempFile.getId());

    return Response.created(location).build();
}

From source file:org.openmuc.framework.webui.bundleconfigurator.BundleConfigurator.java

private void installBundle(HttpServletRequest request, PluginContext pluginContext) {
    if (ServletFileUpload.isMultipartContent(request)) {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {/*from   w  ww. j  a  v a2  s  .c  o  m*/
            List<?> files = upload.parseRequest(request);

            byte[] buffer = new byte[8192];
            for (Object name : files) {
                FileItem element = (FileItem) name;

                if (!element.isFormField()) {
                    String fileName = element.getName();
                    if (!fileName.endsWith(".jar")) {
                        throw new FileUploadException("Wrong data type. Needs to be a \".jar\".");
                    }
                    fileName = fileName.replace('\\', '/'); // Windows stub
                    if (fileName.contains("/")) {
                        fileName = fileName.substring('/' + 1);
                    }

                    InputStream is = element.getInputStream();
                    FileOutputStream fos = new FileOutputStream(new File("bundle", fileName));

                    int len = 0;
                    while ((len = is.read(buffer)) > 0) {
                        fos.write(buffer, 0, len);
                    }

                    fos.flush();
                    fos.close();
                    is.close();

                    context.installBundle("file:bundle/" + fileName);

                    message = "Info: Installed Bundle " + fileName;
                }
            }
        } catch (Exception e) {
            message = "Error: " + e.getMessage();
        }
    }
}

From source file:org.sapia.soto.state.cocoon.util.CocoonFileUploadBase.java

/**
 * Processes an <a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867 </a>
 * compliant <code>multipart/form-data</code> stream. If files are stored on
 * disk, the path is given by <code>getRepository()</code>.
 * //from   w  ww . j  av a  2  s  .c o m
 * @param req
 *          The servlet request to be parsed.
 * 
 * @return A list of <code>FileItem</code> instances parsed from the
 *         request, in the order that they were transmitted.
 * 
 * @exception FileUploadException
 *              if there are problems reading/parsing the request or storing
 *              files.
 */
public List /* FileItem */ parseRequest(HttpRequest req) throws FileUploadException {
    if (null == req) {
        throw new NullPointerException("req parameter");
    }

    ArrayList items = new ArrayList();
    String contentType = req.getHeader(CONTENT_TYPE);

    if ((null == contentType) || (!contentType.startsWith(MULTIPART))) {
        throw new InvalidContentTypeException("the request doesn't contain a " + MULTIPART_FORM_DATA + " or "
                + MULTIPART_MIXED + " stream, content type header is " + contentType);
    }

    int requestSize = req.getContentLength();

    if (requestSize == -1) {
        throw new UnknownSizeException("the request was rejected because it's size is unknown");
    }

    if ((sizeMax >= 0) && (requestSize > sizeMax)) {
        throw new SizeLimitExceededException(
                "the request was rejected because " + "it's size exceeds allowed range");
    }

    try {
        int boundaryIndex = contentType.indexOf("boundary=");

        if (boundaryIndex < 0) {
            throw new FileUploadException(
                    "the request was rejected because " + "no multipart boundary was found");
        }

        byte[] boundary = contentType.substring(boundaryIndex + 9).getBytes();

        InputStream input = req.getInputStream();

        MultipartStream multi = new MultipartStream(input, boundary);
        multi.setHeaderEncoding(headerEncoding);

        boolean nextPart = multi.skipPreamble();

        while (nextPart) {
            Map headers = parseHeaders(multi.readHeaders());
            String fieldName = getFieldName(headers);

            if (fieldName != null) {
                String subContentType = getHeader(headers, CONTENT_TYPE);

                if ((subContentType != null) && subContentType.startsWith(MULTIPART_MIXED)) {
                    // Multiple files.
                    byte[] subBoundary = subContentType.substring(subContentType.indexOf("boundary=") + 9)
                            .getBytes();
                    multi.setBoundary(subBoundary);

                    boolean nextSubPart = multi.skipPreamble();

                    while (nextSubPart) {
                        headers = parseHeaders(multi.readHeaders());

                        if (getFileName(headers) != null) {
                            FileItem item = createItem(headers, false);
                            OutputStream os = item.getOutputStream();

                            try {
                                multi.readBodyData(os);
                            } finally {
                                os.close();
                            }

                            items.add(item);
                        } else {
                            // Ignore anything but files inside
                            // multipart/mixed.
                            multi.discardBodyData();
                        }

                        nextSubPart = multi.readBoundary();
                    }

                    multi.setBoundary(boundary);
                } else {
                    FileItem item = createItem(headers, getFileName(headers) == null);
                    OutputStream os = item.getOutputStream();

                    try {
                        multi.readBodyData(os);
                    } finally {
                        os.close();
                    }

                    items.add(item);
                }
            } else {
                // Skip this part.
                multi.discardBodyData();
            }

            nextPart = multi.readBoundary();
        }
    } catch (IOException e) {
        throw new FileUploadException(
                "Processing of " + MULTIPART_FORM_DATA + " request failed. " + e.getMessage());
    }

    return items;
}

From source file:org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor.java

protected void checkServiceFileExtensionValidity(String fileExtension, String[] allowedExtensions)
        throws FileUploadException {
    boolean isExtensionValid = false;
    StringBuffer allowedExtensionsStr = new StringBuffer();
    for (String allowedExtension : allowedExtensions) {
        allowedExtensionsStr.append(allowedExtension).append(",");
        if (fileExtension.endsWith(allowedExtension)) {
            isExtensionValid = true;/* w  ww . ja  v a 2s  .co  m*/
            break;
        }
    }
    if (!isExtensionValid) {
        throw new FileUploadException(
                " Illegal file type." + " Allowed file extensions are " + allowedExtensionsStr);
    }
}

From source file:org.wso2.carbon.ui.transports.fileupload.AbstractFileUploadExecutor.java

/**
 * This is a helper method that will be used upload main entity (ex: wsdd, jar, class etc) and
 * its resources to a given deployer./*w w w. ja va  2  s. c  o  m*/
 *
 * @param request
 * @param response
 * @param uploadDirName
 * @param extensions
 * @param utilityString
 * @return boolean
 * @throws IOException
 */
protected boolean uploadArtifacts(HttpServletRequest request, HttpServletResponse response,
        String uploadDirName, String[] extensions, String utilityString)
        throws FileUploadException, IOException {
    String axis2Repo = ServerConfiguration.getInstance()
            .getFirstProperty(ServerConfiguration.AXIS2_CONFIG_REPO_LOCATION);
    if (CarbonUtils.isURL(axis2Repo)) {
        String msg = "You are not permitted to upload jars to URL repository";
        throw new FileUploadException(msg);
    }

    String tmpDir = (String) configurationContext.getProperty(ServerConstants.WORK_DIR);
    String uuid = String.valueOf(System.currentTimeMillis() + Math.random());
    tmpDir = tmpDir + File.separator + "artifacts" + File.separator + uuid + File.separator;
    File tmpDirFile = new File(tmpDir);
    if (!tmpDirFile.exists() && !tmpDirFile.mkdirs()) {
        log.warn("Could not create " + tmpDirFile.getAbsolutePath());
    }

    response.setContentType("text/html; charset=utf-8");

    ServletRequestContext servletRequestContext = new ServletRequestContext(request);
    boolean isMultipart = ServletFileUpload.isMultipartContent(servletRequestContext);
    if (isMultipart) {
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // Create a new file upload handler
            List items = parseRequest(servletRequestContext);
            // Process the uploaded items
            for (Iterator iter = items.iterator(); iter.hasNext();) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
                    String fileName = item.getName();
                    String fileExtension = fileName;
                    fileExtension = fileExtension.toLowerCase();

                    String fileNameOnly = getFileName(fileName);
                    File uploadedFile;

                    String fieldName = item.getFieldName();

                    if (fieldName != null && fieldName.equals("jarResource")) {
                        if (fileExtension.endsWith(".jar")) {
                            File servicesDir = new File(tmpDir + File.separator + uploadDirName, "lib");
                            if (!servicesDir.exists() && !servicesDir.mkdirs()) {
                                log.warn("Could not create " + servicesDir.getAbsolutePath());
                            }
                            uploadedFile = new File(servicesDir, fileNameOnly);
                            item.write(uploadedFile);
                        }
                    } else {
                        File servicesDir = new File(tmpDir, uploadDirName);
                        if (!servicesDir.exists() && !servicesDir.mkdirs()) {
                            log.warn("Could not create " + servicesDir.getAbsolutePath());
                        }
                        uploadedFile = new File(servicesDir, fileNameOnly);
                        item.write(uploadedFile);
                    }
                }
            }

            //First lets filter for jar resources
            String repo = configurationContext.getAxisConfiguration().getRepository().getPath();

            //Writing the artifacts to the proper location
            String parent = repo + File.separator + uploadDirName;
            File mainDir = new File(tmpDir + File.separator + uploadDirName);
            File libDir = new File(mainDir, "lib");
            File[] resourceLibFile = FileManipulator.getMatchingFiles(libDir.getAbsolutePath(), null, "jar");

            for (File src : resourceLibFile) {
                File dst = new File(parent, "lib");
                String[] files = libDir.list();
                for (String file : files) {
                    copyFile(src, new File(dst, file));
                }
            }

            for (String extension : extensions) {
                File[] mainFiles = FileManipulator.getMatchingFiles(mainDir.getAbsolutePath(), null, extension);
                for (File mainFile : mainFiles) {
                    File dst = new File(parent);
                    String[] files = mainDir.list();
                    for (String file : files) {
                        File f = new File(dst, file);
                        if (!f.isDirectory()) {
                            copyFile(mainFile, f);
                        }
                    }

                }
            }
            response.sendRedirect(
                    getContextRoot(request) + "/carbon/service-mgt/index.jsp?message=Files have been uploaded "
                            + "successfully. This page will be auto refreshed shortly with "
                            + "the status of the created " + utilityString + " service"); //TODO: why do we redirect to service-mgt ???
            return true;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            String msg = "File upload failed";
            log.error(msg, e);
            throw new FileUploadException(msg, e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
    return false;
}

From source file:org.xchain.framework.servlet.MultipartFormDataServletRequest.java

private static DiskFileItemFactory createDiskFileItemFactory(int sizeThreshold, String repositoryPath)
        throws FileUploadException {
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // the location for saving data that is larger than getSizeThreshold()
    File repository = new File(repositoryPath);
    factory.setRepository(repository);/*ww  w .ja  va2 s  .co  m*/

    // maximum size that will be stored in memory
    factory.setSizeThreshold(sizeThreshold);

    // Check to see if repository exists; if not, try to create it; if this fails, throw an exception. 
    if (repository.exists()) {
        if (!repository.isDirectory()) {
            throw new FileUploadException("Cannot upload files because the specified temporary "
                    + "directory is of type file. (" + repository.getAbsolutePath() + ")");
        }
    } else if (!repository.mkdir()) {
        throw new FileUploadException("Cannot upload files because the specified temporary "
                + " does not exist, and attempts to create it have failed. (" + repository.getAbsolutePath()
                + ")");

    }
    return factory;
}

From source file:se.vgregion.portal.innovationsslussen.idea.controller.IdeaViewController.java

/**
 * Upload file action.// w  w w.  ja v  a 2s  .co m
 *
 * @param request  the request
 * @param response the response
 * @param model    the model
 * @throws FileUploadException the file upload exception
 */
@ActionMapping(params = "action=uploadFile")
public void uploadFile(ActionRequest request, ActionResponse response, Model model)
        throws FileUploadException, SystemException, PortalException {

    ThemeDisplay themeDisplay = getThemeDisplay(request);
    long scopeGroupId = themeDisplay.getScopeGroupId();
    long userId = themeDisplay.getUserId();

    String urlTitle = request.getParameter("urlTitle");

    String fileType = request.getParameter("fileType");
    boolean publicIdea;
    if (fileType.equals("public")) {
        publicIdea = true;
    } else if (fileType.equals("private")) {
        publicIdea = false;
    } else {
        throw new IllegalArgumentException("Unknown filetype: " + fileType);
    }

    //TODO ondig slagning? Cacha?
    Idea idea = ideaService.findIdeaByUrlTitle(urlTitle);
    //TODO Kan det inte finnas flera med samma titel i olika communities?

    IdeaContentType ideaContentType = publicIdea ? IdeaContentType.IDEA_CONTENT_TYPE_PUBLIC
            : IdeaContentType.IDEA_CONTENT_TYPE_PRIVATE;

    if (!isAllowedToDoAction(request, idea, Action.UPLOAD_FILE, ideaContentType)) {
        sendRedirectToContextRoot(response);
        return;
    }

    boolean mayUploadFile = idea.getUserId() == userId;

    IdeaPermissionChecker ideaPermissionChecker = ideaPermissionCheckerService
            .getIdeaPermissionChecker(scopeGroupId, userId, idea);

    if (!mayUploadFile) {
        if (publicIdea) {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPublic();
        } else {
            mayUploadFile = ideaPermissionChecker.isHasPermissionAddDocumentPrivate();
        }
    }

    if (mayUploadFile) {
        response.setRenderParameter("urlTitle", urlTitle);

        PortletFileUpload p = new PortletFileUpload();

        try {
            FileItemIterator itemIterator = p.getItemIterator(request);

            while (itemIterator.hasNext()) {
                FileItemStream fileItemStream = itemIterator.next();

                if (fileItemStream.getFieldName().equals("file")) {

                    InputStream is = fileItemStream.openStream();
                    BufferedInputStream bis = new BufferedInputStream(is);

                    String fileName = fileItemStream.getName();
                    String contentType = fileItemStream.getContentType();

                    ideaService.uploadFile(idea, publicIdea, fileName, contentType, bis);
                }
            }
        } catch (FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (IOException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (se.vgregion.service.innovationsslussen.exception.FileUploadException e) {
            doExceptionStuff(e, response, model);
            return;
        } catch (RuntimeException e) {
            Throwable lastCause = Util.getLastCause(e);
            if (lastCause instanceof SQLException) {
                SQLException nextException = ((SQLException) lastCause).getNextException();
                if (nextException != null) {
                    LOGGER.error(nextException.getMessage(), nextException);
                }
            }
        } finally {
            response.setRenderParameter("ideaType", fileType);
        }
    } else {
        throw new FileUploadException("The user is not authorized to upload to this idea instance.");
    }

    response.setRenderParameter("urlTitle", urlTitle);
    response.setRenderParameter("type", fileType);
    response.setRenderParameter("showView", "showIdea");
}