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

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

Introduction

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

Prototype

long getSize();

Source Link

Document

Returns the size of the file item.

Usage

From source file:edu.umd.cs.submitServer.servlets.UploadSubmission.java

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

    long now = System.currentTimeMillis();
    Timestamp submissionTimestamp = new Timestamp(now);

    // these are set by filters or previous servlets
    Project project = (Project) request.getAttribute(PROJECT);
    StudentRegistration studentRegistration = (StudentRegistration) request.getAttribute(STUDENT_REGISTRATION);
    MultipartRequest multipartRequest = (MultipartRequest) request.getAttribute(MULTIPART_REQUEST);
    boolean webBasedUpload = ((Boolean) request.getAttribute("webBasedUpload")).booleanValue();
    String clientTool = multipartRequest.getCheckedParameter("submitClientTool");
    String clientVersion = multipartRequest.getOptionalCheckedParameter("submitClientVersion");
    String cvsTimestamp = multipartRequest.getOptionalCheckedParameter("cvstagTimestamp");

    Collection<FileItem> files = multipartRequest.getFileItems();
    Kind kind;//  ww w .j  a v a 2 s.  co m

    byte[] zipOutput = null; // zipped version of bytesForUpload
    boolean fixedZip = false;
    try {

        if (files.size() > 1) {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(bos);
            for (FileItem item : files) {
                String name = item.getName();
                if (name == null || name.length() == 0)
                    continue;
                byte[] bytes = item.get();
                ZipEntry zentry = new ZipEntry(name);
                zentry.setSize(bytes.length);
                zentry.setTime(now);
                zos.putNextEntry(zentry);
                zos.write(bytes);
                zos.closeEntry();
            }
            zos.flush();
            zos.close();
            zipOutput = bos.toByteArray();
            kind = Kind.MULTIFILE_UPLOAD;

        } else {
            FileItem fileItem = multipartRequest.getFileItem();
            if (fileItem == null) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "There was a problem processing your submission. "
                                + "No files were found in your submission");
                return;
            }
            // get size in bytes
            long sizeInBytes = fileItem.getSize();
            if (sizeInBytes == 0 || sizeInBytes > Integer.MAX_VALUE) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                        "Trying upload file of size " + sizeInBytes);
                return;
            }

            // copy the fileItem into a byte array
            byte[] bytesForUpload = fileItem.get();
            String fileName = fileItem.getName();

            boolean isSpecialSingleFile = OfficeFileName.matcher(fileName).matches();

            FormatDescription desc = FormatIdentification.identify(bytesForUpload);
            if (!isSpecialSingleFile && desc != null && desc.getMimeType().equals("application/zip")) {
                fixedZip = FixZip.hasProblem(bytesForUpload);
                kind = Kind.ZIP_UPLOAD;
                if (fixedZip) {
                    bytesForUpload = FixZip.fixProblem(bytesForUpload,
                            studentRegistration.getStudentRegistrationPK());
                    kind = Kind.FIXED_ZIP_UPLOAD;
                }
                zipOutput = bytesForUpload;

            } else {

                // ==========================================================================================
                // [NAT] [Buffer to ZIP Part]
                // Check the type of the upload and convert to zip format if
                // possible
                // NOTE: I use both MagicMatch and FormatDescription (above)
                // because MagicMatch was having
                // some trouble identifying all zips

                String mime = URLConnection.getFileNameMap().getContentTypeFor(fileName);

                if (!isSpecialSingleFile && mime == null)
                    try {
                        MagicMatch match = Magic.getMagicMatch(bytesForUpload, true);
                        if (match != null)
                            mime = match.getMimeType();
                    } catch (Exception e) {
                        // leave mime as null
                    }

                if (!isSpecialSingleFile && "application/zip".equalsIgnoreCase(mime)) {
                    zipOutput = bytesForUpload;
                    kind = Kind.ZIP_UPLOAD2;
                } else {
                    InputStream ins = new ByteArrayInputStream(bytesForUpload);
                    if ("application/x-gzip".equalsIgnoreCase(mime)) {
                        ins = new GZIPInputStream(ins);
                    }

                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    ZipOutputStream zos = new ZipOutputStream(bos);

                    if (!isSpecialSingleFile && ("application/x-gzip".equalsIgnoreCase(mime)
                            || "application/x-tar".equalsIgnoreCase(mime))) {

                        kind = Kind.TAR_UPLOAD;

                        TarInputStream tins = new TarInputStream(ins);
                        TarEntry tarEntry = null;
                        while ((tarEntry = tins.getNextEntry()) != null) {
                            zos.putNextEntry(new ZipEntry(tarEntry.getName()));
                            tins.copyEntryContents(zos);
                            zos.closeEntry();
                        }
                        tins.close();
                    } else {
                        // Non-archive file type
                        if (isSpecialSingleFile)
                            kind = Kind.SPECIAL_ZIP_FILE;
                        else
                            kind = Kind.SINGLE_FILE;
                        // Write bytes to a zip file
                        ZipEntry zentry = new ZipEntry(fileName);
                        zos.putNextEntry(zentry);
                        zos.write(bytesForUpload);
                        zos.closeEntry();
                    }
                    zos.flush();
                    zos.close();
                    zipOutput = bos.toByteArray();
                }

                // [END Buffer to ZIP Part]
                // ==========================================================================================

            }
        }

    } catch (NullPointerException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                "There was a problem processing your submission. "
                        + "You should submit files that are either zipped or jarred");
        return;
    } finally {
        for (FileItem fItem : files)
            fItem.delete();
    }

    if (webBasedUpload) {
        clientTool = "web";
        clientVersion = kind.toString();
    }

    Submission submission = uploadSubmission(project, studentRegistration, zipOutput, request,
            submissionTimestamp, clientTool, clientVersion, cvsTimestamp, getDatabaseProps(),
            getSubmitServerServletLog());

    request.setAttribute("submission", submission);

    if (!webBasedUpload) {

        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println("Successful submission #" + submission.getSubmissionNumber() + " received for project "
                + project.getProjectNumber());

        out.flush();
        out.close();
        return;
    }
    boolean instructorUpload = ((Boolean) request.getAttribute("instructorViewOfStudent")).booleanValue();
    // boolean
    // isCanonicalSubmission="true".equals(request.getParameter("isCanonicalSubmission"));
    // set the successful submission as a request attribute
    String redirectUrl;

    if (fixedZip) {
        redirectUrl = request.getContextPath() + "/view/fixedSubmissionUpload.jsp?submissionPK="
                + submission.getSubmissionPK();
    }
    if (project.getCanonicalStudentRegistrationPK() == studentRegistration.getStudentRegistrationPK()) {
        redirectUrl = request.getContextPath() + "/view/instructor/projectUtilities.jsp?projectPK="
                + project.getProjectPK();
    } else if (instructorUpload) {
        redirectUrl = request.getContextPath() + "/view/instructor/project.jsp?projectPK="
                + project.getProjectPK();
    } else {
        redirectUrl = request.getContextPath() + "/view/project.jsp?projectPK=" + project.getProjectPK();
    }

    response.sendRedirect(redirectUrl);

}

