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

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

Introduction

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

Prototype

String getFieldName();

Source Link

Document

Returns the name of the field in the multipart form corresponding to this file item.

Usage

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  ww  w .j  av  a2s . c  o  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:net.ymate.platform.mvc.web.support.FileUploadHelper.java

/**
 * ???????/*from   w w  w.j a v  a 2  s  .  com*/
 * 
 * @param processer
 * @throws IOException 
 * @throws FileUploadException 
 */
private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer)
        throws FileUploadException, IOException {
    ServletFileUpload _upload = new ServletFileUpload();
    if (this.__listener != null) {
        _upload.setProgressListener(this.__listener);
    }
    _upload.setFileSizeMax(this.__fileSizeMax);
    _upload.setSizeMax(this.__sizeMax);
    UploadFormWrapper _form = new UploadFormWrapper();
    Map<String, List<String>> tmpParams = new HashMap<String, List<String>>();
    Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>();
    //
    FileItemIterator _iter = _upload.getItemIterator(this.__request);
    while (_iter.hasNext()) {
        FileItemStream _item = _iter.next();
        if (_item.isFormField()) {
            List<String> _valueList = tmpParams.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<String>();
                tmpParams.put(_item.getFieldName(), _valueList);
            }
            _valueList.add(Streams.asString(_item.openStream(), WebMVC.getConfig().getCharsetEncoding()));
        } else {
            List<UploadFileWrapper> _valueList2 = tmpFiles.get(_item.getFieldName());
            if (_valueList2 == null) {
                _valueList2 = new ArrayList<UploadFileWrapper>();
                tmpFiles.put(_item.getFieldName(), _valueList2);
            }
            // ??
            _valueList2.add(processer.process(_item));
        }
    }
    //
    for (Entry<String, List<String>> entry : tmpParams.entrySet()) {
        String key = entry.getKey();
        List<String> value = entry.getValue();
        _form.getFieldMap().put(key, value.toArray(new String[value.size()]));
    }
    for (Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) {
        String key = entry.getKey();
        _form.getFileMap().put(key, entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()]));
    }
    return _form;
}

From source file:net.ymate.platform.webmvc.util.FileUploadHelper.java

/**
 * ???????/*w w w  . j  a v a 2 s  . c  o  m*/
 *
 * @param processer ?
 * @throws FileUploadException ?
 * @throws IOException         ?
 */
private UploadFormWrapper __doUploadFileAsStream(IUploadFileItemProcesser processer)
        throws FileUploadException, IOException {
    ServletFileUpload _upload = new ServletFileUpload();
    _upload.setFileSizeMax(__fileSizeMax);
    _upload.setSizeMax(__sizeMax);
    if (__listener != null) {
        _upload.setProgressListener(__listener);
    }
    Map<String, List<String>> tmpParams = new HashMap<String, List<String>>();
    Map<String, List<UploadFileWrapper>> tmpFiles = new HashMap<String, List<UploadFileWrapper>>();
    //
    FileItemIterator _fileItemIT = _upload.getItemIterator(__request);
    while (_fileItemIT.hasNext()) {
        FileItemStream _item = _fileItemIT.next();
        if (_item.isFormField()) {
            List<String> _valueList = tmpParams.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<String>();
                tmpParams.put(_item.getFieldName(), _valueList);
            }
            _valueList.add(Streams.asString(_item.openStream(), __charsetEncoding));
        } else {
            List<UploadFileWrapper> _valueList = tmpFiles.get(_item.getFieldName());
            if (_valueList == null) {
                _valueList = new ArrayList<UploadFileWrapper>();
                tmpFiles.put(_item.getFieldName(), _valueList);
            }
            // ??
            _valueList.add(processer.process(_item));
        }
    }
    //
    UploadFormWrapper _form = new UploadFormWrapper();
    for (Map.Entry<String, List<String>> entry : tmpParams.entrySet()) {
        _form.getFieldMap().put(entry.getKey(), entry.getValue().toArray(new String[entry.getValue().size()]));
    }
    for (Map.Entry<String, List<UploadFileWrapper>> entry : tmpFiles.entrySet()) {
        _form.getFileMap().put(entry.getKey(),
                entry.getValue().toArray(new UploadFileWrapper[entry.getValue().size()]));
    }
    return _form;
}

From source file:ninja.servlet.NinjaServletContext.java

private void processFormFields() {
    if (formFieldsProcessed)
        return;//w ww  . java 2 s  . c  o  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: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();//  w  w  w.  j a va  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);
    }
}

