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:org.chiba.adapter.web.HttpRequestHandler.java

private byte[] processMultiPartFile(FileItem item, String id, File savedFile, String encoding, byte[] data)
        throws XFormsException {
    // some data uploaded ...
    if (item.getSize() > 0) {

        if (chibaBean.storesExternalData(id)) {

            // store data to file and create URI
            try {
                savedFile.getParentFile().mkdir();
                item.write(savedFile);/*from  w w w  . j av a2 s  .  c  om*/
            } catch (Exception e) {
                throw new XFormsException(e);
            }
            // content is URI in this case
            try {
                data = savedFile.toURI().toString().getBytes(encoding);
            } catch (UnsupportedEncodingException e) {
                throw new XFormsException(e);
            }

        } else {
            // content is the data
            data = item.get();
        }
    }
    return data;
}

From source file:org.chiba.agent.web.servlet.HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("updating " + uploads.keySet().size() + " uploads(s)");
    }/*ww w  .j  a  va 2 s.  co m*/

    try {
        // update repeat indices
        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;

        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                LOGGER.debug("i'm here");
                String name = item.getName();
                if (name.contains("/")) {
                    name = name.substring(name.lastIndexOf('/') + 1);
                }
                if (name.contains("\\")) {
                    name = name.substring(name.lastIndexOf('\\') + 1);
                }
                if (this.xformsProcessor.isFileUpload(id, "anyURI")) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("found upload type 'anyURI'");
                    }

                    String localPath = new StringBuffer().append(System.currentTimeMillis()).append('/')
                            .append(name).toString();

                    File localFile = new File(this.uploadRoot, localPath);
                    localFile.getParentFile().mkdirs();
                    item.write(localFile);

                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("saving data to path: " + localFile);
                    }

                    // todo: externalize file handling and uri generation
                    data = localFile.toURI().toString().getBytes("UTF-8");
                } else {
                    data = item.get();
                }

                this.xformsProcessor.setUploadValue(id, item.getContentType(), name, data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("ignoring empty upload " + id);
                }
                // todo: removal ?
            }

            item.delete();
        }
    } catch (Exception e) {
        LOGGER.error(e);
        throw new XFormsException(e);
    }
}

From source file:org.chiba.web.servlet._HttpRequestHandler.java

protected void processUploadParameters(Map uploads, HttpServletRequest request) throws XFormsException {
    LOGGER.info("updating " + uploads.keySet().size() + " uploads(s)");

    try {/*w ww. j av  a2 s.  co  m*/
        // update repeat indices

        Iterator iterator = uploads.keySet().iterator();
        String id;
        FileItem item;
        byte[] data;
        while (iterator.hasNext()) {
            id = (String) iterator.next();
            item = (FileItem) uploads.get(id);

            if (item.getSize() > 0) {
                if (this.chibaBean.hasControlType(id, "anyURI")) {

                    String localPath = new StringBuffer().append('/').append(id).toString();
                    File localFile = new File(uploadRoot + this.sessionKey, localPath);

                    localFile.getParentFile().mkdirs();
                    item.write(localFile);
                    // todo: externalize file handling and uri generation
                    data = localFile.toURI().toString().getBytes("UTF-8");
                } else {
                    data = item.get();
                }

                this.chibaBean.updateControlValue(id, item.getContentType(), item.getName(), data);

                // After the value has been set and the RRR took place, create new UploadInfo with status set to 'done'
                request.getSession().setAttribute(XFormsSession.ADAPTER_PREFIX + sessionKey + "-uploadInfo",
                        new UploadInfo(1, 0, 0, 0, "done"));
            } else {
                LOGGER.info("ignoring empty upload " + id);
                // todo: removal ?
            }

            item.delete();
        }

    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.codelibs.fess.mylasta.direction.sponsor.FessMultipartRequestHandler.java

protected void showFileFieldParameter(final FileItem item) {
    if (logger.isDebugEnabled()) {
        logger.debug("[param] {}:{name={}, size={}}", item.getFieldName(), item.getName(), item.getSize());
    }/*from  w  w w  .  ja  v  a 2  s .c om*/
}

From source file:org.codemucker.testserver.capturing.CapturedFileItem.java

public CapturedFileItem(final FileItem item) {
    fieldName = item.getFieldName();/*from  w ww.j ava 2s. c o m*/
    fileName = item.getName();
    size = item.getSize();
    contentType = item.getContentType();
    payloadBytes = item.get();
}

From source file:org.coodex.concrete.attachments.server.UploadByFormResource.java

@Path("/{clientId}/{tokenId}")
@POST//from ww w.ja  v a  2s  .  co  m
@Consumes({ MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA })
@Produces(MediaType.APPLICATION_JSON)
public void uploadByForm(@Suspended final AsyncResponse asyncResponse,
        @Context final HttpServletRequest request, @PathParam("clientId") final String clientId,
        @PathParam("tokenId") final String tokenId) {

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = uploadHandler.parseRequest(request);
                List<AttachmentEntityInfo> result = new ArrayList<AttachmentEntityInfo>();
                for (FileItem item : items) {
                    if (!item.isFormField()) {
                        if (!Common.isBlank(item.getName())) {
                            AttachmentInfo attachmentInfo = new AttachmentInfo();
                            attachmentInfo.setName(item.getName());
                            attachmentInfo.setOwner(clientId);
                            attachmentInfo.setSize(item.getSize());
                            attachmentInfo.setContentType(item.getContentType());
                            result.add(saveToRepo(clientId, tokenId, attachmentInfo, item.getInputStream()));
                        }
                    }
                }
                asyncResponse.resume(result);
            } catch (Throwable t) {
                asyncResponse.resume(t);
            }
        }
    });
    t.setPriority(AttachmentServiceHelper.ATTACHMENT_PROFILE.getInt("upload.priority", 5));
    t.start();
}