From source file:com.krawler.esp.servlets.FileImporterServlet.java

public File getfile(HttpServletRequest request, String fileid) throws ServiceException {
    File uploadFile = null;//w w  w.  j a v  a2  s .c  o  m
    try {
        String destinationDirectory = StorageHandler.GetDocStorePath() + StorageHandler.GetFileSeparator()
                + "importplans";
        File destdir = new File(destinationDirectory);
        if (!destdir.exists()) {
            destdir.mkdir();
        }
        DiskFileUpload fu = new DiskFileUpload();
        String Ext = "";
        List fileItems = null;
        try {
            fileItems = fu.parseRequest(request);
        } catch (FileUploadException e) {
            KrawlerLog.op.warn("Problem While Uploading file :" + e.toString());
        }
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem fi = (FileItem) i.next();
            if (!fi.isFormField()) {
                String fileName = null;
                try {
                    fileName = new String(fi.getName().getBytes(), "UTF8");
                    if (fileName.contains(".")) {
                        Ext = fileName.substring(fileName.lastIndexOf("."));
                    }
                    long size = fi.getSize();
                    if (fi.getSize() != 0) {
                        String projid = request.getParameter("projectid");
                        uploadFile = new File(
                                destinationDirectory + StorageHandler.GetFileSeparator() + fileid + Ext);
                        fi.write(uploadFile);
                        fildoc(fileid, fileName, projid, fileid + Ext, AuthHandler.getUserid(request), size);

                    }
                } catch (IOException ex) {
                    KrawlerLog.op.warn("Problem While Reading file :" + ex.toString());
                    throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
                } catch (ServiceException ex) {
                    KrawlerLog.op.warn("Problem While Reading file :" + ex);
                    throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
                } catch (Exception ex) {
                    KrawlerLog.op.warn("Problem While Reading file :" + ex.toString());
                    throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
                }
            } else {
                arrParam.put(fi.getFieldName(), fi.getString());
            }
        }
    } catch (ConfigurationException ex) {
        KrawlerLog.op.warn("Problem Storing Data In DB [FileImporterServlet.storeInDB()]:" + ex);
        throw ServiceException.FAILURE("FileImporterServlet.getfile", ex);
    }
    return uploadFile;
}

