Example usage for org.apache.commons.fileupload RequestContext RequestContext

List of usage examples for org.apache.commons.fileupload RequestContext RequestContext

Introduction

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

Prototype

RequestContext

Source Link

Usage

From source file:io.agi.framework.coordination.http.HttpImportHandler.java

@Override
public void handle(HttpExchange t) throws IOException {

    int status = 400;
    String response = "";

    //for(Map.Entry<String, List<String> > header : t.getRequestHeaders().entrySet()) {
    //    System.out.println(header.getKey() + ": " + header.getValue().get(0));
    //}/*from w  ww  .  j  ava  2  s.c om*/

    // Based on accepted answer: http://stackoverflow.com/questions/33732110/file-upload-using-httphandler
    DiskFileItemFactory d = new DiskFileItemFactory();

    try {
        ServletFileUpload up = new ServletFileUpload(d);
        List<FileItem> result = up.parseRequest(new RequestContext() {

            @Override
            public String getCharacterEncoding() {
                return "UTF-8";
            }

            @Override
            public int getContentLength() {
                return 0; //tested to work with 0 as return
            }

            @Override
            public String getContentType() {
                return t.getRequestHeaders().getFirst("Content-type");
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return t.getRequestBody();
            }

        });

        for (FileItem fi : result) {

            //System.out.println( "File-Item: " + fi.getFieldName() + " = " + fi.getName() );

            String value = fi.getString();

            if (value == null) {
                continue;
            }

            //System.out.print( value );

            String fieldName = fi.getFieldName();

            if (fieldName.equalsIgnoreCase("entity-file")) {
                PersistenceUtil.ImportEntities(value);
                status = 200;
                response = response + "Imported Entities from: " + fi.getName() + "\n";

                _logger.info("Import: entities file: " + fi.getName());
            } else if (fieldName.equalsIgnoreCase("data-file")) {
                DataRefUtil.ImportData(value);
                status = 200;
                response = response + "Imported Data from: " + fi.getName() + "\n";

                _logger.info("Import: data file: " + fi.getName());
            }
        }

    } catch (Exception e) {
        _logger.error("Unable to import entities/data.");
        _logger.error(e.toString(), e);
    }

    HttpUtil.SendResponse(t, status, response);
}

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  ww  w.  ja va2 s .c  o  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:com.aspectran.web.activity.request.multipart.MultipartFormDataParser.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * /* ww  w .  jav a 2  s  .  c o  m*/
 * @param req the HTTP request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        @Override
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

        @Override
        public String getContentType() {
            return req.getContentType();
        }

        @Override
        @Deprecated
        public int getContentLength() {
            return req.getContentLength();
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:gov.nih.nci.caarray.web.fileupload.MonitoredMultiPartRequest.java

private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }// w  w  w . jav  a  2 s . co m

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

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

        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:hk.hku.cecid.corvus.ws.EBMSMessageHistoryQuerySenderTest.java

private EBMSMessageHistoryRequestData getHttpRequestData() throws Exception {
    // Check content Type
    String contentType = monitor.getContentType();

    if (contentType == null) {
        System.out.println((monitor == null ? "Null Monitor" : "Monitor not null"));
        System.out.println("Lengeth " + monitor.getContentLength());
        Assert.fail("Null Content");
    }/*from  w ww  . ja  va 2 s .c o  m*/

    String mediaType = contentType.split(";")[0];
    assertEquals("Invalid content type", "text/xml", mediaType);

    // 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=utf-8";
        }

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

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

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

    BufferedReader bReader = new BufferedReader(new InputStreamReader(monitor.getInputStream()));

    String strLine = "";
    do {
        strLine = bReader.readLine();
    } while (!strLine.contains("SOAP-ENV"));

    MimeHeaders header = new MimeHeaders();
    header.addHeader("Content-Type", "text/xml");

    SOAPMessage msg = MessageFactory.newInstance().createMessage(header,
            new ByteArrayInputStream(strLine.getBytes()));

    EBMSMessageHistoryRequestData data = new EBMSMessageHistoryRequestData();
    data.setMessageId(getElementValue(msg.getSOAPBody(), "tns:messageId"));
    data.setMessageBox(getElementValue(msg.getSOAPBody(), "tns:messageBox"));
    data.setStatus(getElementValue(msg.getSOAPBody(), "tns:status"));
    data.setService(getElementValue(msg.getSOAPBody(), "tns:service"));
    data.setAction(getElementValue(msg.getSOAPBody(), "tns:action"));
    data.setConversationId(getElementValue(msg.getSOAPBody(), "tns:conversationId"));
    data.setCpaId(getElementValue(msg.getSOAPBody(), "tns:cpaId"));
    return data;
}