From source file:org.cyberoam.iview.helper.RestoreDataHandler.java

public void run() {

    try {//from   w  w  w.ja v a2s  .c o m
        session.setAttribute("statusCheck", "3");
        // Processes the uploaded items
        Iterator it = fileItemsList.iterator();
        while (it.hasNext()) {
            if (RestoreDataHandler.isStopped()) {
                break;
            }

            FileItem fileItem = (FileItem) it.next();
            //checks whether the fileitem is a form field or not.
            if (fileItem.isFormField()) {
                //checks whether the form field name is filename or not.
                if (fileItem.getFieldName() != "filename")
                    continue;
                fileItem.getString();
            }

            if (fileItem != null) {
                String fileName = fileItem.getName();
                if ("".equalsIgnoreCase(fileName.trim()))
                    continue;
                String fName[] = fileName.replace("\\", "/").split("/");
                if (fName != null && fName.length > 0) {
                    fileName = fName[fName.length - 1];
                }

                if (fileItem.getSize() > 0) {
                    CyberoamLogger.appLog.debug("FileName: " + fileName);
                    //saves the file temporary in iViewConfigBean.ArchiveHome location
                    File saveTo = new File(iViewConfigBean.ArchiveHome + fileName);
                    try {
                        fileItem.write(saveTo);
                        int status = BackupRestoreUtility.Restore(saveTo.getPath(),
                                iViewConfigBean.ArchiveHome);
                        if (status == -1) {
                            setNotLoaded(getNotLoaded() + 1);
                        } else {
                            setLoaded(getLoaded() + 1);
                        }
                        //delete the temporary file
                        saveTo.delete();
                    } catch (Exception e) {
                        CyberoamLogger.appLog
                                .debug("An error occurred when we tried to save the uploaded file");
                    }
                }
            }
        }

        //starts the restorefilesrotation thread if one or more files are uploded
        if (getLoaded() > 0)
            new RestoreFilesRotation();
        RestoreDataHandler.setStopFlag(true);
        //         response.sendRedirect(request.getContextPath() + "/webpages/backuprestore.jsp?statusCheck=3&loaded="+loaded+"&notloaded="+notloaded);
    }

    catch (Exception e) {
        session.setAttribute("statusCheck", "3");
        RestoreDataHandler.setStopFlag(true);
        CyberoamLogger.appLog.debug("RestoreDataHandler->process->Exception->" + e, e);
    }
}

From source file:org.deegree.client.core.filter.InputFileWrapper.java

