Example usage for org.apache.commons.fileupload FileItemStream getContentType

List of usage examples for org.apache.commons.fileupload FileItemStream getContentType

Introduction

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

Prototype

String getContentType();

Source Link

Document

Returns the content type passed by the browser or null if not defined.

Usage

From source file:de.kp.ames.web.function.upload.UploadServiceImpl.java

public void doSetRequest(RequestContext ctx) {

    /*/*from  www. ja  v a  2s  . co  m*/
     * The result of the upload request, returned
     * to the requestor; note, that the result must
     * be a text response
     */
    boolean result = false;
    HttpServletRequest request = ctx.getRequest();

    try {

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {

            /* 
             * Create new file upload handler
             */
            ServletFileUpload upload = new ServletFileUpload();

            /*
             * Parse the request
             */
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {

                FileItemStream fileItem = iter.next();
                if (fileItem.isFormField()) {
                    // not supported

                } else {

                    /* 
                     * Hook into the upload request to some virus scanning
                     * using the scanner factory of this application
                     */

                    byte[] bytes = FileUtil.getByteArrayFromInputStream(fileItem.openStream());
                    boolean checked = MalwareScanner.scanForViruses(bytes);

                    if (checked) {

                        String item = this.method.getAttribute(MethodConstants.ATTR_ITEM);
                        String type = this.method.getAttribute(MethodConstants.ATTR_TYPE);
                        if ((item == null) || (type == null)) {
                            this.sendNotImplemented(ctx);

                        } else {

                            String fileName = FilenameUtils.getName(fileItem.getName());
                            String mimeType = fileItem.getContentType();

                            try {
                                result = upload(item, type, fileName, mimeType, bytes);

                            } catch (Exception e) {
                                sendBadRequest(ctx, e);

                            }

                        }

                    }

                }

            }

        }

        /*
         * Send html response
         */
        if (result == true) {
            this.sendHTMLResponse(createHtmlSuccess(), ctx.getResponse());

        } else {
            this.sendHTMLResponse(createHtmlFailure(), ctx.getResponse());

        }

    } catch (Exception e) {
        this.sendBadRequest(ctx, e);

    } finally {
    }

}

From source file:com.pronoiahealth.olhie.server.rest.BookAssetUploadServiceImpl.java

/**
 * Receive an upload book assest/*  ww w.ja v  a 2s  . c o  m*/
 * 
 * @see com.pronoiahealth.olhie.server.rest.BookAssetUploadService#process2(javax.servlet.http.HttpServletRequest)
 */