From source file:nu.validator.servlet.MultipartFormDataFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    if (ServletFileUpload.isMultipartContent(request)) {
        try {// www.  j  a v a2s .com
            boolean utf8 = false;
            String contentType = null;
            Map<String, String[]> params = new HashMap<>();
            InputStream fileStream = null;
            ServletFileUpload upload = new ServletFileUpload();
            FileItemIterator iter = upload.getItemIterator(request);
            while (iter.hasNext()) {
                FileItemStream fileItemStream = iter.next();
                if (fileItemStream.isFormField()) {
                    String fieldName = fileItemStream.getFieldName();
                    if ("content".equals(fieldName) || "fragment".equals(fieldName)) {
                        utf8 = true;
                        String[] parser = params.get("parser");
                        if (parser != null && parser[0].startsWith("xml")) {
                            contentType = "application/xml";
                        } else {
                            contentType = "text/html";
                        }
                        request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.type", "textarea");
                        fileStream = fileItemStream.openStream();
                        break;
                    } else {
                        putParam(params, fieldName, utf8ByteStreamToString(fileItemStream.openStream()));
                    }
                } else {
                    String fileName = fileItemStream.getName();
                    if (fileName != null) {
                        putParam(params, fileItemStream.getFieldName(), fileName);
                        request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.filename", fileName);
                        Matcher m = EXTENSION.matcher(fileName);
                        if (m.matches()) {
                            contentType = EXTENSION_TO_TYPE.get(m.group(1));
                        }
                    }
                    if (contentType == null) {
                        contentType = fileItemStream.getContentType();
                    }
                    request.setAttribute("nu.validator.servlet.MultipartFormDataFilter.type", "file");
                    fileStream = fileItemStream.openStream();
                    break;
                }
            }
            if (fileStream == null) {
                fileStream = new ByteArrayInputStream(new byte[0]);
            }
            if (contentType == null) {
                contentType = "application/octet-stream";
            }
            chain.doFilter(new RequestWrapper(request, params, contentType, utf8, fileStream), response);
        } catch (FileUploadException e) {
            response.sendError(415, e.getMessage());
        } catch (CharacterCodingException e) {
            response.sendError(415, e.getMessage());
        } catch (IOException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        }
    } else {
        chain.doFilter(req, res);
    }
}

From source file:org.alfresco.repo.web.scripts.transfer.PostContentCommandProcessor.java

public int process(WebScriptRequest req, WebScriptResponse resp) {
    logger.debug("post content start");
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;/* w  w  w.  j  a v  a 2  s  . c  o m*/
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    if (webScriptServletRequest == null) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }

    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();

    //Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");

    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }

    try {

        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (!item.isFormField()) {
                logger.debug("got content Mime Part : " + name);
                receiver.saveContent(transferId, item.getName(), item.openStream());
            }
        }

        //            WebScriptServletRequest alfRequest = (WebScriptServletRequest)req;
        //            String[] names = alfRequest.getParameterNames();
        //            for(String name : names)
        //            {
        //                FormField item = alfRequest.getFileField(name);
        //                
        //                if(item != null)
        //                {
        //                    logger.debug("got content Mime Part : " + name);
        //                    receiver.saveContent(transferId, item.getName(), item.getInputStream());
        //                }
        //                else
        //                {
        //                    //TODO - should this be an exception?
        //                    logger.debug("Unable to get content for Mime Part : " + name);
        //                }
        //            }

        logger.debug("success");

        resp.setStatus(Status.STATUS_OK);
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);

    }

    resp.setStatus(Status.STATUS_OK);
    return Status.STATUS_OK;
}

From source file:org.alfresco.repo.web.scripts.transfer.PostSnapshotCommandProcessor.java

public int process(WebScriptRequest req, WebScriptResponse resp) {

    int result = Status.STATUS_OK;
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;/*  www.j  a v a  2 s  .co m*/
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    if (webScriptServletRequest == null) {
        logger.debug("bad request, not assignable from");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }

    //We can't use the WebScriptRequest version of getParameter, since that may cause the content stream 
    //to be parsed. Get hold of the raw HttpServletRequest and work with that.
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();

    //Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");

    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        logger.debug("bad request, not multipart");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }

    try {
        logger.debug("about to upload manifest file");

        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField() && TransferCommons.PART_NAME_MANIFEST.equals(item.getFieldName())) {
                logger.debug("got manifest file");
                receiver.saveSnapshot(transferId, item.openStream());
            }
        }

        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);

        OutputStream out = resp.getOutputStream();
        resp.setContentType("text/xml");
        resp.setContentEncoding("utf-8");

        receiver.generateRequsite(transferId, out);

        out.close();

    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    return result;
}

From source file:org.apache.chemistry.opencmis.server.impl.browser.POSTHttpServletRequestWrapper.java