@SuppressWarnings("unchecked")
public InputFileWrapper(HttpServletRequest request) throws ServletException {
    super(request);
    try {/*  w  ww .  j  av a2s .c  o m*/
        ServletFileUpload upload = new ServletFileUpload();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        upload.setFileItemFactory(factory);
        String encoding = request.getCharacterEncoding();
        List<FileItem> fileItems = upload.parseRequest(request);
        formParameters = new HashMap<String, String[]>();
        for (int i = 0; i < fileItems.size(); i++) {
            FileItem item = fileItems.get(i);
            if (item.isFormField()) {
                String[] values;
                String v;
                if (encoding != null) {
                    v = item.getString(encoding);
                } else {
                    v = item.getString();
                }
                if (formParameters.containsKey(item.getFieldName())) {
                    String[] strings = formParameters.get(item.getFieldName());
                    values = new String[strings.length + 1];
                    for (int j = 0; j < strings.length; j++) {
                        values[j] = strings[j];
                    }
                    values[strings.length] = v;
                } else {
                    values = new String[] { v };
                }
                formParameters.put(item.getFieldName(), values);
            } else if (item.getName() != null && item.getName().length() > 0 && item.getSize() > 0) {
                request.setAttribute(item.getFieldName(), item);
            }
        }
    } catch (FileUploadException fe) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(fe);
        throw servletEx;
    } catch (UnsupportedEncodingException e) {
        ServletException servletEx = new ServletException();
        servletEx.initCause(e);
        throw servletEx;
    }
}

From source file:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_commonsFileUpload() throws Exception {
    Servlet servlet = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override//  w  ww  .  j a v  a  2  s . co m
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException, ServletException {

            boolean isMultipart = ServletFileUpload.isMultipartContent(req);
            Assert.assertTrue(isMultipart);

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletContext servletContext = this.getServletConfig().getServletContext();
            File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
            factory.setRepository(repository);
            ServletFileUpload upload = new ServletFileUpload(factory);

            List<FileItem> items = null;
            try {
                @SuppressWarnings("unchecked")
                List<FileItem> parseRequest = upload.parseRequest(req);
                items = parseRequest;
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            Assert.assertNotNull(items);
            Assert.assertFalse(items.isEmpty());

            FileItem fileItem = items.get(0);

            String submittedFileName = fileItem.getName();
            String contentType = fileItem.getContentType();
            long size = fileItem.getSize();

            PrintWriter writer = resp.getWriter();

            writer.write(submittedFileName);
            writer.write("|");
            writer.write(contentType);
            writer.write("|" + size);
        }
    };

    Dictionary<String, Object> props = new Hashtable<String, Object>();
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S16");
    props.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/Servlet16/*");
    registrations.add(getBundleContext().registerService(Servlet.class, servlet, props));

    Map<String, List<Object>> map = new HashMap<String, List<Object>>();

    map.put("file", Arrays.<Object>asList(getClass().getResource("blue.png")));

    Map<String, List<String>> result = requestAdvisor.upload("Servlet16/do", map);

    Assert.assertEquals("200", result.get("responseCode").get(0));
    Assert.assertEquals("blue.png|image/png|292", result.get("responseBody").get(0));
}

From source file:org.eclipse.kapua.app.console.servlet.FileServlet.java

@SuppressWarnings("unchecked")
public void parse(HttpServletRequest req) throws FileUploadException {
    s_logger.debug("upload.getFileSizeMax(): {}", getFileSizeMax());
    s_logger.debug("upload.getSizeMax(): {}", getSizeMax());

    // Parse the request
    List<FileItem> items = null;
    items = parseRequest(req);/*from  w  ww.ja  va2  s  . com*/

    // Process the uploaded items
    Iterator<FileItem> iter = items.iterator();
    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        if (item.isFormField()) {
            String name = item.getFieldName();
            String value = item.getString();

            s_logger.debug("Form field item name: {}, value: {}", name, value);

            formFields.put(name, value);
        } else {
            String fieldName = item.getFieldName();
            String fileName = item.getName();
            String contentType = item.getContentType();
            boolean isInMemory = item.isInMemory();
            long sizeInBytes = item.getSize();

            s_logger.debug("File upload item name: {}, fileName: {}, contentType: {}, isInMemory: {}, size: {}",
                    new Object[] { fieldName, fileName, contentType, isInMemory, sizeInBytes });

            fileItems.add(item);
        }
    }
}