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

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

Introduction

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

Prototype

byte[] get();

Source Link

Document

Returns the contents of the file item as an array of bytes.

Usage

From source file:org.sakaiproject.tool.syllabus.SyllabusTool.java

public String processUpload(ValueChangeEvent event) {
    if (attachCaneled == false) {
        UIComponent component = event.getComponent();
        Object newValue = event.getNewValue();
        Object oldValue = event.getOldValue();
        PhaseId phaseId = event.getPhaseId();
        Object source = event.getSource();

        if (newValue instanceof String)
            return "";
        if (newValue == null)
            return "";

        try {//from w w  w  .j a  v a2 s.c o m
            FileItem item = (FileItem) event.getNewValue();
            String fileName = item.getName();
            byte[] fileContents = item.get();

            ResourcePropertiesEdit props = contentHostingService.newResourceProperties();

            String tempS = fileName;
            //logger.info(tempS);
            int lastSlash = tempS.lastIndexOf("/") > tempS.lastIndexOf("\\") ? tempS.lastIndexOf("/")
                    : tempS.lastIndexOf("\\");
            if (lastSlash > 0)
                fileName = tempS.substring(lastSlash + 1);

            ContentResource thisAttach = contentHostingService.addAttachmentResource(fileName,
                    item.getContentType(), fileContents, props);

            SyllabusAttachment attachObj = syllabusManager.createSyllabusAttachmentObject(thisAttach.getId(),
                    fileName);
            ////////revise        syllabusManager.addSyllabusAttachToSyllabusData(getEntry().getEntry(), attachObj);
            attachments.add(attachObj);

            String ss = thisAttach.getUrl();
            String fileWithWholePath = thisAttach.getUrl();

            String s = ss;

            if (entry.justCreated != true) {
                allAttachments.add(attachObj);
            }
        } catch (Exception e) {
            logger.error(this + ".processUpload() in SyllabusTool " + e);
            e.printStackTrace();
        }
        if (entry.justCreated == true) {
            return "edit";
        } else {
            return "read";
        }
    }
    return null;
}

From source file:org.sakaiproject.util.ParameterParser.java

/**
 * Get a FileItem parameter by name.//  w ww  .  j  av a 2 s. c  o  m
 * 
 * @param name
 *        The parameter name.
 * @return The parameter FileItem value, or null if it's not defined.
 */
public FileItem getFileItem(String name) {
    // wrap the Apache FileItem in our own homegrown FileItem
    Object o = m_req.getAttribute(name);
    if (o != null && o instanceof org.apache.commons.fileupload.FileItem) {
        org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) o;
        try {
            return new FileItem(Normalizer.normalize(item.getName(), Normalizer.Form.NFC),
                    item.getContentType(), item.getInputStream());
        } catch (IOException e) {
            return new FileItem(Normalizer.normalize(item.getName(), Normalizer.Form.NFC),
                    item.getContentType(), item.get());
        }
    }

    return null;
}

From source file:org.sakaiproject.yaft.tool.YaftTool.java

private List<Attachment> getAttachments(HttpServletRequest request) {
    List<FileItem> fileItems = new ArrayList<FileItem>();

    String uploadsDone = (String) request.getAttribute(RequestFilter.ATTR_UPLOADS_DONE);

    if (uploadsDone != null && uploadsDone.equals(RequestFilter.ATTR_UPLOADS_DONE)) {
        logger.debug("UPLOAD STATUS: " + request.getAttribute("upload.status"));

        try {// w  w  w .j  a  va 2 s . co m
            FileItem attachment1 = (FileItem) request.getAttribute("attachment_0");
            if (attachment1 != null && attachment1.getSize() > 0)
                fileItems.add(attachment1);
            FileItem attachment2 = (FileItem) request.getAttribute("attachment_1");
            if (attachment2 != null && attachment2.getSize() > 0)
                fileItems.add(attachment2);
            FileItem attachment3 = (FileItem) request.getAttribute("attachment_2");
            if (attachment3 != null && attachment3.getSize() > 0)
                fileItems.add(attachment3);
            FileItem attachment4 = (FileItem) request.getAttribute("attachment_3");
            if (attachment4 != null && attachment4.getSize() > 0)
                fileItems.add(attachment4);
            FileItem attachment5 = (FileItem) request.getAttribute("attachment_4");
            if (attachment5 != null && attachment5.getSize() > 0)
                fileItems.add(attachment5);
        } catch (Exception e) {

        }
    }

    List<Attachment> attachments = new ArrayList<Attachment>();
    if (fileItems.size() > 0) {
        for (Iterator i = fileItems.iterator(); i.hasNext();) {
            FileItem fileItem = (FileItem) i.next();

            String name = fileItem.getName();

            if (name.contains("/"))
                name = name.substring(name.lastIndexOf("/") + 1);
            else if (name.contains("\\"))
                name = name.substring(name.lastIndexOf("\\") + 1);

            attachments.add(new Attachment(name, fileItem.getContentType(), fileItem.get()));
        }
    }

    return attachments;
}