public POSTHttpServletRequestWrapper(HttpServletRequest request, File tempDir, int memoryThreshold)
        throws Exception {
    super(request);

    parameters = new HashMap<String, String[]>();

    // parse query string
    parseFormData(request.getQueryString());

    // check multipart
    isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream itemStream = new BufferedInputStream(item.openStream());

            if (item.isFormField()) {
                InputStreamReader reader = new InputStreamReader(itemStream, "UTF-8");

                try {
                    StringBuilder sb = new StringBuilder();

                    char[] buffer = new char[64 * 1024];
                    int b = 0;

                    while ((b = reader.read(buffer)) > -1) {
                        sb.append(buffer, 0, b);
                    }/*  w w w . j  ava  2  s  .c  o m*/

                    addParameter(name, sb.toString());
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            } else {
                filename = item.getName();
                contentType = ((item.getContentType() == null) ? Constants.MEDIATYPE_OCTETSTREAM
                        : item.getContentType());

                ThresholdOutputStream os = new ThresholdOutputStream(tempDir, memoryThreshold);

                try {
                    byte[] buffer = new byte[64 * 1024];
                    int b = 0;

                    while ((b = itemStream.read(buffer)) > -1) {
                        os.write(buffer, 0, b);
                    }

                    os.close();

                    size = BigInteger.valueOf(os.getSize());
                    stream = os.getInputStream();
                } catch (Exception e) {
                    // if something went wrong, make sure the temp file will
                    // be deleted
                    os.destroy();
                    throw e;
                } finally {
                    try {
                        itemStream.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }

        String filenameControl = HttpUtils.getStringParameter(this, Constants.CONTROL_FILENAME);

        if (((filenameControl) != null) && (filenameControl.trim().length() > 0)) {
            filename = filenameControl;
        }

        String contentTypeControl = HttpUtils.getStringParameter(this, Constants.CONTROL_CONTENT_TYPE);

        if ((contentTypeControl != null) && (contentTypeControl.trim().length() > 0)) {
            contentType = contentTypeControl;
        }
    } else {
        // form data processing
        StringBuilder sb = new StringBuilder();

        InputStreamReader sr = new InputStreamReader(request.getInputStream(), "UTF-8");
        char[] buffer = new char[4096];
        int c = 0;

        while ((c = sr.read(buffer)) > -1) {
            sb.append(buffer, 0, c);
        }

        parseFormData(sb.toString());
    }
}

From source file:org.apache.jena.fuseki.servlets.Upload.java

/**  Process an HTTP upload of RDF files (triples or quads)
 *   Stream straight into a graph or dataset -- unlike SPARQL_Upload the destination
 *   is known at the start of the multipart file body
 *//*from w  ww. ja  va2 s .  c om*/

public static UploadDetails fileUploadWorker(HttpAction action, StreamRDF dest) {
    String base = ActionLib.wholeRequestURL(action.request);
    ServletFileUpload upload = new ServletFileUpload();
    //log.info(format("[%d] Upload: Field=%s ignored", action.id, fieldName)) ;

    // Overall counting.
    StreamRDFCounting countingDest = StreamRDFLib.count(dest);

    try {
        FileItemIterator iter = upload.getItemIterator(action.request);
        while (iter.hasNext()) {
            FileItemStream fileStream = iter.next();
            if (fileStream.isFormField()) {
                // Ignore?
                String fieldName = fileStream.getFieldName();
                InputStream stream = fileStream.openStream();
                String value = Streams.asString(stream, "UTF-8");
                ServletOps.errorBadRequest(
                        format("Only files accepted in multipart file upload (got %s=%s)", fieldName, value));
            }
            //Ignore the field name.
            //String fieldName = fileStream.getFieldName();

            InputStream stream = fileStream.openStream();
            // Process the input stream
            String contentTypeHeader = fileStream.getContentType();
            ContentType ct = ContentType.create(contentTypeHeader);
            Lang lang = null;
            if (!matchContentType(ctTextPlain, ct))
                lang = RDFLanguages.contentTypeToLang(ct.getContentType());

            if (lang == null) {
                String name = fileStream.getName();
                if (name == null || name.equals(""))
                    ServletOps.errorBadRequest("No name for content - can't determine RDF syntax");
                lang = RDFLanguages.filenameToLang(name);
                if (name.endsWith(".gz"))
                    stream = new GZIPInputStream(stream);
            }
            if (lang == null)
                // Desperate.
                lang = RDFLanguages.RDFXML;

            String printfilename = fileStream.getName();
            if (printfilename == null || printfilename.equals(""))
                printfilename = "<none>";

            // Before
            // action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s", 
            //                        action.id, printfilename,  ct.getContentType(), ct.getCharset(), lang.getName())) ;

            // count just this step
            StreamRDFCounting countingDest2 = StreamRDFLib.count(countingDest);
            try {
                ActionSPARQL.parse(action, countingDest2, stream, lang, base);
                UploadDetails details1 = new UploadDetails(countingDest2.count(), countingDest2.countTriples(),
                        countingDest2.countQuads());
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id,
                        printfilename, ct.getContentType(), ct.getCharset(), lang.getName(),
                        details1.detailsStr()));
            } catch (RiotParseException ex) {
                action.log.info(format("[%d] Filename: %s, Content-Type=%s, Charset=%s => %s : %s", action.id,
                        printfilename, ct.getContentType(), ct.getCharset(), lang.getName(), ex.getMessage()));
                throw ex;
            }
        }
    } catch (ActionErrorException ex) {
        throw ex;
    } catch (Exception ex) {
        ServletOps.errorOccurred(ex.getMessage());
    }
    // Overall results.
    UploadDetails details = new UploadDetails(countingDest.count(), countingDest.countTriples(),
            countingDest.countQuads());
    return details;
}