Search in sources :

Example 31 with Part

use of javax.servlet.http.Part in project sling by apache.

the class StreamedUploadOperation method doRun.

@Override
protected void doRun(SlingHttpServletRequest request, PostResponse response, List<Modification> changes) throws PersistenceException {
    @SuppressWarnings("unchecked") Iterator<Part> partsIterator = (Iterator<Part>) request.getAttribute("request-parts-iterator");
    Map<String, List<String>> formFields = new HashMap<>();
    boolean streamingBodies = false;
    while (partsIterator.hasNext()) {
        Part part = partsIterator.next();
        String name = part.getName();
        if (isFormField(part)) {
            addField(formFields, name, part);
            if (streamingBodies) {
                LOG.warn("Form field {} was sent after the bodies started to be streamed. " + "Will not have been available to all streamed bodies. " + "It is recommended to send all form fields before streamed bodies in the POST ", name);
            }
        } else {
            streamingBodies = true;
            // process the file body and commit.
            writeContent(request.getResourceResolver(), part, formFields, response, changes);
        }
    }
}
Also used : HashMap(java.util.HashMap) Part(javax.servlet.http.Part) Iterator(java.util.Iterator) ArrayList(java.util.ArrayList) List(java.util.List)

Example 32 with Part

use of javax.servlet.http.Part in project sling by apache.

the class StreamingUploadOperationTest method test.

@Test
public void test() throws PersistenceException, RepositoryException, UnsupportedEncodingException {
    List<Modification> changes = new ArrayList<>();
    PostResponse response = new AbstractPostResponse() {

        @Override
        protected void doSend(HttpServletResponse response) throws IOException {
        }

        @Override
        public void onChange(String type, String... arguments) {
        }

        @Override
        public String getPath() {
            return "/test/upload/location";
        }
    };
    List<Part> partsList = new ArrayList<>();
    partsList.add(new MockPart("formfield1", null, null, 0, new ByteArrayInputStream("testformfield1".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("formfield2", null, null, 0, new ByteArrayInputStream("testformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("test".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("*", "text/plain2", "test2.txt", 8, new ByteArrayInputStream("test1234".getBytes("UTF-8")), Collections.EMPTY_MAP));
    partsList.add(new MockPart("badformfield2", null, null, 0, new ByteArrayInputStream("testbadformfield2".getBytes("UTF-8")), Collections.EMPTY_MAP));
    final Iterator<Part> partsIterator = partsList.iterator();
    final Map<String, Resource> repository = new HashMap<>();
    final ResourceResolver resourceResolver = new MockResourceResolver() {

        @Override
        public Resource getResource(String path) {
            Resource resource = repository.get(path);
            if (resource == null) {
                if ("/test/upload/location".equals(path)) {
                    resource = new MockRealResource(this, path, "sling:Folder");
                    repository.put(path, resource);
                    LOG.debug("Created {} ", path);
                }
            }
            LOG.debug("Resource {} is {} {}", path, resource, ResourceUtil.isSyntheticResource(resource));
            return resource;
        }

        @Override
        public Iterable<Resource> getChildren(Resource resource) {
            return null;
        }

        @Override
        public void delete(Resource resource) throws PersistenceException {
        }

        @Override
        public Resource create(Resource resource, String s, Map<String, Object> map) throws PersistenceException {
            Resource childResource = resource.getChild(s);
            if (childResource != null) {
                throw new IllegalArgumentException("Child " + s + " already exists ");
            }
            Resource newResource = new MockRealResource(this, resource.getPath() + "/" + s, (String) map.get("sling:resourceType"), map);
            repository.put(newResource.getPath(), newResource);
            return newResource;
        }

        @Override
        public void revert() {
        }

        @Override
        public void commit() throws PersistenceException {
            LOG.debug("Committing");
            for (Map.Entry<String, Resource> e : repository.entrySet()) {
                LOG.debug("Committing {} ", e.getKey());
                Resource r = e.getValue();
                ModifiableValueMap vm = r.adaptTo(ModifiableValueMap.class);
                for (Map.Entry<String, Object> me : vm.entrySet()) {
                    if (me.getValue() instanceof InputStream) {
                        try {
                            String value = IOUtils.toString((InputStream) me.getValue());
                            LOG.debug("Converted {} {}  ", me.getKey(), value);
                            vm.put(me.getKey(), value);
                        } catch (IOException e1) {
                            throw new PersistenceException("Failed to commit input stream", e1);
                        }
                    }
                }
                LOG.debug("Converted {} ", vm);
            }
            LOG.debug("Committted {} ", repository);
        }

        @Override
        public boolean hasChanges() {
            return false;
        }
    };
    SlingHttpServletRequest request = new MockSlingHttpServlet3Request(null, null, null, null, null) {

        @Override
        public Object getAttribute(String name) {
            if ("request-parts-iterator".equals(name)) {
                return partsIterator;
            }
            return super.getAttribute(name);
        }

        @Override
        public ResourceResolver getResourceResolver() {
            return resourceResolver;
        }
    };
    streamedUplodOperation.doRun(request, response, changes);
    {
        Resource r = repository.get("/test/upload/location/test1.txt");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
    }
    {
        Resource r = repository.get("/test/upload/location/test1.txt/jcr:content");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
        Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
        Assert.assertEquals("text/plain", m.get("jcr:mimeType"));
        Assert.assertEquals("test", m.get("jcr:data"));
    }
    {
        Resource r = repository.get("/test/upload/location/test2.txt");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:file", m.get("jcr:primaryType"));
    }
    {
        Resource r = repository.get("/test/upload/location/test2.txt/jcr:content");
        Assert.assertNotNull(r);
        ValueMap m = r.adaptTo(ValueMap.class);
        Assert.assertNotNull(m);
        Assert.assertEquals("nt:resource", m.get("jcr:primaryType"));
        Assert.assertTrue(m.get("jcr:lastModified") instanceof Calendar);
        Assert.assertEquals("text/plain2", m.get("jcr:mimeType"));
        Assert.assertEquals("test1234", m.get("jcr:data"));
    }
}
Also used : Modification(org.apache.sling.servlets.post.Modification) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) ArrayList(java.util.ArrayList) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) MockResourceResolver(org.apache.sling.commons.testing.sling.MockResourceResolver) AbstractPostResponse(org.apache.sling.servlets.post.AbstractPostResponse) PostResponse(org.apache.sling.servlets.post.PostResponse) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) Resource(org.apache.sling.api.resource.Resource) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) AbstractPostResponse(org.apache.sling.servlets.post.AbstractPostResponse) MockSlingHttpServlet3Request(org.apache.sling.servlets.post.impl.helper.MockSlingHttpServlet3Request) ByteArrayInputStream(java.io.ByteArrayInputStream) Part(javax.servlet.http.Part) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) MockResourceResolver(org.apache.sling.commons.testing.sling.MockResourceResolver) PersistenceException(org.apache.sling.api.resource.PersistenceException) ValueMap(org.apache.sling.api.resource.ValueMap) HashMap(java.util.HashMap) Map(java.util.Map) ModifiableValueMap(org.apache.sling.api.resource.ModifiableValueMap) Test(org.junit.Test)

