Example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity writeRequest

List of usage examples for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity writeRequest

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods.multipart MultipartRequestEntity writeRequest.

Prototype

public void writeRequest(OutputStream paramOutputStream) throws IOException 

Source Link

Usage

From source file:net.formio.portlet.MockPortletRequests.java

/**
 * Creates new portlet request that contains given resource as multi part.
 * @param paramName/*from ww  w .jav  a 2s. co m*/
 * @param resourceName
 * @return
 */
public static MockMultipartActionRequest newRequest(String paramName, String resourceName, String mimeType) {
    try {
        MockMultipartActionRequest request = new MockMultipartActionRequest();
        // Load resource being uploaded
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Streams.copy(MockPortletRequests.class.getResourceAsStream(resourceName), bos, true);
        byte[] fileContent = bos.toByteArray();

        // Create part & entity from resource
        Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent),
                mimeType, (String) null) };
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
                new PostMethod().getParams());

        ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
        multipartRequestEntity.writeRequest(requestContent);
        request.setContent(requestContent.toByteArray());
        // Set content type of request (important, includes MIME boundary string)
        String contentType = multipartRequestEntity.getContentType();
        request.setContentType(contentType);
        return request;
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:net.formio.servlet.MockServletRequests.java

/**
 * Creates new servlet request that contains given resource as multi part.
 * @param paramName//from w w  w.  j a va  2s  .  c  om
 * @param resourceName
 * @return
 */
public static MockHttpServletRequest newRequest(String paramName, String resourceName, String mimeType) {
    try {
        MockHttpServletRequest request = new MockHttpServletRequest();
        // Load resource being uploaded
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Streams.copy(MockServletRequests.class.getResourceAsStream(resourceName), bos, true);
        byte[] fileContent = bos.toByteArray();

        // Create part & entity from resource
        Part[] parts = new Part[] { new FilePart(paramName, new ByteArrayPartSource(resourceName, fileContent),
                mimeType, (String) null) };
        MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
                new PostMethod().getParams());

        ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
        multipartRequestEntity.writeRequest(requestContent);
        request.setContent(requestContent.toByteArray());
        // Set content type of request (important, includes MIME boundary string)
        String contentType = multipartRequestEntity.getContentType();
        request.setContentType(contentType);
        request.setMethod("POST");
        return request;
    } catch (IOException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }
}

From source file:net.sf.j2ep.test.PostTest.java

public void beginSendMultipart(WebRequest theRequest) {
    theRequest.setURL("localhost:8080", "/test", "/POST/multipart.jsp", null, null);
    theRequest.addParameter("tmp", "", WebRequest.POST_METHOD);

    try {//from www . j a  va2 s  .c o  m
        PostMethod post = new PostMethod();
        FilePart filePart = new FilePart("theFile", new File("WEB-INF/classes/net/sf/j2ep/test/POSTdata"));
        StringPart stringPart = new StringPart("testParam", "123456");
        Part[] parts = new Part[2];
        parts[0] = stringPart;
        parts[1] = filePart;
        MultipartRequestEntity reqEntitiy = new MultipartRequestEntity(parts, post.getParams());

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        reqEntitiy.writeRequest(outStream);

        theRequest.setUserData(new ByteArrayInputStream(outStream.toByteArray()));
        theRequest.addHeader("content-type", reqEntitiy.getContentType());
    } catch (FileNotFoundException e) {
        fail("File was not found " + e.getMessage());
    } catch (IOException e) {
        fail("IOException");
        e.printStackTrace();
    }
}

From source file:eu.impact_project.iif.t2.client.HelperTest.java

/**
 * Test of parseRequest method, of class Helper.
 *///www.  j  av  a 2  s  .  co  m
@Test
public void testParseRequest() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    URL url = this.getClass().getResource("/prueba.txt");
    File testFile = new File(url.getFile());
    Part[] parts = new Part[] { new StringPart("user", "user"), new FilePart("file_workflow", testFile),
            new FilePart("comon_file", testFile) };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    Helper.parseRequest(request);

}

