Example usage for org.apache.commons.fileupload FileItem delete

List of usage examples for org.apache.commons.fileupload FileItem delete

Introduction

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

Prototype

void delete();

Source Link

Document

Deletes the underlying storage for a file item, including deleting any associated temporary disk file.

Usage

From source file:com.twinsoft.convertigo.engine.servlets.GenericServlet.java

public Object processRequest(HttpServletRequest request) throws Exception {
    HttpServletRequestTwsWrapper twsRequest = request instanceof HttpServletRequestTwsWrapper
            ? (HttpServletRequestTwsWrapper) request
            : null;/*  w w  w .  jav a2 s. com*/
    File temporaryFile = null;

    try {
        // Check multipart request
        if (ServletFileUpload.isMultipartContent(request)) {
            Engine.logContext.debug("(ServletRequester.initContext) Multipart resquest");

            // Create a factory for disk-based file items
            DiskFileItemFactory factory = new DiskFileItemFactory();

            // Set factory constraints
            factory.setSizeThreshold(1000);

            temporaryFile = File.createTempFile("c8o-multipart-files", ".tmp");
            int cptFile = 0;
            temporaryFile.delete();
            temporaryFile.mkdirs();
            factory.setRepository(temporaryFile);
            Engine.logContext.debug("(ServletRequester.initContext) Temporary folder for upload is : "
                    + temporaryFile.getAbsolutePath());

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

            // Set overall request size constraint
            upload.setSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_REQUEST_SIZE));
            upload.setFileSizeMax(
                    EnginePropertiesManager.getPropertyAsLong(PropertyName.FILE_UPLOAD_MAX_FILE_SIZE));

            // Parse the request
            List<FileItem> items = GenericUtils.cast(upload.parseRequest(request));

            for (FileItem fileItem : items) {
                String parameterName = fileItem.getFieldName();
                String parameterValue;
                if (fileItem.isFormField()) {
                    parameterValue = fileItem.getString();
                    Engine.logContext.trace("(ServletRequester.initContext) Value for field '" + parameterName
                            + "' : " + parameterValue);
                } else {
                    String name = fileItem.getName().replaceFirst("^.*(?:\\\\|/)(.*?)$", "$1");
                    if (name.length() > 0) {
                        File wDir = new File(temporaryFile, "" + (++cptFile));
                        wDir.mkdirs();
                        File wFile = new File(wDir, name);
                        fileItem.write(wFile);
                        fileItem.delete();
                        parameterValue = wFile.getAbsolutePath();
                        Engine.logContext
                                .debug("(ServletRequester.initContext) Temporary uploaded file for field '"
                                        + parameterName + "' : " + parameterValue);
                    } else {
                        Engine.logContext
                                .debug("(ServletRequester.initContext) No temporary uploaded file for field '"
                                        + parameterName + "', empty name");
                        parameterValue = "";
                    }
                }

                if (twsRequest != null) {
                    twsRequest.addParameter(parameterName, parameterValue);
                }
            }
        }

        Requester requester = getRequester();
        request.setAttribute("convertigo.requester", requester);

        Object result = requester.processRequest(request);

        request.setAttribute("convertigo.cookies", requester.context.getCookieStrings());

        String trSessionId = requester.context.getSequenceTransactionSessionId();
        if (trSessionId != null) {
            request.setAttribute("sequence.transaction.sessionid", trSessionId);
        }

        if (requester.context.requireEndOfContext) {
            // request.setAttribute("convertigo.requireEndOfContext",
            // requester);
            request.setAttribute("convertigo.requireEndOfContext", Boolean.TRUE);
        }

        if (request.getAttribute("convertigo.contentType") == null) { // if
            // contentType
            // set by
            // webclipper
            // servlet
            // (#320)
            request.setAttribute("convertigo.contentType", requester.context.contentType);
        }

        request.setAttribute("convertigo.cacheControl", requester.context.cacheControl);
        request.setAttribute("convertigo.context.contextID", requester.context.contextID);
        request.setAttribute("convertigo.isErrorDocument", new Boolean(requester.context.isErrorDocument));
        request.setAttribute("convertigo.context.removalRequired",
                new Boolean(requester.context.removalRequired()));
        if (requester.context.requestedObject != null) { // #397 : charset HTTP
            // header missing
            request.setAttribute("convertigo.charset", requester.context.requestedObject.getEncodingCharSet());
        } else { // #3803
            Engine.logEngine.warn(
                    "(GenericServlet) requestedObject is null. Set encoding to UTF-8 for processRequest.");
            request.setAttribute("convertigo.charset", "UTF-8");
        }

        return result;
    } finally {
        if (temporaryFile != null) {
            try {
                Engine.logEngine.debug(
                        "(GenericServlet) Removing the temporary file : " + temporaryFile.getAbsolutePath());
                FileUtils.deleteDirectory(temporaryFile);
            } catch (IOException e) {
            }
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.RDFUploadController.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTION)) {
        return;/* www  .  j  a v a 2  s  . c o m*/
    }

    VitroRequest request = new VitroRequest(req);
    if (request.hasFileSizeException()) {
        forwardToFileUploadError(request.getFileSizeException().getLocalizedMessage(), req, response);
        return;
    }

    Map<String, List<FileItem>> fileStreams = request.getFiles();

    LoginStatusBean loginBean = LoginStatusBean.getBean(request);

    try {
        String modelName = req.getParameter("modelName");
        if (modelName != null) {
            loadRDF(request, response);
            return;
        }
    } catch (Exception e) {
        log.error(e, e);
        throw new RuntimeException(e);
    }

    boolean remove = "remove".equals(request.getParameter("mode"));
    String verb = remove ? "Removed" : "Added";

    String languageStr = request.getParameter("language");

    boolean makeClassgroups = ("true".equals(request.getParameter("makeClassgroups")));

    // add directly to the ABox model without reading first into 
    // a temporary in-memory model
    boolean directRead = ("directAddABox".equals(request.getParameter("mode")));

    String uploadDesc = "";

    OntModel uploadModel = (directRead) ? getABoxModel(getServletContext())
            : ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);

    /* ********************* GET RDF by URL ********************** */
    String RDFUrlStr = request.getParameter("rdfUrl");
    if (RDFUrlStr != null && RDFUrlStr.length() > 0) {
        try {
            uploadModel.enterCriticalSection(Lock.WRITE);
            try {
                uploadModel.read(RDFUrlStr, languageStr);
                // languageStr may be null and default would be RDF/XML
            } finally {
                uploadModel.leaveCriticalSection();
            }
            uploadDesc = verb + " RDF from " + RDFUrlStr;
        } catch (JenaException ex) {
            forwardToFileUploadError("Could not parse file to " + languageStr + ": " + ex.getMessage(), req,
                    response);
            return;
        } catch (Exception e) {
            forwardToFileUploadError("Could not load from URL: " + e.getMessage(), req, response);
            return;
        }
    } else {
        /* **************** upload RDF from POST ********************* */
        if (fileStreams.get("rdfStream") != null && fileStreams.get("rdfStream").size() > 0) {
            FileItem rdfStream = fileStreams.get("rdfStream").get(0);
            try {
                if (directRead) {
                    addUsingRDFService(rdfStream.getInputStream(), languageStr, request.getRDFService());
                } else {
                    uploadModel.enterCriticalSection(Lock.WRITE);
                    try {
                        uploadModel.read(rdfStream.getInputStream(), null, languageStr);
                    } finally {
                        uploadModel.leaveCriticalSection();
                    }
                }
                uploadDesc = verb + " RDF from file " + rdfStream.getName();
            } catch (IOException e) {
                forwardToFileUploadError("Could not read file: " + e.getLocalizedMessage(), req, response);
                return;
            } catch (JenaException ex) {
                forwardToFileUploadError("Could not parse file to " + languageStr + ": " + ex.getMessage(), req,
                        response);
                return;
            } catch (Exception e) {
                forwardToFileUploadError("Could not load from file: " + e.getMessage(), req, response);
                return;
            } finally {
                rdfStream.delete();
            }
        }
    }

    /* ********** Do the model changes *********** */
    if (!directRead && uploadModel != null) {

        uploadModel.loadImports();

        long tboxstmtCount = 0L;
        long aboxstmtCount = 0L;

        JenaModelUtils xutil = new JenaModelUtils();

        OntModel tboxModel = getTBoxModel();
        OntModel aboxModel = getABoxModel(getServletContext());
        OntModel tboxChangeModel = null;
        Model aboxChangeModel = null;
        OntModelSelector ontModelSelector = ModelAccess.on(getServletContext()).getOntModelSelector();

        if (tboxModel != null) {
            boolean AGGRESSIVE = true;
            tboxChangeModel = xutil.extractTBox(uploadModel, AGGRESSIVE);
            // aggressively seek all statements that are part of the TBox  
            tboxstmtCount = operateOnModel(request.getUnfilteredWebappDaoFactory(), tboxModel, tboxChangeModel,
                    ontModelSelector, remove, makeClassgroups, loginBean.getUserURI());
        }
        if (aboxModel != null) {
            aboxChangeModel = uploadModel.remove(tboxChangeModel);
            aboxstmtCount = operateOnModel(request.getUnfilteredWebappDaoFactory(), aboxModel, aboxChangeModel,
                    ontModelSelector, remove, makeClassgroups, loginBean.getUserURI());
        }
        request.setAttribute("uploadDesc",
                uploadDesc + ". " + verb + " " + (tboxstmtCount + aboxstmtCount) + "  statements.");
    } else {
        request.setAttribute("uploadDesc", "RDF upload successful.");
    }

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("bodyJsp", "/templates/edit/specific/upload_rdf_result.jsp");
    request.setAttribute("title", "Ingest RDF Data");

    try {
        rd.forward(request, response);
    } catch (Exception e) {
        log.error("Could not forward to view: " + e.getLocalizedMessage());
    }
}

