Search in sources :

Example 61 with Part

use of javax.servlet.http.Part in project spring-framework by spring-projects.

the class MultipartResolutionDelegate method resolvePartList.

private static List<Part> resolvePartList(HttpServletRequest servletRequest, String name) throws Exception {
    Collection<Part> parts = servletRequest.getParts();
    List<Part> result = new ArrayList<>(parts.size());
    for (Part part : parts) {
        if (part.getName().equals(name)) {
            result.add(part);
        }
    }
    return result;
}
Also used : Part(javax.servlet.http.Part) ArrayList(java.util.ArrayList)

Example 62 with Part

use of javax.servlet.http.Part in project undertow by undertow-io.

the class MultiPartServlet method doPost.

@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    Collection<Part> parts = req.getParts();
    PrintWriter writer = resp.getWriter();
    writer.println("PARAMS:");
    for (Part part : parts) {
        writer.println("name: " + part.getName());
        writer.println("filename: " + part.getSubmittedFileName());
        writer.println("content-type: " + part.getContentType());
        Collection<String> headerNames = new TreeSet<>(part.getHeaderNames());
        for (String header : headerNames) {
            writer.println(header + ": " + part.getHeader(header));
        }
        writer.println("size: " + part.getSize());
        writer.println("content: " + FileUtils.readFile(part.getInputStream()));
    }
}
Also used : Part(javax.servlet.http.Part) TreeSet(java.util.TreeSet) PrintWriter(java.io.PrintWriter)

Example 63 with Part

use of javax.servlet.http.Part in project JMRI by JMRI.

the class MultipartRequestHandler method uploadByJavaServletAPI.

public static List<FileMeta> uploadByJavaServletAPI(HttpServletRequest request) throws IOException, ServletException {
    List<FileMeta> files = new LinkedList<FileMeta>();
    if (request.getContentType() != null && request.getContentType().startsWith("multipart/form-data")) {
        request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, MULTI_PART_CONFIG);
    }
    // 1. Get all parts and the flag
    Collection<Part> parts = request.getParts();
    //set replace flag from parameter
    boolean fileReplace = request.getParameter("fileReplace").equals("true");
    //set replace flag from parameter
    String rosterGroup = request.getParameter("rosterGroup");
    // deal with each each part
    FileMeta temp = null;
    for (Part part : parts) {
        // if part is multiparts "file"
        if (part.getContentType() != null) {
            // populate a new FileMeta object
            temp = new FileMeta();
            temp.setFileName(getFilename(part));
            temp.setFileSize(part.getSize() / 1024 + " Kb");
            temp.setFileType(part.getContentType());
            temp.setContent(part.getInputStream());
            temp.setFileReplace(fileReplace);
            temp.setRosterGroup(rosterGroup);
            // 3.3 Add created FileMeta object to List<FileMeta> files
            files.add(temp);
        }
    }
    return files;
}
Also used : Part(javax.servlet.http.Part) LinkedList(java.util.LinkedList)

Example 64 with Part

use of javax.servlet.http.Part in project Synthese_2BIN by TheYoungSensei.