From source file:info.magnolia.cms.filters.MultipartRequestFilterTest.java

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    final MultipartRequestEntity multipart = newMultipartRequestEntity();
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    multipart.writeRequest(output);
    final byte[] bytes = output.toByteArray();
    final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes);
    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override// w  w  w .j a v  a2 s  .  c  o  m
        public int read() throws IOException {
            return delegateStream.read();
        }
    };

    req.setAttribute(isA(String.class), isA(Boolean.class));
    expect(req.getContentType()).andReturn(multipart.getContentType()).anyTimes();
    expect(req.getHeader("Content-Type")).andReturn(multipart.getContentType()).anyTimes();
    expect(req.getCharacterEncoding()).andReturn("UTF-8").anyTimes();
    expect(req.getQueryString()).andReturn("").anyTimes();
    expect(req.getContentLength()).andReturn(Integer.valueOf((int) multipart.getContentLength())).anyTimes();
    expect(req.getInputStream()).andReturn(servletInputStream);
    req.setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override
        public Object answer() throws Throwable {
            final Object[] args = getCurrentArguments();
            checkMultipartForm((MultipartForm) args[1], expectedDocumentType);
            return null;
        }
    });
    webCtx.pop();

    replay(req, res, filterChain, webCtx);
    filter.doFilter(req, res, filterChain);
    verify(req, res, filterChain, webCtx);
}

From source file:info.magnolia.cms.filters.MultipartRequestFilterTempFileDeletionTest.java

public void doTest(Filter filter, final String expectedDocumentType) throws Throwable {
    //GIVEN// w  w w . j  a v  a2 s.  c om
    final MultipartRequestEntity multipart = newMultipartRequestEntity();
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    multipart.writeRequest(output);
    final byte[] bytes = output.toByteArray();
    final ByteArrayInputStream delegateStream = new ByteArrayInputStream(bytes);
    final ServletInputStream servletInputStream = new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return delegateStream.read();
        }
    };

    //WHEN
    req.setAttribute(isA(String.class), isA(Boolean.class));
    when(req.getContentType()).thenReturn(multipart.getContentType());
    when(req.getHeader("Content-Type")).thenReturn(multipart.getContentType());
    when(req.getCharacterEncoding()).thenReturn("UTF-8");
    when(req.getQueryString()).thenReturn("");
    when(req.getContentLength()).thenReturn(Integer.valueOf((int) multipart.getContentLength()));
    when(req.getInputStream()).thenReturn(servletInputStream);

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final Object args = invocation.getArguments()[1];
            checkMultipartForm((MultipartForm) args, expectedDocumentType);
            webCtx.setPostedForm((MultipartForm) args);
            return null;
        }
    }).when(req).setAttribute(eq(MultipartForm.REQUEST_ATTRIBUTE_NAME), isA(MultipartForm.class));
    when(file.exists()).thenReturn(true);

    webCtx.pop();

    //THEN
    filter.doFilter(req, res, filterChain);
}

From source file:fr.paris.lutece.portal.web.upload.UploadServletTest.java

private MockHttpServletRequest getMultipartRequest() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    byte[] fileContent = new byte[] { 1, 2, 3 };
    Part[] parts = new Part[] { new FilePart("file1", new ByteArrayPartSource("file1", fileContent)) };
    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());
    // Serialize request body
    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(requestContent);
    // Set request body to HTTP servlet request
    request.setContent(requestContent.toByteArray());
    // Set content type to HTTP servlet request (important, includes Mime boundary string)
    request.setContentType(multipartRequestEntity.getContentType());
    request.setMethod("POST");
    return request;
}

From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *///  w  ww  . j a v a 2s  . c  o m
@Test
public void testDoPost() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://www.ua.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:eu.impact_project.iif.t2.client.WorkflowRunnerTest.java

/**
 * Test of doPost method, of class WorkflowRunner.
 *//* w ww  .j  a  v  a  2  s . c om*/