Example 33 with Part

use of javax.servlet.http.Part in project tomee by apache.

the class CommonsFileUploadPartFactory method read.

public static Collection<Part> read(final HttpRequestImpl request) {
    // mainly for testing
    // Create a new file upload handler
    final DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setRepository(REPO);
    final ServletFileUpload upload = new ServletFileUpload();
    upload.setFileItemFactory(factory);
    final List<Part> parts = new ArrayList<>();
    try {
        final List<FileItem> items = upload.parseRequest(new ServletRequestContext(request));
        final String enc = request.getCharacterEncoding();
        for (final FileItem item : items) {
            final CommonsFileUploadPart part = new CommonsFileUploadPart(item, null);
            parts.add(part);
            if (part.getSubmittedFileName() == null) {
                String name = part.getName();
                String value = null;
                try {
                    String encoding = request.getCharacterEncoding();
                    if (encoding == null) {
                        if (enc == null) {
                            encoding = "UTF-8";
                        } else {
                            encoding = enc;
                        }
                    }
                    value = part.getString(encoding);
                } catch (final UnsupportedEncodingException uee) {
                    try {
                        value = part.getString("UTF-8");
                    } catch (final UnsupportedEncodingException e) {
                    // not possible
                    }
                }
                request.addInternalParameter(name, value);
            }
        }
        return parts;
    } catch (final FileUploadException e) {
        throw new IllegalStateException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletRequestContext(org.apache.commons.fileupload.servlet.ServletRequestContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DiskFileItemFactory(org.apache.commons.fileupload.disk.DiskFileItemFactory) FileItem(org.apache.commons.fileupload.FileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) Part(javax.servlet.http.Part) FileUploadException(org.apache.commons.fileupload.FileUploadException)

Example 34 with Part

use of javax.servlet.http.Part in project XRTB by benmfaul.

the class WebCampaign method multiPart.

public String multiPart(Request baseRequest, HttpServletRequest request, MultipartConfigElement config) throws Exception {
    HttpSession session = request.getSession(false);
    String user = (String) session.getAttribute("user");
    User u = db.getUser(user);
    if (u == null)
        throw new Exception("No such user");
    baseRequest.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, config);
    Collection<Part> parts = request.getParts();
    for (Part part : parts) {
        System.out.println("" + part.getName());
    }
    Part filePart = request.getPart("file");
    InputStream imageStream = filePart.getInputStream();
    byte[] resultBuff = new byte[0];
    byte[] buff = new byte[1024];
    int k = -1;
    while ((k = imageStream.read(buff, 0, buff.length)) > -1) {
        // temp buffer size
        byte[] tbuff = new byte[resultBuff.length + k];
        // = bytes already
        // read + bytes last
        // read
        // copy
        System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length);
        // previous
        // bytes
        // copy
        System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
        // current
        // lot
        // call the temp buffer as your result buff
        resultBuff = tbuff;
    }
    System.out.println(resultBuff.length + " bytes read.");
    if (k == 0) {
        // no file provided
        throw new Exception("No file provided");
    } else {
        byte[] bytes = new byte[1024];
        Part namePart = request.getPart("name");
        InputStream nameStream = namePart.getInputStream();
        int rc = nameStream.read(bytes);
        String name = new String(bytes, 0, rc);
        FileOutputStream fos = new FileOutputStream(u.directory + "/" + name);
        fos.write(resultBuff);
        fos.close();
    }
    Map response = new HashMap();
    response.put("images", getFiles(u));
    return getString(response);
}
Also used : User(com.xrtb.db.User) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) Part(javax.servlet.http.Part) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) HashMap(java.util.HashMap) Map(java.util.Map)