From source file:axiom.servlet.AbstractServletClient.java

protected List parseUploads(ServletRequestContext reqcx, RequestTrans reqtrans, final UploadStatus uploadStatus,
        String encoding) throws FileUploadException, UnsupportedEncodingException {

    List uploads = null;//  ww  w .  j a va  2s .c  o m
    Context cx = Context.enter();
    ImporterTopLevel scope = new ImporterTopLevel(cx, true);

    try {
        // handle file upload
        DiskFileItemFactory factory = new DiskFileItemFactory();
        FileUpload upload = new FileUpload(factory);
        // use upload limit for individual file size, but also set a limit on overall size
        upload.setFileSizeMax(uploadLimit * 1024);
        upload.setSizeMax(totalUploadLimit * 1024);

        // register upload tracker with user's session
        if (uploadStatus != null) {
            upload.setProgressListener(new ProgressListener() {
                public void update(long bytesRead, long contentLength, int itemsRead) {
                    uploadStatus.update(bytesRead, contentLength, itemsRead);
                }
            });
        }

        uploads = upload.parseRequest(reqcx);
        Iterator it = uploads.iterator();

        while (it.hasNext()) {
            FileItem item = (FileItem) it.next();
            String name = item.getFieldName();
            Object value = null;
            // check if this is an ordinary HTML form element or a file upload
            if (item.isFormField()) {
                value = item.getString(encoding);
            } else {
                String itemName = item.getName().trim();
                if (itemName == null || itemName.equals("")) {
                    continue;
                }
                value = new MimePart(itemName, item.get(), item.getContentType());
                value = new NativeJavaObject(scope, value, value.getClass());
            }
            item.delete();
            // if multiple values exist for this name, append to _array

            // reqtrans.addPostParam(name, value); ????

            Object ret = reqtrans.get(name);
            if (ret != null && ret != Scriptable.NOT_FOUND) {
                appendFormValue(reqtrans, name, value);
            } else {
                reqtrans.set(name, value);
            }
        }
    } finally {
        Context.exit();
    }

    return uploads;
}