@Test
public void testDoPostURLFail() throws Exception {
    HttpServletRequest request = mock(HttpServletRequest.class);
    HttpServletResponse response = mock(HttpServletResponse.class);
    ServletConfig config = mock(ServletConfig.class);
    ServletContext context = mock(ServletContext.class);
    RequestDispatcher dispatcher = mock(RequestDispatcher.class);
    ServletOutputStream stream = mock(ServletOutputStream.class);
    HttpSession session = mock(HttpSession.class);

    when(request.getSession(true)).thenReturn(session);

    ArrayList<Workflow> flowList = new ArrayList<>();
    Workflow flow = new Workflow();
    flow.setStringVersion("Esto es una prueba");
    flow.setWsdls("<wsdl>http://www.ua.es</wsdl>");
    flow.setUrls("http://falsa.es");

    ArrayList<WorkflowInput> flowInputs = new ArrayList<>();
    WorkflowInput input = new WorkflowInput("pru0Input");
    input.setDepth(1);
    flowInputs.add(input);

    input = new WorkflowInput("pru1Input");
    input.setDepth(0);
    flowInputs.add(input);

    flow.setInputs(flowInputs);

    flowList.add(flow);
    when(session.getAttribute("workflows")).thenReturn(flowList);

    when(config.getServletContext()).thenReturn(context);
    URL url = this.getClass().getResource("/config.properties");
    File testFile = new File(url.getFile());
    when(context.getRealPath("/")).thenReturn(testFile.getParent() + "/");

    Part[] parts = new Part[] { new StringPart("user", "user"), new StringPart("pass", "pass"),
            new StringPart("workflow0pru0Input", "prueba0"), new StringPart("workflow0pru0Input0", "prueba0.0"),
            new StringPart("workflow0pru1Input", "prueba1")

    };

    MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());

    ByteArrayOutputStream requestContent = new ByteArrayOutputStream();

    multipartRequestEntity.writeRequest(requestContent);

    final ByteArrayInputStream inputContent = new ByteArrayInputStream(requestContent.toByteArray());

    when(request.getInputStream()).thenReturn(new ServletInputStream() {
        @Override
        public int read() throws IOException {
            return inputContent.read();
        }
    });

    when(request.getContentType()).thenReturn(multipartRequestEntity.getContentType());

    WorkflowRunner runer = new WorkflowRunner();
    try {
        runer.init(config);
        runer.doPost(request, response);

    } catch (ServletException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (IOException ex) {
        fail("Should not raise exception " + ex.toString());
    } catch (NullPointerException ex) {
        //ok no funciona el server de taverna
    }
}

From source file:ch.sportchef.business.event.bundary.EventImageResourceTest.java

@Test
public void uploadImageWithOK() throws IOException, ServletException {
    // arrange//w w  w. j ava2  s.c  om
    final byte[] fileContent = readTestImage();
    final Part[] parts = new Part[] {
            new FilePart(TEST_IMAGE_NAME, new ByteArrayPartSource(TEST_IMAGE_NAME, fileContent)) };
    final MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts,
            new PostMethod().getParams());
    final ByteArrayOutputStream requestContent = new ByteArrayOutputStream();
    multipartRequestEntity.writeRequest(requestContent);
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(requestContent.toByteArray());
    final ServletInputStreamMock inputStreamMock = new ServletInputStreamMock(inputStream);
    final String contentType = multipartRequestEntity.getContentType();

    expect(httpServletRequest.getContentType()).andStubReturn(contentType);
    expect(httpServletRequest.getInputStream()).andStubReturn(inputStreamMock);

    eventImageServiceMock.uploadImage(anyLong(), anyObject());
    mockProvider.replayAll();

    // act
    final Response response = eventImageResource.uploadImage(httpServletRequest);

    // assert
    assertThat(response.getStatus(), is(OK.getStatusCode()));
    mockProvider.verifyAll();
}