@Override
@POST
@Path("/upload2")
@Produces("text/html")
@SecureAccess({ SecurityRoleEnum.ADMIN, SecurityRoleEnum.AUTHOR })
public String process2(@Context HttpServletRequest req)
        throws ServletException, IOException, FileUploadException {
    try {
        // Check that we have a file upload request
        boolean isMultipart = ServletFileUpload.isMultipartContent(req);
        if (isMultipart == true) {

            // FileItemFactory fileItemFactory = new FileItemFactory();
            String description = null;
            String descriptionDetail = null;
            String hoursOfWorkStr = null;
            String bookId = null;
            String action = null;
            String dataType = null;
            String contentType = null;
            //String data = null;
            byte[] bytes = null;
            String fileName = null;
            long size = 0;
            ServletFileUpload fileUpload = new ServletFileUpload();
            fileUpload.setSizeMax(FILE_SIZE_LIMIT);
            FileItemIterator iter = fileUpload.getItemIterator(req);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if (item.isFormField()) {
                    // description
                    if (item.getFieldName().equals("description")) {
                        description = Streams.asString(stream);
                    }

                    // detail
                    if (item.getFieldName().equals("descriptionDetail")) {
                        descriptionDetail = Streams.asString(stream);
                    }

                    // Work hours
                    if (item.getFieldName().equals("hoursOfWork")) {
                        hoursOfWorkStr = Streams.asString(stream);
                    }

                    // BookId
                    if (item.getFieldName().equals("bookId")) {
                        bookId = Streams.asString(stream);
                    }

                    // action
                    if (item.getFieldName().equals("action")) {
                        action = Streams.asString(stream);
                    }

                    // datatype
                    if (item.getFieldName().equals("dataType")) {
                        dataType = Streams.asString(stream);
                    }

                } else {
                    if (item != null) {
                        contentType = item.getContentType();
                        fileName = item.getName();
                        item.openStream();
                        InputStream in = item.openStream();
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        IOUtils.copy(in, bos);
                        bytes = bos.toByteArray();
                        size = bytes.length;
                    }
                }
            }

            // convert the hoursOfWork
            int hoursOfWork = 0;
            if (hoursOfWorkStr != null) {
                try {
                    hoursOfWork = Integer.parseInt(hoursOfWorkStr);
                } catch (Exception e) {
                    log.log(Level.WARNING, "Could not conver " + hoursOfWorkStr
                            + " to an int in BookAssetUploadServiceImpl. Converting to 0.");
                    hoursOfWork = 0;
                }
            }

            // Verify that the session user is the author or co-author of
            // the book. They would be the only ones who could add to the
            // book.
            String userId = userToken.getUserId();
            boolean isAuthor = bookDAO.isUserAuthorOrCoauthorOfBook(userId, bookId);
            if (isAuthor == false) {
                throw new Exception("The user " + userId + " is not the author or co-author of the book.");
            }

            // Add to the database
            bookDAO.addUpdateBookassetBytes(description, descriptionDetail, bookId, contentType,
                    BookAssetDataType.valueOf(dataType).toString(), bytes, action, fileName, null, null, size,
                    hoursOfWork, userId);

            // Tell Solr about the update
            queueBookEvent.fire(new QueueBookEvent(bookId, userId));
        }
        return "OK";
    } catch (Exception e) {
        log.log(Level.SEVERE, "Throwing servlet exception for unhandled exception", e);
        // return "ERROR:\n" + e.getMessage();

        if (e instanceof FileUploadException) {
            throw (FileUploadException) e;
        } else {
            throw new FileUploadException(e.getMessage());
        }
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java

/**
 * Adds the resource content with language <code>language</code> to the
 * specified resource./*  w  w w.java  2  s  . co  m*/
 * 
 * @param request
 *          the request
 * @param resourceId
 *          the resource identifier
 * @param languageId
 *          the language identifier
 * @param is
 *          the input stream
 * @return the resource
 */
@POST
@Path("/{resource}/content/{language}")
@Produces(MediaType.MEDIA_TYPE_WILDCARD)
public Response addFileContent(@Context HttpServletRequest request, @PathParam("resource") String resourceId,
        @PathParam("language") String languageId) {

    Site site = getSite(request);

    // Check the parameters
    if (resourceId == null)
        throw new WebApplicationException(Status.BAD_REQUEST);

    // Extract the language
    Language language = LanguageUtils.getLanguage(languageId);
    if (language == null) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }

    // Get the resource
    Resource<?> resource = loadResource(request, resourceId, null);
    if (resource == null || resource.contents().isEmpty()) {
        throw new WebApplicationException(Status.NOT_FOUND);
    }

    String fileName = null;
    String mimeType = null;
    File uploadedFile = null;

    try {
        // Multipart form encoding?
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ServletFileUpload payload = new ServletFileUpload();
                for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) {
                    FileItemStream item = iter.next();
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String fieldValue = Streams.asString(item.openStream());
                        if (StringUtils.isBlank(fieldValue))
                            continue;
                        if (OPT_MIMETYPE.equals(fieldName)) {
                            mimeType = fieldValue;
                        }
                    } else {
                        // once the body gets read iter.hasNext must not be invoked
                        // or the stream can not be read
                        fileName = StringUtils.trim(item.getName());
                        mimeType = StringUtils.trim(item.getContentType());
                        uploadedFile = File.createTempFile("upload-", null);
                        FileOutputStream fos = new FileOutputStream(uploadedFile);
                        try {
                            IOUtils.copy(item.openStream(), fos);
                        } catch (IOException e) {
                            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
                        } finally {
                            IOUtils.closeQuietly(fos);
                        }
                    }
                }
            } catch (FileUploadException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            }
        }

        // Octet binary stream
        else {
            try {
                fileName = StringUtils.trimToNull(request.getHeader("X-File-Name"));
                mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE));
            } catch (UnknownLanguageException e) {
                throw new WebApplicationException(Status.BAD_REQUEST);
            }
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = request.getInputStream();
                if (is == null)
                    throw new WebApplicationException(Status.BAD_REQUEST);
                uploadedFile = File.createTempFile("upload-", null);
                fos = new FileOutputStream(uploadedFile);
                IOUtils.copy(is, fos);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }

        }
        // Has there been a file in the request?
        if (uploadedFile == null)
            throw new WebApplicationException(Status.BAD_REQUEST);

        // A mime type would be nice as well
        if (StringUtils.isBlank(mimeType)) {
            mimeType = detectMimeTypeFromFile(fileName, uploadedFile);
            if (mimeType == null)
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }

        // Get the current user
        User user = securityService.getUser();
        if (user == null)
            throw new WebApplicationException(Status.UNAUTHORIZED);

        // Make sure the user has editing rights
        if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR))
            throw new WebApplicationException(Status.UNAUTHORIZED);

        // Try to create the resource content
        InputStream is = null;
        ResourceContent content = null;
        ResourceContentReader<?> reader = null;
        ResourceSerializer<?, ?> serializer = serializerService
                .getSerializerByType(resource.getURI().getType());
        try {
            reader = serializer.getContentReader();
            is = new FileInputStream(uploadedFile);
            content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType);
        } catch (IOException e) {
            logger.warn("Error reading resource content {} from request", resource.getURI());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (ParserConfigurationException e) {
            logger.warn("Error configuring parser to read resource content {}: {}", resource.getURI(),
                    e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (SAXException e) {
            logger.warn("Error parsing udpated resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.BAD_REQUEST);
        } finally {
            IOUtils.closeQuietly(is);
        }

        URI uri = null;
        WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site,
                true);
        try {
            is = new FileInputStream(uploadedFile);
            resource = contentRepository.putContent(resource.getURI(), content, is);
            uri = new URI(resource.getURI().getIdentifier());
        } catch (IOException e) {
            logger.warn("Error writing content to resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IllegalStateException e) {
            logger.warn("Illegal state while adding content to resource {}: {}", resource.getURI(),
                    e.getMessage());
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
        } catch (ContentRepositoryException e) {
            logger.warn("Error adding content to resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (URISyntaxException e) {
            logger.warn("Error creating a uri for resource {}: {}", resource.getURI(), e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
        }

        // Create the response
        ResponseBuilder response = Response.created(uri);
        response.type(MediaType.MEDIA_TYPE_WILDCARD);
        response.tag(ResourceUtils.getETagValue(resource));
        response.lastModified(ResourceUtils.getModificationDate(resource, language));
        return response.build();

    } finally {
        FileUtils.deleteQuietly(uploadedFile);
    }
}

From source file:cn.webwheel.ActionSetter.java

@SuppressWarnings("unchecked")
public Object[] set(Object action, ActionInfo ai, HttpServletRequest request) throws IOException {
    SetterConfig cfg = ai.getSetterConfig();
    List<SetterInfo> setters;
    if (action != null) {
        Class cls = action.getClass();
        setters = setterMap.get(cls);/*ww w.  ja v  a2 s .  c  o  m*/
        if (setters == null) {
            synchronized (this) {
                setters = setterMap.get(cls);
                if (setters == null) {
                    Map<Class, List<SetterInfo>> map = new HashMap<Class, List<SetterInfo>>(setterMap);
                    map.put(cls, setters = parseSetters(cls));
                    setterMap = map;
                }
            }
        }
    } else {
        setters = Collections.emptyList();
    }

    List<SetterInfo> args = argMap.get(ai.actionMethod);
    if (args == null) {
        synchronized (this) {
            args = argMap.get(ai.actionMethod);
            if (args == null) {
                Map<Method, List<SetterInfo>> map = new HashMap<Method, List<SetterInfo>>(argMap);
                map.put(ai.actionMethod, args = parseArgs(ai.actionMethod));
                argMap = map;
            }
        }
    }

    if (setters.isEmpty() && args.isEmpty())
        return new Object[0];

    Map<String, Object> params;
    try {
        if (cfg.getCharset() != null) {
            request.setCharacterEncoding(cfg.getCharset());
        }
    } catch (UnsupportedEncodingException e) {
        //
    }

    if (ServletFileUpload.isMultipartContent(request)) {
        params = new HashMap<String, Object>(request.getParameterMap());
        request.setAttribute(WRPName, params);
        ServletFileUpload fileUpload = new ServletFileUpload();
        if (cfg.getCharset() != null) {
            fileUpload.setHeaderEncoding(cfg.getCharset());
        }
        if (cfg.getFileUploadSizeMax() != 0) {
            fileUpload.setSizeMax(cfg.getFileUploadSizeMax());
        }
        if (cfg.getFileUploadFileSizeMax() != 0) {
            fileUpload.setFileSizeMax(cfg.getFileUploadFileSizeMax());
        }
        boolean throwe = false;
        try {
            FileItemIterator it = fileUpload.getItemIterator(request);
            while (it.hasNext()) {
                FileItemStream fis = it.next();
                if (fis.isFormField()) {
                    String s = Streams.asString(fis.openStream(), cfg.getCharset());
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new String[] { s });
                    } else if (o instanceof String[]) {
                        String[] ss = (String[]) o;
                        String[] nss = new String[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = s;
                        params.put(fis.getFieldName(), nss);
                    }
                } else if (!fis.getName().isEmpty()) {
                    File tempFile;
                    try {
                        tempFile = File.createTempFile("wfu", null);
                    } catch (IOException e) {
                        throwe = true;
                        throw e;
                    }
                    FileExImpl fileEx = new FileExImpl(tempFile);
                    Object o = params.get(fis.getFieldName());
                    if (o == null) {
                        params.put(fis.getFieldName(), new FileEx[] { fileEx });
                    } else if (o instanceof FileEx[]) {
                        FileEx[] ss = (FileEx[]) o;
                        FileEx[] nss = new FileEx[ss.length + 1];
                        System.arraycopy(ss, 0, nss, 0, ss.length);
                        nss[ss.length] = fileEx;
                        params.put(fis.getFieldName(), nss);
                    }
                    Streams.copy(fis.openStream(), new FileOutputStream(fileEx.getFile()), true);
                    fileEx.fileName = fis.getName();
                    fileEx.contentType = fis.getContentType();
                }
            }
        } catch (FileUploadException e) {
            if (action instanceof FileUploadExceptionAware) {
                ((FileUploadExceptionAware) action).setFileUploadException(e);
            }
        } catch (IOException e) {
            if (throwe) {
                throw e;
            }
        }
    } else {
        params = request.getParameterMap();
    }

    if (cfg.getSetterPolicy() == SetterPolicy.ParameterAndField
            || (cfg.getSetterPolicy() == SetterPolicy.Auto && args.isEmpty())) {
        for (SetterInfo si : setters) {
            si.setter.set(action, si.member, params, si.paramName);
        }
    }

    Object[] as = new Object[args.size()];
    for (int i = 0; i < as.length; i++) {
        SetterInfo si = args.get(i);
        as[i] = si.setter.set(action, null, params, si.paramName);
    }
    return as;
}

From source file:hk.hku.cecid.corvus.http.PartnershipSenderUnitTest.java

/**
 * A Helper method which assert whether the HTTP content received in the HTTP monitor 
 * is a multi-part form data, with basic-auth and well-formed partnership operation request.
 *///from w  w  w. ja va  2  s  .  co  m
private void assertHttpRequestReceived() throws Exception {
    // Debug print information.
    Map headers = monitor.getHeaders();

    // #0 Assertion
    assertFalse("No HTTP header found in the captured data.", headers.isEmpty());

    Map.Entry tmp = null;
    Iterator itr = null;
    itr = headers.entrySet().iterator();
    logger.info("Header information");
    while (itr.hasNext()) {
        tmp = (Map.Entry) itr.next();
        logger.info(tmp.getKey() + " : " + tmp.getValue());
    }

    // #1 Check BASIC authentication value.
    String basicAuth = (String) headers.get("Authorization");

    // #1 Assertion
    assertNotNull("No Basic Authentication found in the HTTP Header.", basicAuth);

    String[] authToken = basicAuth.split(" ");

    // There are 2 token, one is the "Basic" and another is the base64 auth value.
    assertTrue(authToken.length == 2);
    assertTrue("Missing basic auth prefix 'Basic'", authToken[0].equalsIgnoreCase("Basic"));
    // #1 Decode the base64 authentication value to see whether it is "corvus:corvus".
    String decodedCredential = new String(new BASE64Decoder().decodeBuffer(authToken[1]), "UTF-8");
    assertEquals("Invalid basic auth content", USER_NAME + ":" + PASSWORD, decodedCredential);

    // #2 Check content Type
    String contentType = monitor.getContentType();
    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "multipart/form-data", mediaType);

    // #3 Check the multi-part content.
    // Make a request context that bridge the content from our monitor to FileUpload library.    
    RequestContext rc = new RequestContext() {
        public String getCharacterEncoding() {
            return "charset=ISO-8859-1";
        }

        public int getContentLength() {
            return monitor.getContentLength();
        }

        public String getContentType() {
            return monitor.getContentType();
        }

        public InputStream getInputStream() {
            return monitor.getInputStream();
        }
    };

    FileUpload multipartParser = new FileUpload();
    FileItemIterator item = multipartParser.getItemIterator(rc);
    FileItemStream fstream = null;

    /*
     * For each field in the partnership, we have to check the existence of the 
     * associated field in the HTTP request. Also we check whether the content
     * of that web form field has same data to the field in the partnership.    
     */
    itr = this.target.getPartnershipMapping().entrySet().iterator();
    Map data = ((KVPairData) this.target.properties).getProperties();
    Map.Entry e; // an entry representing the partnership data to web form name mapping.
    String formParamName; // a temporary pointer pointing to the value in the entry.
    Object dataValue; // a temporary pointer pointing to the value in the partnership data.

    while (itr.hasNext()) {
        e = (Map.Entry) itr.next();
        formParamName = (String) e.getValue();
        // Add new part if the mapped key is not null.
        if (formParamName != null) {
            assertTrue("Insufficient number of web form parameter hit.", item.hasNext());
            // Get the next multi-part element.
            fstream = item.next();
            // Assert field name
            assertEquals("Missed web form parameter ?", formParamName, fstream.getFieldName());
            // Assert field content
            dataValue = data.get(e.getKey());
            if (dataValue instanceof String) {
                // Assert content equal.
                assertEquals((String) dataValue, IOHandler.readString(fstream.openStream(), null));
            } else if (dataValue instanceof byte[]) {
                byte[] expectedBytes = (byte[]) dataValue;
                byte[] actualBytes = IOHandler.readBytes(fstream.openStream());
                // Assert byte length equal
                assertEquals(expectedBytes.length, actualBytes.length);
                for (int j = 0; j < expectedBytes.length; j++)
                    assertEquals(expectedBytes[j], actualBytes[j]);
            } else {
                throw new IllegalArgumentException("Invalid content found in multipart.");
            }
            // Log information.
            logger.info("Field name found and verifed: " + fstream.getFieldName() + " content type:"
                    + fstream.getContentType());
        }
    }
    /* Check whether the partnership operation in the HTTP request is expected as i thought */
    assertTrue("Missing request_action ?!", item.hasNext());
    fstream = item.next();
    assertEquals("request_action", fstream.getFieldName());
    // Assert the request_action has same content the operation name.
    Map partnershipOpMap = this.target.getPartnershipOperationMapping();
    assertEquals(partnershipOpMap.get(new Integer(this.target.getExecuteOperation())),
            IOHandler.readString(fstream.openStream(), null));
}

From source file:ch.entwine.weblounge.contentrepository.impl.endpoint.FilesEndpoint.java

/**
 * Creates a file resource at the site's content repository by uploading
 * initial file content and returns the location to post updates to.
 * //from  w w  w  .java 2 s  . co m
 * @param request
 *          the http request
 * @param resourceXml
 *          the new resource
 * @param path
 *          the path to store the resource at
 * @param mimeType
 *          the content mime type
 * @return response the resource location
 */
@POST
@Path("/uploads")
@Produces(MediaType.MEDIA_TYPE_WILDCARD)
public Response uploadFile(@Context HttpServletRequest request) {

    Site site = getSite(request);

    // Make sure the content repository is writable
    if (site.getContentRepository().isReadOnly()) {
        logger.warn("Attempt to write to read-only content repository {}", site);
        throw new WebApplicationException(Status.PRECONDITION_FAILED);
    }

    String fileName = null;
    Language language = null;
    String path = null;
    String mimeType = null;
    File uploadedFile = null;

    try {
        // Multipart form encoding?
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                ServletFileUpload payload = new ServletFileUpload();
                for (FileItemIterator iter = payload.getItemIterator(request); iter.hasNext();) {
                    FileItemStream item = iter.next();
                    String fieldName = item.getFieldName();
                    if (item.isFormField()) {
                        String fieldValue = Streams.asString(item.openStream());
                        if (StringUtils.isBlank(fieldValue))
                            continue;
                        if (OPT_PATH.equals(fieldName)) {
                            path = fieldValue;
                        } else if (OPT_LANGUAGE.equals(fieldName)) {
                            try {
                                language = LanguageUtils.getLanguage(fieldValue);
                            } catch (UnknownLanguageException e) {
                                throw new WebApplicationException(Status.BAD_REQUEST);
                            }
                        } else if (OPT_MIMETYPE.equals(fieldName)) {
                            mimeType = fieldValue;
                        }
                    } else {
                        // once the body gets read iter.hasNext must not be invoked
                        // or the stream can not be read
                        fileName = StringUtils.trim(item.getName());
                        mimeType = StringUtils.trim(item.getContentType());
                        uploadedFile = File.createTempFile("upload-", null);
                        FileOutputStream fos = new FileOutputStream(uploadedFile);
                        try {
                            IOUtils.copy(item.openStream(), fos);
                        } catch (IOException e) {
                            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
                        } finally {
                            IOUtils.closeQuietly(fos);
                        }
                    }
                }

            } catch (FileUploadException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            }
        }

        // Octet binary stream
        else {
            try {
                fileName = StringUtils.trimToNull(request.getHeader("X-File-Name"));
                path = StringUtils.trimToNull(request.getParameter(OPT_PATH));
                mimeType = StringUtils.trimToNull(request.getParameter(OPT_MIMETYPE));
                language = LanguageUtils.getLanguage(request.getParameter(OPT_LANGUAGE));
            } catch (UnknownLanguageException e) {
                throw new WebApplicationException(Status.BAD_REQUEST);
            }

            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = request.getInputStream();
                if (is == null)
                    throw new WebApplicationException(Status.BAD_REQUEST);
                uploadedFile = File.createTempFile("upload-", null);
                fos = new FileOutputStream(uploadedFile);
                IOUtils.copy(is, fos);
            } catch (IOException e) {
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            } finally {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(fos);
            }

        }

        // Has there been a file in the request?
        if (uploadedFile == null)
            throw new WebApplicationException(Status.BAD_REQUEST);

        // Check the filename
        if (fileName == null) {
            logger.warn("No filename found for upload, request header 'X-File-Name' not specified");
            fileName = uploadedFile.getName();
        }

        // Make sure there is a language
        if (language == null) {
            language = LanguageUtils.getPreferredLanguage(request, site);
        }

        // A mime type would be nice as well
        if (StringUtils.isBlank(mimeType)) {
            mimeType = detectMimeTypeFromFile(fileName, uploadedFile);
            if (mimeType == null)
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }

        // Set owner and date created
        User user = securityService.getUser();
        if (user == null)
            throw new WebApplicationException(Status.UNAUTHORIZED);

        // Make sure the user has editing rights
        if (!SecurityUtils.userHasRole(user, SystemRole.EDITOR))
            throw new WebApplicationException(Status.UNAUTHORIZED);

        WritableContentRepository contentRepository = (WritableContentRepository) getContentRepository(site,
                true);

        // Create the resource uri
        URI uri = null;
        InputStream is = null;
        Resource<?> resource = null;
        ResourceURI resourceURI = null;
        logger.debug("Adding resource to {}", resourceURI);
        ResourceSerializer<?, ?> serializer = serializerService.getSerializerByMimeType(mimeType);
        if (serializer == null) {
            logger.debug("No specialized resource serializer found, using regular file serializer");
            serializer = serializerService.getSerializerByType(FileResource.TYPE);
        }

        // Create the resource
        try {
            is = new FileInputStream(uploadedFile);
            resource = serializer.newResource(site, is, user, language);
            resourceURI = resource.getURI();
        } catch (FileNotFoundException e) {
            logger.warn("Error creating resource at {} from image: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
        }

        // If a path has been specified, set it
        if (path != null && StringUtils.isNotBlank(path)) {
            try {
                if (!path.startsWith("/"))
                    path = "/" + path;
                WebUrl url = new WebUrlImpl(site, path);
                resourceURI.setPath(url.getPath());

                // Make sure the resource doesn't exist
                if (contentRepository.exists(new GeneralResourceURIImpl(site, url.getPath()))) {
                    logger.warn("Tried to create already existing resource {} in site '{}'", resourceURI, site);
                    throw new WebApplicationException(Status.CONFLICT);
                }
            } catch (IllegalArgumentException e) {
                logger.warn("Tried to create a resource with an invalid path '{}': {}", path, e.getMessage());
                throw new WebApplicationException(Status.BAD_REQUEST);
            } catch (ContentRepositoryException e) {
                logger.warn("Resource lookup {} failed for site '{}'", resourceURI, site);
                throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
            }
        }

        // Store the new resource
        try {
            uri = new URI(resourceURI.getIdentifier());
            contentRepository.put(resource, true);
        } catch (URISyntaxException e) {
            logger.warn("Error creating a uri for resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IOException e) {
            logger.warn("Error writing new resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IllegalStateException e) {
            logger.warn("Illegal state while adding new resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
        } catch (ContentRepositoryException e) {
            logger.warn("Error adding new resource {}: {}", resourceURI, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        }

        ResourceContent content = null;
        ResourceContentReader<?> reader = null;
        try {
            reader = serializer.getContentReader();
            is = new FileInputStream(uploadedFile);
            content = reader.createFromContent(is, user, language, uploadedFile.length(), fileName, mimeType);
        } catch (IOException e) {
            logger.warn("Error reading resource content {} from request", uri);
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (ParserConfigurationException e) {
            logger.warn("Error configuring parser to read resource content {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (SAXException e) {
            logger.warn("Error parsing udpated resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.BAD_REQUEST);
        } catch (Throwable t) {
            logger.warn("Unknown error while trying to read resource content {}: {}", uri, t.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
            if (content == null) {
                try {
                    contentRepository.delete(resourceURI);
                } catch (Throwable t) {
                    logger.error("Error deleting orphan resource {}", resourceURI, t);
                }
            }
        }

        try {
            is = new FileInputStream(uploadedFile);
            resource = contentRepository.putContent(resource.getURI(), content, is);
        } catch (IOException e) {
            logger.warn("Error writing content to resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } catch (IllegalStateException e) {
            logger.warn("Illegal state while adding content to resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.PRECONDITION_FAILED);
        } catch (ContentRepositoryException e) {
            logger.warn("Error adding content to resource {}: {}", uri, e.getMessage());
            throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
        } finally {
            IOUtils.closeQuietly(is);
        }

        // Create the response
        ResponseBuilder response = Response.created(uri);
        response.type(MediaType.MEDIA_TYPE_WILDCARD);
        response.tag(ResourceUtils.getETagValue(resource));
        response.lastModified(ResourceUtils.getModificationDate(resource));
        return response.build();

    } finally {
        FileUtils.deleteQuietly(uploadedFile);
    }
}

From source file:ninja.servlet.NinjaServletContext.java

private void processFormFields() {
    if (formFieldsProcessed)
        return;// w  w w  .  ja  v  a  2 s .co  m
    formFieldsProcessed = true;

    // return if not multipart
    if (!ServletFileUpload.isMultipartContent(httpServletRequest))
        return;

    // get fileProvider from route method/class, or defaults to an injected one
    // if none injected, then we do not process form fields this way and let the user
    // call classic getFileItemIterator() by himself
    FileProvider fileProvider = null;
    if (route != null) {
        if (fileProvider == null) {
            fileProvider = route.getControllerMethod().getAnnotation(FileProvider.class);
        }
        if (fileProvider == null) {
            fileProvider = route.getControllerClass().getAnnotation(FileProvider.class);
        }
    }

    // get file item provider from file provider or default one
    FileItemProvider fileItemProvider = null;
    if (fileProvider == null) {
        fileItemProvider = injector.getInstance(FileItemProvider.class);
    } else {
        fileItemProvider = injector.getInstance(fileProvider.value());
    }

    if (fileItemProvider instanceof NoFileItemProvider)
        return;

    // Initialize maps and other constants
    ArrayListMultimap<String, String> formMap = ArrayListMultimap.create();
    ArrayListMultimap<String, FileItem> fileMap = ArrayListMultimap.create();

    // This is the iterator we can use to iterate over the contents of the request.
    try {

        FileItemIterator fileItemIterator = getFileItemIterator();

        while (fileItemIterator.hasNext()) {

            FileItemStream item = fileItemIterator.next();

            if (item.isFormField()) {

                String charset = NinjaConstant.UTF_8;

                String contentType = item.getContentType();

                if (contentType != null) {
                    charset = HttpHeaderUtils.getCharsetOfContentTypeOrUtf8(contentType);
                }

                // save the form field for later use from getParameter
                String value = Streams.asString(item.openStream(), charset);
                formMap.put(item.getFieldName(), value);

            } else {

                // process file as input stream and save for later use in getParameterAsFile or getParameterAsInputStream
                FileItem fileItem = fileItemProvider.create(item);
                fileMap.put(item.getFieldName(), fileItem);
            }
        }
    } catch (FileUploadException | IOException e) {
        throw new RuntimeException("Failed to parse multipart request data", e);
    }

    // convert both multimap<K,V> to map<K,List<V>>
    formFieldsMap = toUnmodifiableMap(formMap);
    fileFieldsMap = toUnmodifiableMap(fileMap);
}

From source file:ninja.uploads.DiskFileItemProvider.java

@Override
public FileItem create(FileItemStream item) {

    File tmpFile = null;//from ww w  .j  a  va2s. c  o m

    // do copy
    try (InputStream is = item.openStream()) {
        tmpFile = File.createTempFile("nju", null, tmpFolder);
        Files.copy(is, tmpFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create temporary uploaded file on disk", e);
    }

    // return
    final String name = item.getName();
    final File file = tmpFile;
    final String contentType = item.getContentType();
    final FileItemHeaders headers = item.getHeaders();

    return new FileItem() {
        @Override
        public String getFileName() {
            return name;
        }

        @Override
        public InputStream getInputStream() {
            try {
                return new FileInputStream(file);
            } catch (FileNotFoundException e) {
                throw new RuntimeException("Failed to read temporary uploaded file from disk", e);
            }
        }

        @Override
        public File getFile() {
            return file;
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public FileItemHeaders getHeaders() {
            return headers;
        }

        @Override
        public void cleanup() {
            // try to delete temporary file, silently fail on error
            try {
                file.delete();
            } catch (Exception e) {
            }
        }
    };

}

From source file:ninja.uploads.MemoryFileItemProvider.java

@Override
public FileItem create(FileItemStream item) {

    // build output stream to get bytes
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    // do copy/*from ww  w . jav a 2s.  c o m*/
    try {
        ByteStreams.copy(item.openStream(), outputStream);
    } catch (IOException e) {
        throw new RuntimeException("Failed to create temporary uploaded file in memory", e);
    }

    // return
    final String name = item.getName();
    final byte[] bytes = outputStream.toByteArray();
    final String contentType = item.getContentType();
    final FileItemHeaders headers = item.getHeaders();

    return new FileItem() {
        @Override
        public String getFileName() {
            return name;
        }

        @Override
        public InputStream getInputStream() {
            return new ByteArrayInputStream(bytes);
        }

        @Override
        public File getFile() {
            throw new UnsupportedOperationException("Not supported in MemoryFileProvider");
        }

        @Override
        public String getContentType() {
            return contentType;
        }

        @Override
        public FileItemHeaders getHeaders() {
            return headers;
        }

        @Override
        public void cleanup() {
        }
    };

}

From source file:nu.kelvin.jfileshare.ajax.FileReceiverServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession();
    UserItem currentUser = (UserItem) session.getAttribute("user");
    if (currentUser != null && ServletFileUpload.isMultipartContent(req)) {
        Conf conf = (Conf) getServletContext().getAttribute("conf");
        // keep files of up to 10 MiB in memory 10485760
        FileItemFactory factory = new DiskFileItemFactory(10485760, new File(conf.getPathTemp()));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(conf.getFileSizeMax());

        // set file upload progress listener
        FileUploadListener listener = new FileUploadListener();
        session.setAttribute("uploadListener", listener);
        upload.setProgressListener(listener);

        File tempFile = File.createTempFile(String.format("%05d-", currentUser.getUid()), null,
                new File(conf.getPathTemp()));
        tempFile.deleteOnExit();/*from www.  j  av  a 2 s.  c o  m*/
        try {
            FileItem file = new FileItem();

            /* iterate over all uploaded items */
            FileItemIterator it = upload.getItemIterator(req);
            FileOutputStream filestream = null;

            while (it.hasNext()) {
                FileItemStream item = it.next();
                String name = item.getFieldName();
                InputStream instream = item.openStream();
                DigestOutputStream outstream = null;

                if (item.isFormField()) {
                    String value = Streams.asString(instream);
                    // logger.info(name + " : " + value);
                    /* not the file upload. Maybe the password field? */
                    if (name.equals("password") && !value.equals("")) {
                        logger.info("Uploaded file has password set");
                        file.setPwPlainText(value);
                    }
                    instream.close();
                } else {
                    // This is the file you're looking for
                    file.setName(item.getName());
                    file.setType(
                            item.getContentType() == null ? "application/octet-stream" : item.getContentType());
                    file.setUid(currentUser.getUid());

                    try {
                        filestream = new FileOutputStream(tempFile);
                        MessageDigest md = MessageDigest.getInstance("MD5");
                        outstream = new DigestOutputStream(filestream, md);
                        long filesize = IOUtils.copyLarge(instream, outstream);

                        if (filesize == 0) {
                            throw new Exception("File is empty.");
                        }
                        md = outstream.getMessageDigest();
                        file.setMd5sum(toHex(md.digest()));
                        file.setSize(filesize);

                    } finally {
                        if (outstream != null) {
                            try {
                                outstream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (filestream != null) {
                            try {
                                filestream.close();
                            } catch (IOException ignored) {
                            }
                        }
                        if (instream != null) {
                            try {
                                instream.close();
                            } catch (IOException ignored) {
                            }
                        }
                    }
                }
            }
            /* All done. Save the new file */
            if (conf.getDaysFileExpiration() != 0) {
                file.setDaysToKeep(conf.getDaysFileExpiration());
            }
            if (file.create(ds, req.getRemoteAddr())) {
                File finalFile = new File(conf.getPathStore(), Integer.toString(file.getFid()));
                tempFile.renameTo(finalFile);
                logger.log(Level.INFO, "User {0} storing file \"{1}\" in the filestore",
                        new Object[] { currentUser.getUid(), file.getName() });
                req.setAttribute("msg",
                        "File <strong>\"" + Helpers.htmlSafe(file.getName())
                                + "\"</strong> uploaded successfully. <a href='" + req.getContextPath()
                                + "/file/edit/" + file.getFid() + "'>Click here to edit file</a>");
                req.setAttribute("javascript", "parent.uploadComplete('info');");
            } else {
                req.setAttribute("msg", "Unable to contact the database");
                req.setAttribute("javascript", "parent.uploadComplete('critical');");
            }
        } catch (SizeLimitExceededException e) {
            tempFile.delete();
            req.setAttribute("msg", "File is too large. The maximum size of file uploads is "
                    + FileItem.humanReadable(conf.getFileSizeMax()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (FileUploadException e) {
            tempFile.delete();
            req.setAttribute("msg", "Unable to upload file");
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } catch (Exception e) {
            tempFile.delete();
            req.setAttribute("msg",
                    "Unable to upload file. ".concat(e.getMessage() == null ? "" : e.getMessage()));
            req.setAttribute("javascript", "parent.uploadComplete('warning');");
        } finally {
            session.setAttribute("uploadListener", null);
        }
        ServletContext app = getServletContext();
        RequestDispatcher disp = app.getRequestDispatcher("/templates/AjaxDummy.jsp");
        disp.forward(req, resp);
    }
}