From source file:org.seasar.cubby.controller.impl.MultipartRequestParserImplMultipartRequestTest.java

@Test
public void getParameterMap() throws Exception {
    final PartSource filePartSource = new ByteArrayPartSource("upload.txt", "upload test".getBytes("UTF-8"));
    final PostMethod method = new PostMethod();
    final Part[] parts = new Part[] { new StringPart("a", "12345"), new StringPart("b", "abc"),
            new StringPart("b", "def"), new FilePart("file", filePartSource) };
    this.entity = new MultipartRequestEntity(parts, method.getParams());
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    this.entity.writeRequest(out);
    out.flush();//from w w  w .ja  v a 2  s  . co  m
    out.close();
    this.input = new ByteArrayInputStream(out.toByteArray());
    this.attributes.put("c", new String[] { "999" });

    final Map<String, Object[]> parameterMap = requestParser.getParameterMap(request);
    assertEquals("parameterMap.size()", 4, parameterMap.size());
    final Object[] a = parameterMap.get("a");
    assertEquals("a.length", 1, a.length);
    assertEquals("a[0]", "12345", a[0]);
    final Object[] b = parameterMap.get("b");
    assertEquals("b.length", 2, b.length);
    assertEquals("b[0]", "abc", b[0]);
    assertEquals("b[1]", "def", b[1]);
    final Object[] c = parameterMap.get("c");
    assertEquals("c.length", 1, c.length);
    assertEquals("c[0]", "999", c[0]);
    final Object[] file = parameterMap.get("file");
    assertEquals("file.length", 1, file.length);
    assertTrue("file[0]", file[0] instanceof FileItem);
    final FileItem item = (FileItem) file[0];
    assertEquals("upload test", new String(item.get(), "UTF-8"));
}

From source file:org.seasar.cubby.converter.impl.ByteArrayFileItemConverter.java

/**
 * {@inheritDoc}/*  w  w w .  j  a  va2s  . co  m*/
 * <p>
 * ??{@link FileItem}????byte????
 * </p>
 * 
 * @return ??{@link FileItem}???? byte ?
 * @see FileItem#get()
 */
@Override
protected Object convert(final FileItem fileItem) {
    return fileItem.get();
}

From source file:org.seasr.meandre.components.tools.text.io.InputData.java