From source file:com.silverpeas.attachment.servlets.DragAndDrop.java

/**
 * Method declaration/*from  www  .  ja va  2s  . c o  m*/
 * @param req
 * @param res
 * @throws IOException
 * @throws ServletException
 * @see
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_ENTER_METHOD");
    if (!FileUploadUtil.isRequestMultipart(req)) {
        res.getOutputStream().println("SUCCESS");
        return;
    }
    ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.util.attachment.Attachment", "");
    boolean actifyPublisherEnable = settings.getBoolean("ActifyPublisherEnable", false);
    try {
        req.setCharacterEncoding("UTF-8");
        String componentId = req.getParameter("ComponentId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                "componentId = " + componentId);
        String id = req.getParameter("PubId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "id = " + id);
        String userId = req.getParameter("UserId");
        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE", "userId = " + userId);
        String context = req.getParameter("Context");
        boolean bIndexIt = StringUtil.getBooleanValue(req.getParameter("IndexIt"));

        List<FileItem> items = FileUploadUtil.parseRequest(req);
        for (FileItem item : items) {
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getFieldName());
            SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                    "item = " + item.getName() + "; " + item.getString("UTF-8"));

            if (!item.isFormField()) {
                String fileName = item.getName();
                if (fileName != null) {
                    String physicalName = saveFileOnDisk(item, componentId, context);
                    String mimeType = AttachmentController.getMimeType(fileName);
                    long size = item.getSize();
                    SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                            "item size = " + size);
                    // create AttachmentDetail Object
                    AttachmentDetail attachment = new AttachmentDetail(
                            new AttachmentPK(null, "useless", componentId), physicalName, fileName, null,
                            mimeType, size, context, new Date(), new AttachmentPK(id, "useless", componentId));
                    attachment.setAuthor(userId);
                    try {
                        AttachmentController.createAttachment(attachment, bIndexIt);
                    } catch (Exception e) {
                        // storing data into DB failed, delete file just added on disk
                        deleteFileOnDisk(physicalName, componentId, context);
                        throw e;
                    }
                    // Specific case: 3d file to convert by Actify Publisher
                    if (actifyPublisherEnable) {
                        String extensions = settings.getString("Actify3dFiles");
                        StringTokenizer tokenizer = new StringTokenizer(extensions, ",");
                        // 3d native file ?
                        boolean fileForActify = false;
                        SilverTrace.info("attachment", "DragAndDrop.doPost", "root.MSG_GEN_PARAM_VALUE",
                                "nb tokenizer =" + tokenizer.countTokens());
                        String type = FileRepositoryManager.getFileExtension(fileName);
                        while (tokenizer.hasMoreTokens() && !fileForActify) {
                            String extension = tokenizer.nextToken();
                            fileForActify = type.equalsIgnoreCase(extension);
                        }
                        if (fileForActify) {
                            String dirDestName = "a_" + componentId + "_" + id;
                            String actifyWorkingPath = settings.getString("ActifyPathSource")
                                    + File.separatorChar + dirDestName;

                            String destPath = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath;
                            if (!new File(destPath).exists()) {
                                FileRepositoryManager.createGlobalTempPath(actifyWorkingPath);
                            }
                            String normalizedFileName = FilenameUtils.normalize(fileName);
                            if (normalizedFileName == null) {
                                normalizedFileName = FilenameUtils.getName(fileName);
                            }
                            String destFile = FileRepositoryManager.getTemporaryPath() + actifyWorkingPath
                                    + File.separatorChar + normalizedFileName;
                            FileRepositoryManager
                                    .copyFile(AttachmentController.createPath(componentId, "Images")
                                            + File.separatorChar + physicalName, destFile);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        SilverTrace.error("attachment", "DragAndDrop.doPost", "ERREUR", e);
        res.getOutputStream().println("ERROR");
        return;
    }
    res.getOutputStream().println("SUCCESS");
}

From source file:com.runwaysdk.controller.ServletDispatcher.java

/**
 * @param req//  ww  w  .  jav a 2  s.  c o  m
 * @param annotation
 * @return
 * @throws FileUploadException
 */
@SuppressWarnings("unchecked")
private Map<String, Parameter> getParameters(HttpServletRequest req, ActionParameters annotation) {
    String mojaxObject = req.getParameter(MOJAX_OBJECT);

    if (mojaxObject != null) {
        try {
            return this.getParameterMap(new MojaxObjectParser(annotation, mojaxObject).getMap());
        } catch (JSONException e) {
            throw new ClientException(e);
        }
    } else {
        if (ServletFileUpload.isMultipartContent(req)) {
            Map<String, Parameter> parameters = new HashMap<String, Parameter>();

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

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

            try {
                List<FileItem> items = upload.parseRequest(req);

                for (FileItem item : items) {
                    String fieldName = item.getFieldName();

                    if (item.isFormField()) {
                        String fieldValue = item.getString();

                        if (!parameters.containsKey(fieldName)) {
                            parameters.put(fieldName, new BasicParameter());
                        }

                        ((BasicParameter) parameters.get(fieldName)).add(fieldValue);
                    } else if (!item.isFormField() && item.getSize() > 0) {
                        parameters.put(fieldName, new MultipartFileParameter(item));
                    }
                }

                return parameters;
            } catch (FileUploadException e) {
                // Change the exception type
                throw new RuntimeException(e);
            }
        } else {
            return this.getParameterMap(req.getParameterMap());
        }
    }
}

From source file:it.eng.spagobi.mapcatalogue.service.DetailMapModule.java

private GeoMap recoverMapDetails(SourceBean serviceRequest)
        throws EMFUserError, SourceBeanException, IOException {
    GeoMap map = new GeoMap();

    String idStr = (String) serviceRequest.getAttribute("ID");
    Integer id = new Integer(idStr);
    String description = (String) serviceRequest.getAttribute("DESCR");
    String name = (String) serviceRequest.getAttribute("NAME");
    String format = (String) serviceRequest.getAttribute("FORMAT");
    Integer binId = new Integer((String) serviceRequest.getAttribute("BIN_ID"));

    map.setMapId(id.intValue());/*from  www  . java2  s .c  o  m*/
    map.setName(name);
    map.setDescr(description);
    map.setFormat(format);
    map.setBinId(binId);

    //gets the file eventually uploaded and sets the content variable
    FileItem uploaded = (FileItem) serviceRequest.getAttribute("UPLOADED_FILE");
    String fileName = null;
    if (uploaded != null) {
        fileName = GeneralUtilities.getRelativeFileNames(uploaded.getName());
        if (uploaded.getSize() == 0
                && ((String) serviceRequest.getAttribute("MESSAGEDET")).equals("DETAIL_INS")) {
            EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "201");
            getErrorHandler().addError(error);
            return map;
        }
        int maxSize = GeneralUtilities.getTemplateMaxSize();
        if (uploaded.getSize() > maxSize
                && ((String) serviceRequest.getAttribute("MESSAGEDET")).equals("DETAIL_INS")) {
            EMFValidationError error = new EMFValidationError(EMFErrorSeverity.ERROR, "uploadFile", "202");
            getErrorHandler().addError(error);
            return map;
        }
        if (uploaded.getSize() > 0) {
            try {
                content = uploaded.get();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    return map;
}

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

private void saveToDB(FileItem item, String folder) {
    IUploadInfo info = (IUploadInfo) Mirror.me(Demsy.bizEngine.getStaticType(LibConst.BIZSYS_ADMIN_UPLOAD))
            .born();/* w w w .j ava  2s.c  o  m*/
    Demsy me = Demsy.me();
    if (me.getSoft() != null)
        info.setSoftID(me.getSoft().getId());
    info.setContentType(item.getContentType());
    info.setExtName("CKFINDER");
    info.setLocalName(item.getName());
    info.setContentLength(item.getSize());
    info.setPath(new Upload(folder + "/" + this.newFileName));

    Demsy.orm().save(info);
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * This method parses the submit action, puts in session a listener where the
 * progress status is updated, and eventually stores the received data in
 * the user session.//from  w  w w.  ja  v  a  2 s.  c  o m
 * 
 * returns null in the case of success or a string with the error
 * 
 */
@SuppressWarnings("unchecked")
protected String parsePostRequest(HttpServletRequest request, HttpServletResponse response) {

    try {
        String delay = request.getParameter(PARAM_DELAY);
        uploadDelay = Integer.parseInt(delay);
    } catch (Exception e) {
    }

    HttpSession session = request.getSession();

    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") new upload request received.");

    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.isFrozen() || listener.isCanceled() || listener.getPercent() >= 100) {
            removeCurrentListener(request);
        } else {
            String error = getMessage("busy");
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") " + error);
            return error;
        }
    }
    // Create a file upload progress listener, and put it in the user session,
    // so the browser can use ajax to query status of the upload process
    listener = createNewListener(request);

    List<FileItem> uploadedItems;
    try {

        // Call to a method which the user can override
        checkRequest(request);

        // Create the factory used for uploading files,
        FileItemFactory factory = getFileItemFactory(request.getContentLength());
        ServletFileUpload uploader = new ServletFileUpload(factory);
        uploader.setSizeMax(maxSize);
        uploader.setProgressListener(listener);

        // Receive the files
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsing HTTP POST request ");
        uploadedItems = uploader.parseRequest(request);
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") parsed request, " + uploadedItems.size()
                + " items received.");

        // Received files are put in session
        Vector<FileItem> sessionFiles = (Vector<FileItem>) getSessionFileItems(request);
        if (sessionFiles == null) {
            sessionFiles = new Vector<FileItem>();
        }

        String error = "";
        session.setAttribute(SESSION_LAST_FILES, uploadedItems);

        if (uploadedItems.size() > 0) {
            sessionFiles.addAll(uploadedItems);
            String msg = "";
            for (FileItem i : sessionFiles) {
                msg += i.getFieldName() + " => " + i.getName() + "(" + i.getSize() + " bytes),";
            }
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") puting items in session: " + msg);
            session.setAttribute(SESSION_FILES, sessionFiles);
        } else {
            logger.error("UPLOAD-SERVLET (" + session.getId() + ") error NO DATA received ");
            error += getMessage("no_data");
        }

        return error.length() > 0 ? error : null;

    } catch (SizeLimitExceededException e) {
        RuntimeException ex = new UploadSizeLimitException(e.getPermittedSize(), e.getActualSize());
        listener.setException(ex);
        throw ex;
    } catch (UploadSizeLimitException e) {
        listener.setException(e);
        throw e;
    } catch (UploadCanceledException e) {
        listener.setException(e);
        throw e;
    } catch (UploadTimeoutException e) {
        listener.setException(e);
        throw e;
    } catch (Exception e) {
        logger.error("UPLOAD-SERVLET (" + request.getSession().getId() + ") Unexpected Exception -> "
                + e.getMessage() + "\n" + stackTraceToString(e));
        e.printStackTrace();
        RuntimeException ex = new UploadException(e);
        listener.setException(ex);
        throw ex;
    }
}