Example 35 with Part

use of javax.servlet.http.Part in project dropbox-sdk-java by dropbox.

the class DropboxBrowse method doUpload.

// -------------------------------------------------------------------------------------------
// POST /upload
// -------------------------------------------------------------------------------------------
public void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
    request.setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
    if (!common.checkPost(request, response))
        return;
    User user = common.requireLoggedInUser(request, response);
    if (user == null)
        return;
    DbxClientV2 dbxClient = requireDbxClient(request, response, user);
    if (dbxClient == null)
        return;
    try {
        // Just call getParts() to trigger the too-large exception.
        request.getParts();
    } catch (IllegalStateException ex) {
        response.sendError(400, "Request too large");
        return;
    }
    String targetFolder = slurpUtf8Part(request, response, "targetFolder", 1024);
    if (targetFolder == null)
        return;
    Part filePart = request.getPart("file");
    if (filePart == null) {
        response.sendError(400, "Field \"file\" is missing.");
        return;
    }
    String fileName = filePart.getName();
    if (fileName == null) {
        response.sendError(400, "Field \"file\" has no name.");
        return;
    }
    // Upload file to Dropbox
    String fullTargetPath = targetFolder + "/" + fileName;
    FileMetadata metadata;
    try {
        metadata = dbxClient.files().upload(fullTargetPath).uploadAndFinish(filePart.getInputStream());
    } catch (DbxException ex) {
        common.handleDbxException(response, user, ex, "upload(" + jq(fullTargetPath) + ", ...)");
        return;
    } catch (IOException ex) {
        response.sendError(400, "Error getting file data from you.");
        return;
    }
    // Display uploaded file metadata.
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "UTF-8"));
    out.println("<html>");
    out.println("<head><title>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</title></head>");
    out.println("<body>");
    out.println("<h2>File uploaded: " + escapeHtml4(metadata.getPathLower()) + "</h2>");
    out.println("<pre>");
    out.print(escapeHtml4(metadata.toStringMultiline()));
    out.println("</pre>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
}
Also used : DbxClientV2(com.dropbox.core.v2.DbxClientV2) MultipartConfigElement(javax.servlet.MultipartConfigElement) Part(javax.servlet.http.Part) FileMetadata(com.dropbox.core.v2.files.FileMetadata) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) DbxException(com.dropbox.core.DbxException) PrintWriter(java.io.PrintWriter)

Aggregations

Part (javax.servlet.http.Part)68 Test (org.junit.Test)42 ByteArrayInputStream (java.io.ByteArrayInputStream)27 MultipartConfigElement (javax.servlet.MultipartConfigElement)27 MultiPart (org.eclipse.jetty.util.MultiPartInputStreamParser.MultiPart)24 IOException (java.io.IOException)19 InputStream (java.io.InputStream)12 ArrayList (java.util.ArrayList)12 ByteArrayOutputStream (java.io.ByteArrayOutputStream)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 ServletException (javax.servlet.ServletException)10 HttpServletRequest (javax.servlet.http.HttpServletRequest)9 AbstractHttpClientServerTest (org.eclipse.jetty.client.AbstractHttpClientServerTest)7 File (java.io.File)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 ContentResponse (org.eclipse.jetty.client.api.ContentResponse)5 MockPart (org.springframework.mock.web.test.MockPart)5 RequestPart (org.springframework.web.bind.annotation.RequestPart)5 PrintWriter (java.io.PrintWriter)4