From source file:bijian.util.upload.MyMultiPartRequest.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 *
 * @param req  the request./*  www  .j ava 2 s .c  o  m*/
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

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

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

        public InputStream getInputStream() throws IOException {
            InputStream in = req.getInputStream();
            if (in == null) {
                throw new IOException("Missing content in the request");
            }
            return req.getInputStream();
        }
    };
}

From source file:com.ultrapower.eoms.common.plugin.ajaxupload.AjaxMultiPartRequest.java

/**
 * Creates a RequestContext needed by Jakarta Commons Upload.
 * //from  ww w.  j a va  2s.c  om
 * @param req
 *            the request.
 * @return a new request context.
 */
private RequestContext createRequestContext(final HttpServletRequest req) {
    return new RequestContext() {
        public String getCharacterEncoding() {
            return req.getCharacterEncoding();
        }

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

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

        public InputStream getInputStream() throws IOException {
            return req.getInputStream();
        }
    };
}

From source file:org.cellprofiler.subimager.ImageWriterHandler.java

public void handle(HttpExchange exchange) throws IOException {
    if (!exchange.getRequestMethod().equals("POST")) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_METHOD,
                "<html><body>writeimage only accepts HTTP post</body></html>");
        return;/*from  www .j a va2 s  . c o m*/
    }
    final String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
    if (contentType == null) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>No Content-type request header</body></html>");
        return;
    }
    if (!contentType.startsWith(MULTIPART_FORM_DATA)) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Content type must be " + MULTIPART_FORM_DATA + ".</body></html>");
        return;
    }
    int idx = contentType.indexOf(BOUNDARY_EQUALS, MULTIPART_FORM_DATA.length());
    if (idx == -1) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>Did not find boundary identifier in multipart/form-data content type.</body></html>");
        return;
    }
    final String contentEncoding = exchange.getRequestHeaders().getFirst("Content-Encoding");
    String contentLengthString = exchange.getRequestHeaders().getFirst("Content-Length");
    if (contentLengthString == null) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                "<html><body>No Content-Length request header</body></html>");
        return;
    }
    try {
        Integer.parseInt(contentLengthString);
    } catch (NumberFormatException e) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("<html><body>Content length was not a number: %s</body></html>", contentLengthString));
        return;
    }
    final int contentLength = Integer.parseInt(contentLengthString);
    final InputStream requestBodyStream = exchange.getRequestBody();
    FileUpload upload = new FileUpload();
    FileItemIterator fileItemIterator;
    String omeXML = null;
    URI uri = null;
    int index = 0;
    NDImage ndimage = null;
    String compression = DEFAULT_COMPRESSION;
    try {
        fileItemIterator = upload.getItemIterator(new RequestContext() {

            public String getCharacterEncoding() {
                return contentEncoding;
            }

            public String getContentType() {
                return contentType;
            }

            public int getContentLength() {
                return contentLength;
            }

            public InputStream getInputStream() throws IOException {
                return requestBodyStream;
            }
        });
        while (fileItemIterator.hasNext()) {
            FileItemStream fis = fileItemIterator.next();
            String name = fis.getFieldName();

            if (name.equals(NAME_IMAGE)) {
                String imageContentType = fis.getContentType();
                if (imageContentType == null) {
                    reportError(exchange, HttpURLConnection.HTTP_UNSUPPORTED_TYPE,
                            "<html><body>Image form-data field must have a content type.</body></html>");
                    return;
                }
                try {
                    InputStream is = SubimagerUtils.getInputStream(exchange, fis);
                    if (is == null)
                        return;
                    ndimage = NDImage.decode(is);
                } catch (MalformedStreamException e) {
                    reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                            "<html><body>Failed to read body for part, " + name + ".</body></html>");
                } catch (IOException e) {
                    reportError(exchange, HttpURLConnection.HTTP_INTERNAL_ERROR,
                            "<html><body>Failed to read multipart body data</body></html>");
                    return;
                } catch (org.cellprofiler.subimager.NDImage.FormatException e) {
                    reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                            "<html><body>Image data was not in correct format: " + e.getMessage()
                                    + "</body></html>");
                    return;
                }
            } else {
                String partDataString = SubimagerUtils.readFully(exchange, fis);
                if (partDataString == null)
                    return;
                if (name.equals(NAME_INDEX)) {
                    try {
                        index = Integer.parseInt(partDataString);
                    } catch (NumberFormatException e) {
                        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                                "<html><body>Index form-data field must be a number: " + partDataString
                                        + ".</body></html>");
                        return;
                    }
                } else if (name.equals(NAME_OMEXML)) {
                    omeXML = partDataString;
                } else if (name.equals(NAME_URL)) {
                    try {
                        uri = new URI(partDataString);
                    } catch (URISyntaxException e) {
                        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                                "<html><body>Improperly formatted URL: " + partDataString + ".</body></html>");
                        return;
                    }
                } else if (name.equals(NAME_COMPRESSION)) {
                    compression = partDataString;
                }
            }
        }
        if (ndimage == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have an image part</body></html>");
            return;
        }
        if (uri == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have a URL part</body></html>");
            return;
        }
        if (omeXML == null) {
            reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST,
                    "<html><body>Request did not have an omexml part</body></html>");
            return;
        }
        writeImage(exchange, ndimage, uri, omeXML, index, compression);
    } catch (FileUploadException e) {
        reportError(exchange, HttpURLConnection.HTTP_BAD_REQUEST, String
                .format("<html><body>Parsing error in multipart message: %s</body></html>", e.getMessage()));
        return;
    }
}