From source file:com.duroty.application.files.actions.UploadAction.java

protected ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ActionMessages errors = new ActionMessages();

    try {//from  ww  w.  j  a  v a  2s  .  c  o m
        boolean isMultipart = FileUpload.isMultipartContent(request);

        Store storeInstance = getStoreInstance(request);

        if (isMultipart) {
            Map fields = new HashMap();
            Vector files = new Vector();

            //Parse the request
            List items = diskFileUpload.parseRequest(request);

            //Process the uploaded items
            Iterator iter = items.iterator();

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

                if (item.isFormField()) {
                    fields.put(item.getFieldName(), item.getString());
                } else {
                    if (!StringUtils.isBlank(item.getName())) {
                        ByteArrayOutputStream baos = null;

                        try {
                            baos = new ByteArrayOutputStream();

                            IOUtils.copy(item.getInputStream(), baos);

                            MailPartObj part = new MailPartObj();
                            part.setAttachent(baos.toByteArray());
                            part.setContentType(item.getContentType());
                            part.setName(item.getName());
                            part.setSize(item.getSize());

                            files.addElement(part);
                        } catch (Exception ex) {
                        } finally {
                            IOUtils.closeQuietly(baos);
                        }
                    }
                }
            }

            if (files.size() > 0) {
                //Integer label = new Integer((String) fields.get("label"));
                storeInstance.send(files, 0, Charset.defaultCharset().displayName());
            }
        } else {
            errors.add("general",
                    new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "mail.send", "The form is null"));
            request.setAttribute("exception", "The form is null");
            request.setAttribute("newLocation", null);
            doTrace(request, DLog.ERROR, getClass(), "The form is null");
        }
    } catch (Exception ex) {
        String errorMessage = ExceptionUtilities.parseMessage(ex);

        if (errorMessage == null) {
            errorMessage = "NullPointerException";
        }

        errors.add("general", new ActionMessage(ExceptionCode.ERROR_MESSAGES_PREFIX + "general", errorMessage));
        request.setAttribute("exception", errorMessage);
        doTrace(request, DLog.ERROR, getClass(), errorMessage);
    } finally {
    }

    if (errors.isEmpty()) {
        doTrace(request, DLog.INFO, getClass(), "OK");

        return mapping.findForward(Constants.ACTION_SUCCESS_FORWARD);
    } else {
        saveErrors(request, errors);

        return mapping.findForward(Constants.ACTION_FAIL_FORWARD);
    }
}