the class Controleur method doGet.

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Lecture init param 'chemin'
    String chemin = this.getServletConfig().getInitParameter("chemin");
    // Les données reçues sont multipart
    Part part = request.getPart("fichier");
    if (part.getSize() == 0) {
        RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
        rd.forward(request, response);
        return;
    }
    /*
		 * Il faut déterminer s'il s'agit d'un champ classique ou d'un champ de
		 * type fichier : on délègue cette opération à la méthode utilitaire
		 * getNomFichier().
		 */
    String nomFichier = getNomFichier(part);
    if (nomFichier != null && !nomFichier.isEmpty()) {
        String nomChamp = part.getName();
        /*
			 * Antibug pour Internet Explorer, qui transmet pour une raison
			 * mystique le chemin du fichier local à la machine du client...
			 * 
			 * Ex : C:/dossier/sous-dossier/fichier.ext
			 * 
			 * On doit donc faire en sorte de ne sélectionner que le nom et
			 * l'extension du fichier, et de se débarrasser du superflu.
			 */
        nomFichier = nomFichier.substring(nomFichier.lastIndexOf('/') + 1).substring(nomFichier.lastIndexOf('\\') + 1);
        nomFichier = nomFichier.substring(1, nomFichier.length() - 1);
        /* Écriture du fichier sur le disque */
        ecrireFichier(part, nomFichier, chemin);
        request.setAttribute(nomChamp, nomFichier);
    }
    try {
        String nomClasse = nomFichier.substring(0, nomFichier.length() - 6);
        MyClassLoader cl = new MyClassLoader();
        String fi = chemin + nomClasse + ".class";
        Class cls = cl.findClass(fi);
        Propriete laClasse = new Propriete(nomClasse, Modifier.isAbstract(cls.getModifiers()));
        List<Propriete> attributs = new ArrayList<Propriete>();
        for (Field field : cls.getDeclaredFields()) {
            Visibilite visibilite = chercherVisibilite(field.getModifiers());
            boolean estStatique = false;
            if (Modifier.isStatic(field.getModifiers()))
                estStatique = true;
            String valDefaut = "";
            Propriete prop = new Propriete(field.getName() + " : " + field.getType().getSimpleName() + valDefaut, estStatique, visibilite);
            attributs.add(prop);
        }
        List<Propriete> methodes = chercherMethodes(cls);
        List<Propriete> constructeurs = chercherConstruteurs(cls);
        request.setAttribute("nom", nomClasse);
        request.setAttribute("identite", laClasse);
        request.setAttribute("attributs", attributs);
        request.setAttribute("methodes", methodes);
        request.setAttribute("constructeurs", constructeurs);
        RequestDispatcher rd = request.getServletContext().getNamedDispatcher("Index");
        rd.forward(request, response);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return;
}
Also used : Field(java.lang.reflect.Field) Part(javax.servlet.http.Part) Visibilite(gimme.domaine.Visibilite) ArrayList(java.util.ArrayList) RequestDispatcher(javax.servlet.RequestDispatcher) Propriete(gimme.domaine.Propriete)

Example 65 with Part

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

the class StreamingUploadOperationTest method testPartsContentRange.

@Test
public void testPartsContentRange() 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")), mapOf("Content-Range", "bytes 0-3/8", "Content-Length", "4")));
    partsList.add(new MockPart("test1.txt", "text/plain", "test1bad.txt", 4, new ByteArrayInputStream("part".getBytes("UTF-8")), mapOf("Content-Range", "bytes 4-7/8", "Content-Length", "4")));
    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) {
            List<Resource> children = new ArrayList<>();
            for (Map.Entry<String, Resource> e : repository.entrySet()) {
                if (isChild(resource.getPath(), e.getKey())) {
                    children.add(e.getValue());
                }
            }
            return children;
        }

        private boolean isChild(String path, String key) {
            if (key.length() > path.length() && key.startsWith(path)) {
                return !key.substring(path.length() + 1).contains("/");
            }
            return false;
        }

        @Override
        public Iterator<Resource> listChildren(Resource parent) {
            return getChildren(parent).iterator();
        }

        @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 ");
            }
            String resourceType = (String) map.get("sling:resourceType");
            if (resourceType == null) {
                resourceType = (String) map.get("jcr:primaryType");
            }
            if (resourceType == null) {
                LOG.warn("Resource type null for {} {} ", resource, resource.getPath() + "/" + s);
            }
            Resource newResource = new MockRealResource(this, resource.getPath() + "/" + s, resourceType, map);
            repository.put(newResource.getPath(), newResource);
            LOG.debug("Created Resource {} ", newResource.getPath());
            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("Comittted {} ", 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("testpart", 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)

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