@SuppressWarnings("unchecked")
@Override//w ww.  j  a v a 2  s .  co  m
public void handle(HttpServletRequest request, HttpServletResponse response) throws WebUIException {
    console.entering(getClass().getName(), "handle", response);

    console.finer("Request method:\t" + request.getMethod());
    console.finer("Request content-type:\t" + request.getContentType());
    console.finer("Request path:\t" + request.getPathInfo());
    console.finer("Request query string:\t" + request.getQueryString());

    response.setStatus(HttpServletResponse.SC_OK);

    String action = request.getParameter("action");
    console.fine("Action: " + action);

    if (action != null) {
        StreamInitiator si = new StreamInitiator(streamId);
        StreamTerminator st = new StreamTerminator(streamId);

        if (action.equals("urls")) {
            SortedMap<String, URL> urls = new TreeMap<String, URL>();
            Enumeration<String> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                if (paramName.startsWith("url_")) {
                    String sUrl = request.getParameter(paramName);
                    console.fine(paramName + ": " + sUrl);
                    try {
                        urls.put(paramName, new URL(sUrl));
                    } catch (MalformedURLException e) {
                        console.warning(sUrl + " is not a valid URL, ignoring it.");
                        continue;
                    }
                }
            }

            if (urls.size() == 0)
                throw new WebUIException("No URLs provided");

            try {
                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, si);
                    componentContext.pushDataComponentToOutput(OUT_DATA, si);
                }

                for (URL url : urls.values()) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL,
                            BasicDataTypesTools.stringToStrings(url.toString()));
                    componentContext.pushDataComponentToOutput(OUT_DATA, url);
                }

                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, st);
                    componentContext.pushDataComponentToOutput(OUT_DATA, st);
                }
            } catch (ComponentContextException e) {
                throw new WebUIException(e);
            }
        }

        else

        if (action.equals("text")) {
            String text = request.getParameter("text");
            if (text == null || text.length() == 0)
                throw new WebUIException("No text provided");

            try {
                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, si);
                    componentContext.pushDataComponentToOutput(OUT_DATA, si);
                }

                componentContext.pushDataComponentToOutput(OUT_LABEL,
                        BasicDataTypesTools.stringToStrings("text_input"));
                componentContext.pushDataComponentToOutput(OUT_DATA, text);

                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, st);
                    componentContext.pushDataComponentToOutput(OUT_DATA, st);
                }
            } catch (ComponentContextException e) {
                throw new WebUIException(e);
            }
        }

        else

        if (action.equals("upload")) {
            if (!ServletFileUpload.isMultipartContent(request))
                throw new WebUIException("File upload request needs to be done using a multipart content type");

            ServletFileUpload fileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> uploadedFiles;
            try {
                uploadedFiles = fileUpload.parseRequest(request);
            } catch (FileUploadException e) {
                throw new WebUIException(e);
            }

            try {
                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, si);
                    componentContext.pushDataComponentToOutput(OUT_DATA, si);
                }

                for (FileItem file : uploadedFiles) {
                    if (file == null || !file.getFieldName().startsWith("file_"))
                        continue;

                    console.fine("isFormField:\t" + file.isFormField());
                    console.fine("fieldName:\t" + file.getFieldName());
                    console.fine("name:\t" + file.getName());
                    console.fine("contentType:\t" + file.getContentType());
                    console.fine("size:\t" + file.getSize());

                    if (file.isFormField())
                        continue;

                    Strings label = BasicDataTypesTools.stringToStrings(file.getName());
                    Bytes data = BasicDataTypesTools.byteArrayToBytes(file.get());

                    componentContext.pushDataComponentToOutput(OUT_LABEL, label);
                    componentContext.pushDataComponentToOutput(OUT_DATA, data);
                }

                if (_wrapAsStream) {
                    componentContext.pushDataComponentToOutput(OUT_LABEL, st);
                    componentContext.pushDataComponentToOutput(OUT_DATA, st);
                }
            } catch (ComponentContextException e) {
                throw new WebUIException(e);
            }
        }

        else
            throw new WebUIException("Unknown action: " + action);

        _done = true;
        try {
            response.getWriter().println(
                    "<html><head><meta http-equiv='REFRESH' content='1;url=/'></head><body></body></html>");
        } catch (IOException e) {
            throw new WebUIException(e);
        }
    } else
        emptyRequest(response);

    console.exiting(getClass().getName(), "handle");
}

From source file:org.signserver.web.GenericProcessServlet.java