From source file:org.cellprofiler.subimager.TestImageJHandlerBase.java

protected Response post(Request request, Map<String, NDImage> ndimagesIn, Map<String, NDImage> ndimagesOut) {
    StringWriter writer = new StringWriter();
    try {//from  w  w  w  .j  a  v  a 2  s.c om
        Marshaller marshaller = new Marshaller(writer);
        marshaller.marshal(request);
    } catch (MarshalException e2) {
        throw new AssertionError(e2.getMessage());
    } catch (ValidationException e2) {
        throw new AssertionError(e2.getMessage());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        throw new AssertionError(e.getMessage());
    }
    String xml = writer.toString();

    ArrayList<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart(ImageJHandler.NAME_REQUEST, xml));
    String sURL = String.format("http://localhost:%d/imagej", getPort());
    final PostMethod post = new PostMethod(sURL);
    for (Map.Entry<String, NDImage> entry : ndimagesIn.entrySet()) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            entry.getValue().encode(bos);
        } catch (IOException e1) {
            e1.printStackTrace();
            throw new AssertionError("Failed to encode image: " + e1.getMessage());
        }
        ByteArrayPartSource src = new ByteArrayPartSource(entry.getKey(), bos.toByteArray());
        FilePart filePart = new FilePart(entry.getKey(), src, "application/octet-stream", "binary");
        parts.add(filePart);
    }
    post.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), post.getParams()));
    HttpClient client = new HttpClient();
    int responseCode;
    try {
        responseCode = client.executeMethod(post);
    } catch (HttpException e) {
        throw new AssertionError(e.getMessage());
    } catch (IOException e) {
        throw new AssertionError(e.getMessage());
    }
    assertEquals(HttpURLConnection.HTTP_OK, responseCode);
    final String contentType = post.getResponseHeader("Content-Type").getValue();
    assertTrue(contentType.startsWith("multipart/form-data"));
    final long contentLength = post.getResponseContentLength();
    try {
        final InputStream responseBodyStream = post.getResponseBodyAsStream();
        FileUpload upload = new FileUpload();
        FileItemIterator fileItemIterator;
        fileItemIterator = upload.getItemIterator(new RequestContext() {

            public String getCharacterEncoding() {
                if (post.getResponseHeader("Content-Encoding") == null)
                    return null;
                return post.getResponseHeader("Content-Encoding").getValue();
            }

            public String getContentType() {
                return contentType;
            }

            public int getContentLength() {
                return (int) contentLength;
            }

            InputStream tmpStream = null;

            public InputStream getInputStream() throws IOException {
                if (tmpStream == null) {
                    byte[] buf = new byte[(int) contentLength];
                    int offset = 0;
                    while (offset < buf.length) {
                        offset += responseBodyStream.read(buf, offset, buf.length - offset);
                    }
                    tmpStream = new ByteArrayInputStream(buf);
                }
                return tmpStream;
            }
        });
        assertTrue(fileItemIterator.hasNext());
        FileItemStream fis = fileItemIterator.next();
        assertEquals(fis.getFieldName(), ImageJHandler.NAME_RESPONSE);
        Reader rdr = new InputStreamReader(fis.openStream(), "utf-8");
        Unmarshaller unmarshaller = new Unmarshaller(Response.class);
        unmarshaller.setProperty(XMLProperties.LENIENT_INTEGER_VALIDATION, "true");
        Object oresponse = unmarshaller.unmarshal(rdr);
        assertTrue(oresponse instanceof Response);
        Response response = (Response) oresponse;
        while (fileItemIterator.hasNext()) {
            fis = fileItemIterator.next();
            String name = fis.getFieldName();
            NDImage ndimage = NDImage.decode(fis.openStream());
            ndimagesOut.put(name, ndimage);
        }
        return response;
    } catch (IOException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (FileUploadException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (MarshalException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (ValidationException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    } catch (FormatException e) {
        e.printStackTrace();
        throw new AssertionError(e.getMessage());
    }

}

From source file:org.jwifisd.eyefi.Main3.java

public static void main(String[] args) throws Exception {
    MultipartStream stream = new MultipartStream(
            new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430"),
            "---------------------------02468ace13579bdfcafebabef00d".getBytes());
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    String readHeaders = stream.readHeaders();
    System.out.println(readHeaders.toString());
    stream.readBodyData(output);//from  w  w w. ja v  a2  s.  c om
    output = new ByteArrayOutputStream();
    readHeaders = stream.readHeaders();
    System.out.println(readHeaders.toString());
    stream.readBodyData(output);

    final InputStream in = new FileInputStream("src/main/resources/NanoHTTPD-977513220698581430");

    FileItemIterator iter = new FileUpload().getItemIterator(new RequestContext() {

        @Override
        public InputStream getInputStream() throws IOException {
            return in;
        }

        @Override
        public String getContentType() {
            // TODO Auto-generated method stub
            return "multipart/form-data; boundary=---------------------------02468ace13579bdfcafebabef00d";
        }

        @Override
        public int getContentLength() {
            return 4237763;
        }

        @Override
        public String getCharacterEncoding() {
            // TODO Auto-generated method stub
            return "UTF-8";
        }
    });

    while (iter.hasNext()) {
        FileItemStream item = iter.next();

        System.out.println("name:" + item.getName());
        System.out.println("name:" + item.getContentType());
        //item.openStream();

    }
}