From source file:com.afis.jx.ckfinder.connector.handlers.command.FileUploadCommand.java

/**
 *
 * @param request http request//from  w w  w . j a  va  2s. co m
 * @return true if uploaded correctly
 */
@SuppressWarnings("unchecked")
private boolean fileUpload(final HttpServletRequest request) {
    try {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        List<FileItem> items = uploadHandler.parseRequest(request);
        Collections.sort(items, new Comparator<FileItem>() {
            //This comparator moves tokenParamName to first position on the list.
            @Override
            public int compare(FileItem a, FileItem b) {
                if (a.getFieldName().equals(tokenParamName)) {
                    return (-1);
                }
                if (b.getFieldName().equals(tokenParamName)) {
                    return (1);
                }
                return 0;
            }
        });

        for (int i = 0, j = items.size(); i < j; i++) {
            FileItem item = items.get(i);
            if (configuration.isEnableCsrfProtection() && (!items.get(0).getFieldName().equals(tokenParamName)
                    || (item.getFieldName().equals(tokenParamName)
                            && !checkCsrfToken(request, item.getString())))) {
                throw new ConnectorException(Constants.Errors.CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST,
                        "CSRF Attempt");
            } else if (items.get(0).getFieldName().equals(tokenParamName) && items.size() == 1) {
                //No file was provided. Only the CSRF token
                throw new ConnectorException(Constants.Errors.CKFINDER_CONNECTOR_ERROR_CUSTOM_ERROR,
                        "No file provided in the request.");
            } else if (!item.isFormField()) {
                String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder;
                this.fileName = getFileItemName(item);

                try {
                    if (validateUploadItem(item, path)) {
                        return saveTemporaryFile(path, item);
                    }
                } finally {
                    item.delete();
                }
            }
        }
        return false;
    } catch (InvalidContentTypeException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
        return false;
    } catch (IOFileUploadException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    } catch (SizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (FileSizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (ConnectorException e) {
        this.errorCode = e.getErrorCode();
        if (this.errorCode == Constants.Errors.CKFINDER_CONNECTOR_ERROR_CUSTOM_ERROR) {
            this.customErrorMsg = e.getErrorMsg();
        }
        return false;
    } catch (Exception e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    }

}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.WorkflowUploadPortlet.java

@Override
protected void doUpload(ActionRequest request, ActionResponse response) {
    PortletContext context = getPortletContext();
    context.log("[FileUploadPortlet] doUpload() called");

    try {/*from w  w w .  j ava 2s  .co m*/
        DiskFileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload pfu = new PortletFileUpload(factory);
        pfu.setSizeMax(uploadMaxSize); // Maximum upload size
        pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

        PortletSession ps = request.getPortletSession();
        if (ps.getAttribute("uploads", ps.APPLICATION_SCOPE) == null)
            ps.setAttribute("uploads", new Hashtable<String, ProgressListener>());

        //get the FileItems
        String fieldName = null;

        List fileItems = pfu.parseRequest(request);
        Iterator iter = fileItems.iterator();
        File serverSideFile = null;
        Hashtable h = new Hashtable(); //fileupload
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // retrieve hidden parameters if item is a form field
            if (item.isFormField()) {
                fieldName = item.getFieldName();
                if ("newGrafName".equals(fieldName))
                    h.put("newGrafName", item.getString());
                if ("newAbstName".equals(fieldName))
                    h.put("newAbstName", item.getString());
                if ("newRealName".equals(fieldName))
                    h.put("newRealName", item.getString());
            } else { // item is not a form field, do file upload
                Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps
                        .getAttribute("uploads");//,ps.APPLICATION_SCOPE
                pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

                String s = item.getName();
                s = FilenameUtils.getName(s);
                ProgressListener pl = pfu.getProgressListener();
                tmp.put(s, pl);
                ps.setAttribute("uploads", tmp);

                String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser();
                File f = new File(tempDir);
                if (!f.exists())
                    f.mkdirs();
                serverSideFile = new File(tempDir, s);
                item.write(serverSideFile);
                item.delete();
                context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir);
            }
        }
        // file upload to storage
        try {
            ServiceType st = InformationBase.getI().getService("wfs", "portal", new Hashtable(), new Vector());
            h.put("senderObj", "ZipFileSender");
            h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url"));
            h.put("wfsID", st.getServiceUrl());
            h.put("userID", request.getRemoteUser());

            Hashtable hsh = new Hashtable();
            //                    st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
            //                    hsh.put("url", "http://localhost:8080/storage");
            st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
            PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject()).newInstance();
            psc.setServiceURL(st.getServiceUrl());
            psc.setServiceID("/receiver");
            if (serverSideFile != null)
                psc.fileUpload(serverSideFile, "fileName", h);
        } catch (Exception ex) {
            response.setRenderParameter("full", "error.upload");
            ex.printStackTrace();
            return;
        }
        ps.removeAttribute("uploads", ps.APPLICATION_SCOPE);

    } catch (FileUploadException fue) {
        response.setRenderParameter("full", "error.upload");

        fue.printStackTrace();
        context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        response.setRenderParameter("full", "error.exception");
        context.log("[FileUploadPortlet] - failed to upload file - " + e.toString());
        return;
    }
    response.setRenderParameter("full", "action.succesfull");
}