/**
 * Handles http post.//from w  ww. ja  v a2 s.  c  om
 *
 * @param req servlet request
 * @param res servlet response
 *
 * @throws IOException input/output error
 * @throws ServletException error
 */
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    LOG.debug(">doPost()");

    int workerId = 1;
    byte[] data = null;
    String fileName = null;
    String pdfPassword = null;
    boolean workerRequest = false;

    if (LOG.isDebugEnabled()) {
        LOG.debug("Received a request with length: " + req.getContentLength());
    }

    final String workerNameOverride = (String) req.getAttribute(WORKERNAME_PROPERTY_OVERRIDE);

    if (workerNameOverride != null) {
        workerId = getWorkerSession().getWorkerId(workerNameOverride);
        workerRequest = true;
    }

    final long maxUploadSize = getMaxUploadSize();

    ProcessType processType = ProcessType.signDocument;
    final MetaDataHolder metadataHolder = new MetaDataHolder();

    if (ServletFileUpload.isMultipartContent(req)) {
        final DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(Integer.MAX_VALUE); // Don't write to disk

        final ServletFileUpload upload = new ServletFileUpload(factory);

        // Limit the maximum size of input
        upload.setSizeMax(maxUploadSize);

        try {
            final List items = upload.parseRequest(req);
            final Iterator iter = items.iterator();
            FileItem fileItem = null;
            String encoding = null;
            while (iter.hasNext()) {
                final Object o = iter.next();
                if (o instanceof FileItem) {
                    final FileItem item = (FileItem) o;

                    if (item.isFormField()) {
                        if (!workerRequest) {
                            if (WORKERNAME_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerName in the request: " + item.getString());
                                }
                                workerId = getWorkerSession().getWorkerId(item.getString());
                            } else if (WORKERID_PROPERTY_NAME.equals(item.getFieldName())) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Found a signerId in the request: " + item.getString());
                                }
                                try {
                                    workerId = Integer.parseInt(item.getString());
                                } catch (NumberFormatException ignored) {
                                }
                            }
                        }

                        final String itemFieldName = item.getFieldName();

                        if (PDFPASSWORD_PROPERTY_NAME.equals(itemFieldName)) {
                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found a pdfPassword in the request.");
                            }
                            pdfPassword = item.getString("ISO-8859-1");
                        } else if (PROCESS_TYPE_PROPERTY_NAME.equals(itemFieldName)) {
                            final String processTypeAttribute = item.getString("ISO-8859-1");

                            if (LOG.isDebugEnabled()) {
                                LOG.debug("Found process type in the request: " + processTypeAttribute);
                            }

                            if (processTypeAttribute != null) {
                                try {
                                    processType = ProcessType.valueOf(processTypeAttribute);
                                } catch (IllegalArgumentException e) {
                                    sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                                    return;
                                }
                            } else {
                                processType = ProcessType.signDocument;
                            }
                        } else if (ENCODING_PROPERTY_NAME.equals(itemFieldName)) {
                            encoding = item.getString("ISO-8859-1");
                        } else if (isFieldMatchingMetaData(itemFieldName)) {
                            try {
                                metadataHolder.handleMetaDataProperty(itemFieldName,
                                        item.getString("ISO-8859-1"));
                            } catch (IOException e) {
                                sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                                return;
                            }
                        }
                    } else {
                        // We only care for one upload at a time right now
                        if (fileItem == null) {
                            fileItem = item;
                        }
                    }
                }
            }

            if (fileItem == null) {
                sendBadRequest(res, "Missing file content in upload");
                return;
            } else {
                fileName = fileItem.getName();
                data = fileItem.get(); // Note: Reads entiry file to memory

                if (encoding != null && !encoding.isEmpty()) {
                    if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                        if (LOG.isDebugEnabled()) {
                            LOG.debug("Decoding base64 data");
                        }
                        data = Base64.decode(data);
                    } else {
                        sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                        return;
                    }
                }
            }
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            LOG.error(HTTP_MAX_UPLOAD_SIZE + " exceeded: " + ex.getLocalizedMessage());
            res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                    "Maximum content length is " + maxUploadSize + " bytes");
            return;
        } catch (FileUploadException ex) {
            throw new ServletException("Upload failed", ex);
        }
    } else {
        if (!workerRequest) {
            String name = req.getParameter(WORKERNAME_PROPERTY_NAME);
            if (name != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerName in the request: " + name);
                }
                workerId = getWorkerSession().getWorkerId(name);
            }
            String id = req.getParameter(WORKERID_PROPERTY_NAME);
            if (id != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a signerId in the request: " + id);
                }
                workerId = Integer.parseInt(id);
            }
        }

        final Enumeration<String> params = req.getParameterNames();

        while (params.hasMoreElements()) {
            final String property = params.nextElement();
            if (PDFPASSWORD_PROPERTY_NAME.equals(property)) {
                pdfPassword = (String) req.getParameter(PDFPASSWORD_PROPERTY_NAME);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found a pdfPassword in the request.");
                }
            } else if (isFieldMatchingMetaData(property)) {
                try {
                    metadataHolder.handleMetaDataProperty(property, req.getParameter(property));
                } catch (IOException e) {
                    sendBadRequest(res, "Malformed properties given using REQUEST_METADATA.");
                    return;
                }
            }
        }

        final String processTypeAttribute = (String) req.getParameter(PROCESS_TYPE_PROPERTY_NAME);

        if (processTypeAttribute != null) {
            try {
                processType = ProcessType.valueOf(processTypeAttribute);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Found process type in the request: " + processType.name());
                }
            } catch (IllegalArgumentException e) {
                sendBadRequest(res, "Illegal process type: " + processTypeAttribute);
                return;
            }
        } else {
            processType = ProcessType.signDocument;
        }

        if (METHOD_GET.equalsIgnoreCase(req.getMethod())
                || (req.getContentType() != null && req.getContentType().contains(FORM_URL_ENCODED))) {
            LOG.debug("Request is FORM_URL_ENCODED");

            if (req.getParameter(DATA_PROPERTY_NAME) == null) {
                sendBadRequest(res, "Missing field 'data' in request");
                return;
            }
            data = req.getParameter(DATA_PROPERTY_NAME).getBytes();

            String encoding = req.getParameter(ENCODING_PROPERTY_NAME);
            if (encoding != null && !encoding.isEmpty()) {
                if (ENCODING_BASE64.equalsIgnoreCase(encoding)) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Decoding base64 data");
                    }
                    data = Base64.decode(data);
                } else {
                    sendBadRequest(res, "Unknown encoding for the 'data' field: " + encoding);
                    return;
                }
            }
        } else {
            // Pass-through the content to be handled by worker if
            // unknown content-type
            if (LOG.isDebugEnabled()) {
                LOG.debug("Request Content-type: " + req.getContentType());
            }

            // Get an input stream and read the bytes from the stream
            InputStream in = req.getInputStream();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            in.close();
            os.close();
            data = os.toByteArray();
        }
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Request of type: " + processType.name());
    }

    // Limit the maximum size of input
    if (data.length > maxUploadSize) {
        LOG.error("Content length exceeds " + maxUploadSize + ", not processed: " + req.getContentLength());
        res.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE,
                "Maximum content length is " + maxUploadSize + " bytes");
    } else {
        processRequest(req, res, workerId, data, fileName, pdfPassword, processType, metadataHolder);
    }

    LOG.debug("<doPost()");
}