From source file:fr.paris.lutece.plugins.genericattributes.service.entrytype.AbstractEntryTypeFile.java

/**
 * Get a generic attributes response from a file item
 * @param fileItem The file item/*w  ww  . java2s .c  om*/
 * @param entry The entry
 * @param bCreatePhysicalFile True to create the physical file associated
 *            with the file of the response, false otherwise. Note that the
 *            physical file will never be saved in the database by this
 *            method, like any other created object.
 * @return The created response
 */
private Response getResponseFromFile(FileItem fileItem, Entry entry, boolean bCreatePhysicalFile) {
    if (fileItem instanceof GenAttFileItem) {
        GenAttFileItem genAttFileItem = (GenAttFileItem) fileItem;

        if (genAttFileItem.getIdResponse() > 0) {
            Response response = ResponseHome.findByPrimaryKey(genAttFileItem.getIdResponse());
            response.setEntry(entry);
            response.setFile(FileHome.findByPrimaryKey(response.getFile().getIdFile()));

            if (bCreatePhysicalFile) {
                response.getFile().getPhysicalFile().setValue(fileItem.get());
            }

            return response;
        }
    }

    Response response = new Response();
    response.setEntry(entry);

    File file = new File();
    file.setTitle(fileItem.getName());
    file.setSize((fileItem.getSize() < Integer.MAX_VALUE) ? (int) fileItem.getSize() : Integer.MAX_VALUE);

    if (bCreatePhysicalFile) {
        file.setMimeType(FileSystemUtil.getMIMEType(file.getTitle()));

        PhysicalFile physicalFile = new PhysicalFile();
        physicalFile.setValue(fileItem.get());
        file.setPhysicalFile(physicalFile);
    }

    response.setFile(file);

    return response;
}

