Search in sources :

Example 1 with Part

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

the class Request method recycle.

/**
     * Release all object references, and initialize instance variables, in
     * preparation for reuse of this object.
     */
public void recycle() {
    internalDispatcherType = null;
    requestDispatcherPath = null;
    authType = null;
    inputBuffer.recycle();
    usingInputStream = false;
    usingReader = false;
    userPrincipal = null;
    subject = null;
    parametersParsed = false;
    if (parts != null) {
        for (Part part : parts) {
            try {
                part.delete();
            } catch (IOException ignored) {
            // ApplicationPart.delete() never throws an IOEx
            }
        }
        parts = null;
    }
    partsParseException = null;
    locales.clear();
    localesParsed = false;
    secure = false;
    remoteAddr = null;
    remoteHost = null;
    remotePort = -1;
    localPort = -1;
    localAddr = null;
    localName = null;
    attributes.clear();
    sslAttributesParsed = false;
    notes.clear();
    recycleSessionInfo();
    recycleCookieInfo(false);
    if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
        parameterMap = new ParameterMap<>();
    } else {
        parameterMap.setLocked(false);
        parameterMap.clear();
    }
    mappingData.recycle();
    applicationMapping.recycle();
    applicationRequest = null;
    if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) {
        if (facade != null) {
            facade.clear();
            facade = null;
        }
        if (inputStream != null) {
            inputStream.clear();
            inputStream = null;
        }
        if (reader != null) {
            reader.clear();
            reader = null;
        }
    }
    asyncSupported = null;
    if (asyncContext != null) {
        asyncContext.recycle();
    }
    asyncContext = null;
}
Also used : Part(javax.servlet.http.Part) ApplicationPart(org.apache.catalina.core.ApplicationPart) IOException(java.io.IOException)

Example 2 with Part

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

the class HTMLManagerServlet method upload.

protected String upload(HttpServletRequest request, StringManager smClient) {
    String message = "";
    try {
        while (true) {
            Part warPart = request.getPart("deployWar");
            if (warPart == null) {
                message = smClient.getString("htmlManagerServlet.deployUploadNoFile");
                break;
            }
            String filename = warPart.getSubmittedFileName();
            if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) {
                message = smClient.getString("htmlManagerServlet.deployUploadNotWar", filename);
                break;
            }
            // Get the filename if uploaded name includes a path
            if (filename.lastIndexOf('\\') >= 0) {
                filename = filename.substring(filename.lastIndexOf('\\') + 1);
            }
            if (filename.lastIndexOf('/') >= 0) {
                filename = filename.substring(filename.lastIndexOf('/') + 1);
            }
            // Identify the appBase of the owning Host of this Context
            // (if any)
            File file = new File(host.getAppBaseFile(), filename);
            if (file.exists()) {
                message = smClient.getString("htmlManagerServlet.deployUploadWarExists", filename);
                break;
            }
            ContextName cn = new ContextName(filename, true);
            String name = cn.getName();
            if ((host.findChild(name) != null) && !isDeployed(name)) {
                message = smClient.getString("htmlManagerServlet.deployUploadInServerXml", filename);
                break;
            }
            if (isServiced(name)) {
                message = smClient.getString("managerServlet.inService", name);
            } else {
                addServiced(name);
                try {
                    warPart.write(file.getAbsolutePath());
                    // Perform new deployment
                    check(name);
                } finally {
                    removeServiced(name);
                }
            }
            break;
        }
    } catch (Exception e) {
        message = smClient.getString("htmlManagerServlet.deployUploadFail", e.getMessage());
        log(message, e);
    }
    return message;
}
Also used : Part(javax.servlet.http.Part) File(java.io.File) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) ContextName(org.apache.catalina.util.ContextName)

Example 3 with Part

use of javax.servlet.http.Part in project jetty.project by eclipse.

the class MultiPartContentProviderTest method testFieldWithOverridenContentType.