From source file:org.soaplab.clients.spinet.ServiceController.java

/*************************************************************************
 *
 *************************************************************************/
@SuppressWarnings("unchecked")
private Map<String, Object> retrieveParameters() throws SoaplabException {

    if (request == null) {
        String msg = "Request is null. Strange... Probably an internal error.";
        log.error(msg);//  w  w w  . j  a  va 2  s.co  m
        throw new SoaplabException(msg);
    }

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

    // check that we have a file upload request
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (isMultipart) {
        try {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                String name = item.getFieldName();
                // String value = item.getString ("UTF-8");
                // params.put (name, value);
                if (item.isFormField()) {
                    params.put(name, item.getString("UTF-8"));
                } else {
                    byte[] value = item.get();
                    if (value != null && value.length > 0) {
                        params.put(name, value);
                    }
                }
            }
        } catch (Exception e) {
            throw new SoaplabException(e.getMessage(), e);
        }

    } else {
        for (Enumeration en = request.getParameterNames(); en.hasMoreElements();) {
            String name = (String) en.nextElement();
            String value = request.getParameter(name);
            params.put(name, value);
        }
    }

    // some request params are not inputs
    setServiceName((String) params.get("serviceName"));
    setJobElementId((String) params.get("jobElementId"));
    return params;
}