From source file:com.hightern.fckeditor.connector.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * // w  w w  .  j  a v a  2 s .c  o  m
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
@SuppressWarnings("unchecked")
UploadResponse doPost(final HttpServletRequest request) {
    Dispatcher.logger.debug("Entering Dispatcher#doPost");

    final Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request)) {
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    } else if (!Command.isValidForPost(context.getCommandStr())) {
        uploadResponse = UploadResponse.getInvalidCommandError();
    } else if (!ResourceType.isValidType(context.getTypeStr())) {
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) {
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    } else {

        // call the Connector#fileUpload
        final ResourceType type = context.getDefaultResourceType();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            final List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            final FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            final String fileName = FilenameUtils.getName(uplFile.getName());
            Dispatcher.logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                final String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request),
                        type, context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName)) {
                    uploadResponse = UploadResponse.getOK(fileUrl);
                } else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (final InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (final WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    Dispatcher.logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:com.safetys.framework.fckeditor.connector.Dispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*from   www  .  java2 s . c  o  m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
@SuppressWarnings("unchecked")
UploadResponse doPost(final HttpServletRequest request) {
    Dispatcher.logger.debug("Entering Dispatcher#doPost");

    final Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request)) {
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    } else if (!Command.isValidForPost(context.getCommandStr())) {
        uploadResponse = UploadResponse.getInvalidCommandError();
    } else if (!ResourceType.isValidType(context.getTypeStr())) {
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    } else if (!UtilsFile.isValidPath(context.getCurrentFolderStr())) {
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    } else {

        // call the Connector#fileUpload
        final ResourceType type = context.getDefaultResourceType();
        final FileItemFactory factory = new DiskFileItemFactory();
        final ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            final List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            final FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            final String fileName = FilenameUtils.getName(uplFile.getName());
            Dispatcher.logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName))) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                final String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                Dispatcher.logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                final String newFileName = this.connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                final String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request),
                        type, context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName)) {
                    uploadResponse = UploadResponse.getOK(fileUrl);
                } else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    Dispatcher.logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (final InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (final WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (final FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    Dispatcher.logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}

From source file:hu.sztaki.lpds.pgportal.portlets.workflow.RealWorkflowPortlet.java

@Override
public void doUpload(ActionRequest request, ActionResponse response) {
    PortletContext context = getPortletContext();
    context.log("[FileUploadPortlet] doUpload() called");

    try {//from  ww w . ja  v a2s . c  om
        DiskFileItemFactory factory = new DiskFileItemFactory();
        PortletFileUpload pfu = new PortletFileUpload(factory);
        pfu.setSizeMax(uploadMaxSize); // Maximum upload size
        pfu.setProgressListener((ProgressListener) new FileUploadProgressListener());

        PortletSession ps = request.getPortletSession();
        if (ps.getAttribute("uploaded") == null)
            ps.setAttribute("uploaded", new Vector<String>());
        ps.setAttribute("upload", pfu);

        //get the FileItems
        String fieldName = null;

        List fileItems = pfu.parseRequest(request);
        Iterator iter = fileItems.iterator();
        File serverSideFile = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // retrieve hidden parameters if item is a form field
            if (item.isFormField()) {
                fieldName = item.getFieldName();
            } else { // item is not a form field, do file upload
                Hashtable<String, ProgressListener> tmp = (Hashtable<String, ProgressListener>) ps
                        .getAttribute("uploads", ps.APPLICATION_SCOPE);

                String s = item.getName();
                s = FilenameUtils.getName(s);
                ps.setAttribute("uploading", s);

                String tempDir = System.getProperty("java.io.tmpdir") + "/uploads/" + request.getRemoteUser();
                File f = new File(tempDir);
                if (!f.exists())
                    f.mkdirs();
                serverSideFile = new File(tempDir, s);
                item.write(serverSideFile);
                item.delete();
                context.log("[FileUploadPortlet] - file " + s + " uploaded successfully to " + tempDir);
                // file upload to storage
                try {
                    Hashtable h = new Hashtable();
                    h.put("portalURL", PropertyLoader.getInstance().getProperty("service.url"));
                    h.put("userID", request.getRemoteUser());

                    String uploadField = "";
                    // retrieve hidden parameters if item is a form field
                    for (FileItem item0 : (List<FileItem>) fileItems) {
                        if (item0.isFormField())
                            h.put(item0.getFieldName(), item0.getString());
                        else
                            uploadField = item0.getFieldName();

                    }

                    Hashtable hsh = new Hashtable();
                    ServiceType st = InformationBase.getI().getService("storage", "portal", hsh, new Vector());
                    PortalStorageClient psc = (PortalStorageClient) Class.forName(st.getClientObject())
                            .newInstance();
                    psc.setServiceURL(st.getServiceUrl());
                    psc.setServiceID("/upload");
                    if (serverSideFile != null) {
                        psc.fileUpload(serverSideFile, uploadField, h);
                    }
                } catch (Exception ex) {
                    response.setRenderParameter("full", "error.upload");
                    ex.printStackTrace();
                    return;
                }
                ((Vector<String>) ps.getAttribute("uploaded")).add(s);

            }

        }
        //            ps.removeAttribute("uploads",ps.APPLICATION_SCOPE);
        ps.setAttribute("finaluploads", "");

    } catch (FileUploadException fue) {
        response.setRenderParameter("full", "error.upload");

        fue.printStackTrace();
        context.log("[FileUploadPortlet] - failed to upload file - " + fue.toString());
        return;
    } catch (Exception e) {
        e.printStackTrace();
        response.setRenderParameter("full", "error.exception");
        context.log("[FileUploadPortlet] - failed to upload file - " + e.toString());
        return;
    }
    response.setRenderParameter("full", "action.succesfull");

}

From source file:com.kmetop.demsy.modules.ckfinder.FileUploadCommand.java

/**
 * //w  w w . j  a va 2  s  . co  m
 * @param request
 *            http request
 * @return true if uploaded correctly
 */
@SuppressWarnings("unchecked")
private boolean fileUpload(final HttpServletRequest request) {
    try {
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);

        List<FileItem> items = uploadHandler.parseRequest(request);
        for (FileItem item : items) {
            String path = configuration.getTypes().get(this.type).getPath() + this.currentFolder;

            this.fileName = getFileItemName(item);

            try {
                if (validateUploadItem(item, path)) {
                    boolean succ = saveTemporaryFile(path, item);
                    try {
                        saveToDB(item, configuration.getTypes().get(this.type).getUrl() + this.currentFolder);
                    } catch (Throwable e) {
                        log.error("??! ", e);
                    }
                    return succ;
                }
            } finally {
                // file should be deleted from temporary files automaticly
                // but in some cases the file was not deleted
                // but when file was deleted after item.write
                // then inputstream isn't available any more.
                try {
                    item.getOutputStream().close();
                    item.getInputStream().close();
                } catch (IOException e) {
                    // when input stream isn't avail
                    // you don't have to close it
                    // Probably if this issue will be fixed:
                    // https://issues.apache.org/jira/browse/FILEUPLOAD-191
                    // all code in finally can be deleted.
                }

                item.delete();
            }
        }
        return false;
    } catch (InvalidContentTypeException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_CORRUPT;
        return false;
    } catch (IOFileUploadException e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    } catch (SizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (FileSizeLimitExceededException e) {
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_UPLOADED_TOO_BIG;
        return false;
    } catch (ConnectorException e) {
        this.errorCode = e.getErrorCode();
        return false;
    } catch (Exception e) {
        if (configuration.isDebugMode()) {
            this.exception = e;
        }
        this.errorCode = Constants.Errors.CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED;
        return false;
    }

}

From source file:net.fckeditor.connector.MyDispatcher.java

/**
 * Called by the connector servlet to handle a {@code POST} request. In
 * particular, it handles the {@link Command#FILE_UPLOAD FileUpload} and
 * {@link Command#QUICK_UPLOAD QuickUpload} commands.
 * /*w ww .j  av  a  2  s  . co m*/
 * @param request
 *            the current request instance
 * @return the upload response instance associated with this request
 */
UploadResponse doPost(final HttpServletRequest request) {
    logger.debug("Entering Dispatcher#doPost");

    Context context = ThreadLocalData.getContext();
    context.logBaseParameters();

    UploadResponse uploadResponse = null;
    // check permissions for user actions
    if (!RequestCycleHandler.isFileUploadEnabled(request))
        uploadResponse = UploadResponse.getFileUploadDisabledError();
    // check parameters  
    else if (!Command.isValidForPost(context.getCommandStr()))
        uploadResponse = UploadResponse.getInvalidCommandError();
    else if (!ResourceType.isValidType(context.getTypeStr()))
        uploadResponse = UploadResponse.getInvalidResourceTypeError();
    else if (!UtilsFile.isValidPath(context.getCurrentFolderStr()))
        uploadResponse = UploadResponse.getInvalidCurrentFolderError();
    else {

        // call the Connector#fileUpload
        ResourceType type = context.getDefaultResourceType();
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
            List<FileItem> items = upload.parseRequest(request);
            // We upload just one file at the same time
            FileItem uplFile = items.get(0);
            // Some browsers transfer the entire source path not just the
            // filename
            String fileName = FilenameUtils.getName(uplFile.getName());
            fileName = UUID.randomUUID().toString().replace("-", "") + "."
                    + FilenameUtils.getExtension(fileName);
            logger.debug("Parameter NewFile: {}", fileName);
            // check the extension
            if (type.isDeniedExtension(FilenameUtils.getExtension(fileName)))
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            // Secure image check (can't be done if QuickUpload)
            else if (type.equals(ResourceType.IMAGE) && PropertiesLoader.isSecureImageUploads()
                    && !UtilsFile.isImage(uplFile.getInputStream())) {
                uploadResponse = UploadResponse.getInvalidFileTypeError();
            } else {
                String sanitizedFileName = UtilsFile.sanitizeFileName(fileName);
                logger.debug("Parameter NewFile (sanitized): {}", sanitizedFileName);
                String newFileName = connector.fileUpload(type, context.getCurrentFolderStr(),
                        sanitizedFileName, uplFile.getInputStream());
                String fileUrl = UtilsResponse.fileUrl(RequestCycleHandler.getUserFilesPath(request), type,
                        context.getCurrentFolderStr(), newFileName);

                if (sanitizedFileName.equals(newFileName))
                    uploadResponse = UploadResponse.getOK(fileUrl);
                else {
                    uploadResponse = UploadResponse.getFileRenamedWarning(fileUrl, newFileName);
                    logger.debug("Parameter NewFile (renamed): {}", newFileName);
                }
            }

            uplFile.delete();
        } catch (InvalidCurrentFolderException e) {
            uploadResponse = UploadResponse.getInvalidCurrentFolderError();
        } catch (WriteException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (IOException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        } catch (FileUploadException e) {
            uploadResponse = UploadResponse.getFileUploadWriteError();
        }
    }

    logger.debug("Exiting Dispatcher#doPost");
    return uploadResponse;
}