@Test
public void testFieldWithOverridenContentType() throws Exception {
    String name = "field";
    String value = "è";
    Charset encoding = StandardCharsets.ISO_8859_1;
    start(new AbstractMultiPartHandler() {

        @Override
        protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Collection<Part> parts = request.getParts();
            Assert.assertEquals(1, parts.size());
            Part part = parts.iterator().next();
            Assert.assertEquals(name, part.getName());
            String contentType = part.getContentType();
            Assert.assertNotNull(contentType);
            int equal = contentType.lastIndexOf('=');
            Charset charset = Charset.forName(contentType.substring(equal + 1));
            Assert.assertEquals(encoding, charset);
            Assert.assertEquals(value, IO.toString(part.getInputStream(), charset));
        }
    });
    MultiPartContentProvider multiPart = new MultiPartContentProvider();
    HttpFields fields = new HttpFields();
    fields.put(HttpHeader.CONTENT_TYPE, "text/plain;charset=" + encoding.name());
    BytesContentProvider content = new BytesContentProvider(value.getBytes(encoding));
    multiPart.addFieldPart(name, content, fields);
    multiPart.close();
    ContentResponse response = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).method(HttpMethod.POST).content(multiPart).send();
    Assert.assertEquals(200, response.getStatus());
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Charset(java.nio.charset.Charset) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Part(javax.servlet.http.Part) HttpFields(org.eclipse.jetty.http.HttpFields) Collection(java.util.Collection) AbstractHttpClientServerTest(org.eclipse.jetty.client.AbstractHttpClientServerTest) Test(org.junit.Test)

Example 4 with Part

use of javax.servlet.http.Part in project jetty.project by eclipse.

the class MultiPartContentProviderTest method testFieldWithFile.

@Test
public void testFieldWithFile() throws Exception {
    // Prepare a file to upload.
    byte[] data = new byte[1024];
    new Random().nextBytes(data);
    Path tmpDir = MavenTestingUtils.getTargetTestingPath();
    Path tmpPath = Files.createTempFile(tmpDir, "multipart_", ".txt");
    try (OutputStream output = Files.newOutputStream(tmpPath, StandardOpenOption.CREATE)) {
        output.write(data);
    }
    String field = "field";
    String value = "€";
    String fileField = "file";
    Charset encoding = StandardCharsets.UTF_8;
    String contentType = "text/plain;charset=" + encoding.name();
    String headerName = "foo";
    String headerValue = "bar";
    start(new AbstractMultiPartHandler() {

        @Override
        protected void handle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            List<Part> parts = new ArrayList<>(request.getParts());
            Assert.assertEquals(2, parts.size());
            Part fieldPart = parts.get(0);
            Part filePart = parts.get(1);
            if (!field.equals(fieldPart.getName())) {
                Part swap = filePart;
                filePart = fieldPart;
                fieldPart = swap;
            }
            Assert.assertEquals(field, fieldPart.getName());
            Assert.assertEquals(contentType, fieldPart.getContentType());
            Assert.assertEquals(value, IO.toString(fieldPart.getInputStream(), encoding));
            Assert.assertEquals(headerValue, fieldPart.getHeader(headerName));
            Assert.assertEquals(fileField, filePart.getName());
            Assert.assertEquals("application/octet-stream", filePart.getContentType());
            Assert.assertEquals(tmpPath.getFileName().toString(), filePart.getSubmittedFileName());
            Assert.assertEquals(Files.size(tmpPath), filePart.getSize());
            Assert.assertArrayEquals(data, IO.readBytes(filePart.getInputStream()));
        }
    });
    MultiPartContentProvider multiPart = new MultiPartContentProvider();
    HttpFields fields = new HttpFields();
    fields.put(headerName, headerValue);
    multiPart.addFieldPart(field, new StringContentProvider(value, encoding), fields);
    multiPart.addFilePart(fileField, tmpPath.getFileName().toString(), new PathContentProvider(tmpPath), null);
    multiPart.close();
    ContentResponse response = client.newRequest("localhost", connector.getLocalPort()).scheme(scheme).method(HttpMethod.POST).content(multiPart).send();
    Assert.assertEquals(200, response.getStatus());
    Files.delete(tmpPath);
}
Also used : Path(java.nio.file.Path) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) OutputStream(java.io.OutputStream) Charset(java.nio.charset.Charset) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Random(java.util.Random) Part(javax.servlet.http.Part) HttpFields(org.eclipse.jetty.http.HttpFields) ArrayList(java.util.ArrayList) List(java.util.List) AbstractHttpClientServerTest(org.eclipse.jetty.client.AbstractHttpClientServerTest) Test(org.junit.Test)

Example 5 with Part

use of javax.servlet.http.Part in project jetty.project by eclipse.

the class MultiPartInputStreamParser method deleteParts.

/**
     * Delete any tmp storage for parts, and clear out the parts list.
     *
     * @throws MultiException if unable to delete the parts
     */
public void deleteParts() throws MultiException {
    Collection<Part> parts = getParsedParts();
    MultiException err = new MultiException();
    for (Part p : parts) {
        try {
            ((MultiPartInputStreamParser.MultiPart) p).cleanUp();
        } catch (Exception e) {
            err.add(e);
        }
    }
    _parts.clear();
    err.ifExceptionThrowMulti();
}
Also used : Part(javax.servlet.http.Part) IOException(java.io.IOException)

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