From source file:org.tolven.ajax.DocServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(4096);//from   w  ww .ja va2 s.c  o  m
    //  Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);
    Writer writer = response.getWriter();
    // Parse the request
    String returnTo = null;
    try {
        List<FileItem> items = upload.parseRequest(request);
        long id = 0;
        for (FileItem item : items) {
            if (item.isFormField()) {
                String name = item.getFieldName();
                String value = item.getString();
                if ("returnTo".equals(name))
                    returnTo = value;
            } else {
                String contentType = item.getContentType();
                boolean isInMemory = item.isInMemory();
                // TODO less than int bytes 
                int sizeInBytes = (int) item.getSize();
                AccountUser accountUser = TolvenRequest.getInstance().getAccountUser();
                DocBase doc = docBean.createNewDocument(contentType, "", accountUser);
                // Get the logged in user and set as the author
                Object obj = request.getSession().getAttribute(GeneralSecurityFilter.ACCOUNT_ID);
                if (obj == null)
                    throw new IllegalStateException(getClass() + ": Session ACCOUNT_ID is null");
                obj = request.getSession().getAttribute(GeneralSecurityFilter.TOLVENUSER_ID);
                if (obj == null)
                    throw new IllegalStateException(getClass() + ": Session TOLVENUSER_ID is null");
                String kbeKeyAlgorithm = propertyBean.getProperty(DocumentSecretKey.DOC_KBE_KEY_ALGORITHM_PROP);
                int kbeKeyLength = Integer
                        .parseInt(propertyBean.getProperty(DocumentSecretKey.DOC_KBE_KEY_LENGTH));

                if (isInMemory) {
                    doc.setAsEncryptedContent(item.get(), kbeKeyAlgorithm, kbeKeyLength);
                } else {
                    InputStream uploadedStream = item.getInputStream();
                    byte[] b = new byte[sizeInBytes];
                    uploadedStream.read(b);
                    doc.setAsEncryptedContent(b, kbeKeyAlgorithm, kbeKeyLength);
                    uploadedStream.close();
                }
                docBean.finalizeDocument(doc);
            }
            //             writer.write( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<html>\n" +
            writer.write("<html>\n" + "<head>"
                    + (returnTo == null ? " "
                            : "<meta http-equiv=\"refresh\" content=\"0; url=" + returnTo + "\"/>")
                    + "</head><body>\n" + id + "\n</body>\n</html>\n");
        }
    } catch (FileUploadException e) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        e.printStackTrace();
    } finally {
        request.setAttribute("activeWriter", writer);
        //         writer.close();
    }
}

From source file:org.tolven.web.MenuAction.java

/**
 * Add an attachment to the current menudataItem 
 * @return success/*from  w  w  w .  j a va2s  . c o  m*/
 * @throws Exception 
 */
public String addAttachment() throws Exception {
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();
    FileItem upfile = (FileItem) request.getAttribute("upfile");
    if (upfile == null)
        return "fail";
    String contentType = upfile.getContentType();
    TolvenLogger.info("Upload, contentType: " + contentType, MenuAction.class);
    boolean isInMemory = upfile.isInMemory();
    int sizeInBytes = (int) upfile.getSize();
    DocBase doc = getDocumentLocal().createNewDocument(contentType, getAttachmentType(),
            TolvenRequest.getInstance().getAccountUser());
    doc.setSchemaURI(getAttachmentType());
    byte[] b;
    if (isInMemory) {
        b = upfile.get();
    } else {
        InputStream uploadedStream = upfile.getInputStream();
        b = new byte[sizeInBytes];
        uploadedStream.read(b);
        uploadedStream.close();
    }
    String kbeKeyAlgorithm = getTolvenPropertiesBean()
            .getProperty(DocumentSecretKey.DOC_KBE_KEY_ALGORITHM_PROP);
    int kbeKeyLength = Integer
            .parseInt(getTolvenPropertiesBean().getProperty(DocumentSecretKey.DOC_KBE_KEY_LENGTH));
    doc.setAsEncryptedContent(b, kbeKeyAlgorithm, kbeKeyLength);
    getDocBean().createFinalDocument(doc);
    getDocumentLocal().createAttachment(getDrilldownItemDoc(), doc, getAttachmentDescription(),
            TolvenRequest.getInstance().getAccountUser(), getNow());

    setAttachmentDescription(null);
    return "success";
}