From source file:com.flexive.war.servlet.CeFileUpload.java

@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse)
        throws ServletException, IOException {
    String renderContent = null;/*from   w  ww.  j a va 2  s  . c o m*/
    try {

        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final BeContentEditorBean ceb = null; // = ContentEditorBean.getSingleton().getInstance(request);

        if (ceb == null) {
            renderContent = "No Content Editor Bean is active";
        } else {

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

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

            // Parse the request
            List /* FileItem */ items = upload.parseRequest(request);

            BinaryDescriptor binary = null;

            String xpath = null;
            for (Object item1 : items) {
                FileItem item = (FileItem) item1;
                if (item.isFormField()) {
                    if (item.getFieldName().equalsIgnoreCase("result")) {
                        renderContent = item.getString().replaceAll("\\\\n", "\\\n");
                    } else if (item.getFieldName().equalsIgnoreCase("xpath")) {
                        xpath = item.getString();
                    }
                } else {
                    InputStream uploadedStream = null;
                    try {
                        uploadedStream = item.getInputStream();
                        String name = item.getName();
                        if (name.indexOf('\\') > 0)
                            name = name.substring(name.lastIndexOf('\\') + 1);
                        binary = new BinaryDescriptor(name, item.getSize(), uploadedStream);
                    } finally {
                        if (uploadedStream != null)
                            uploadedStream.close();
                    }
                }
                //                    System.out.println("Item: " + item.getName());
            }

            //FxContent co = ceb.getContent();
            FxBinary binProperty = new FxBinary(binary);
            //co.setValue(xpath, binProperty);
            //ceb.getContentEngine().prepareSave(co);
        }
    } catch (Throwable t) {
        System.err.println(t.getMessage());
        t.printStackTrace();
        renderContent = t.getMessage();
    }

    // Render the result
    PrintWriter w = servletResponse.getWriter();
    if (renderContent == null) {
        renderContent = "No content";
    }
    w.print(renderContent);
    w.close();
    servletResponse.setContentType("text/html");
    servletResponse.setContentLength(renderContent.length());
    ((HttpServletResponse) servletResponse).setStatus(HttpServletResponse.SC_OK);
}