Java Code Examples for org.apache.cxf.helpers.IOUtils#readBytesFromStream()

The following examples show how to use org.apache.cxf.helpers.IOUtils#readBytesFromStream() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SoapPayloadConverterTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void convertXmlToValidCxfPayload() throws IOException, XMLStreamException {

    // read XML bytes as an XML Document
    ByteArrayInputStream bis = new ByteArrayInputStream(IOUtils.readBytesFromStream(inputStream));
    StaxUtils.read(bis);
    bis.reset();

    // convert XML to CxfPayload
    final Exchange exchange = createExchangeWithBody(bis);
    final Message in = exchange.getIn();
    requestConverter.process(exchange);

    final Object body = in.getBody();
    Assertions.assertThat(body).isInstanceOf(CxfPayload.class);
    @SuppressWarnings("unchecked")
    final CxfPayload<Source> cxfPayload = (CxfPayload<Source>) body;

    // validate every header and body part XML
    for (Source headerPart : cxfPayload.getHeaders()) {
        validateXml(headerPart);
    }
    for (Source bodyPart : cxfPayload.getBodySources()) {
        validateXml(bodyPart);
    }
}
 
Example 2
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadImageFromForm2() throws Exception {
    File file =
        new File(getClass().getResource("/org/apache/cxf/systest/jaxrs/resources/java.jpg")
                           .toURI().getPath());
    String address = "http://localhost:" + PORT + "/bookstore/books/formimage2";
    WebClient client = WebClient.create(address);
    client.type("multipart/form-data").accept("multipart/form-data");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
                                                        "true");
    MultipartBody body2 = client.post(file, MultipartBody.class);
    InputStream is2 = body2.getRootAttachment().getDataHandler().getInputStream();
    byte[] image1 = IOUtils.readBytesFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);
    ContentDisposition cd2 = body2.getRootAttachment().getContentDisposition();
    assertEquals("form-data;name=file;filename=java.jpg", cd2.toString());
    assertEquals("java.jpg", cd2.getParameter("filename"));
}
 
Example 3
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddGetImageWebClient() throws Exception {
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    String address = "http://localhost:" + PORT + "/bookstore/books/image";
    WebClient client = WebClient.create(address);
    client.type("multipart/mixed").accept("multipart/mixed");
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");
    InputStream is2 = client.post(is1, InputStream.class);
    byte[] image1 = IOUtils.readBytesFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);

}
 
Example 4
Source File: JMSTestMtom.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testMTOM() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/jms_mtom", "JMSMTOMService");
    QName portName = new QName("http://cxf.apache.org/jms_mtom", "MTOMPort");

    URL wsdl = getWSDLURL("/wsdl/jms_test_mtom.wsdl");
    JMSMTOMService service = new JMSMTOMService(wsdl, serviceName);

    JMSMTOMPortType mtom = service.getPort(portName, JMSMTOMPortType.class);
    Binding binding = ((BindingProvider)mtom).getBinding();
    ((SOAPBinding)binding).setMTOMEnabled(true);

    Holder<String> name = new Holder<>("Sam");
    URL fileURL = this.getClass().getResource("/org/apache/cxf/systest/jms/JMSClientServerTest.class");
    Holder<DataHandler> handler1 = new Holder<>();
    handler1.value = new DataHandler(fileURL);
    int size = handler1.value.getInputStream().available();
    mtom.testDataHandler(name, handler1);

    byte[] bytes = IOUtils.readBytesFromStream(handler1.value.getInputStream());
    Assert.assertEquals("The response file is not same with the sent file.", size, bytes.length);
    ((Closeable)mtom).close();
}
 
Example 5
Source File: JweContainerRequestFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext context) throws IOException {
    if (isMethodWithNoContent(context.getMethod())
        || isCheckEmptyStream() && !context.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(context.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    JweDecryptionOutput out = decrypt(encryptedContent);
    byte[] bytes = out.getContent();
    context.setEntityStream(new ByteArrayInputStream(bytes));
    context.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        context.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(context.getHeaders(), out.getHeaders());
    }
}
 
Example 6
Source File: JAXRSSoapBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void handleMessage(Message message) throws Fault {
    InputStream is = message.getContent(InputStream.class);
    if (is == null) {
        return;
    }
    byte[] payload;
    try {
        // input stream will be closed by readBytesFromStream()
        payload = IOUtils.readBytesFromStream(is);
        assertNotNull("payload was null", payload);
        assertTrue("payload was EMPTY", payload.length > 0);
        message.setContent(InputStream.class, new ByteArrayInputStream(payload));
    } catch (Exception e) {
        String error = "Failed to read the stream properly due to " + e.getMessage();
        assertNotNull(error, e);
    }
}
 
Example 7
Source File: JAXRSClientServerSpringBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testRetrieveBookAegis3() throws Exception {

    try (Socket s = new Socket("localhost", Integer.parseInt(PORT));
        InputStream is = this.getClass().getResourceAsStream("resources/retrieveRequest.txt")) {

        byte[] bytes = IOUtils.readBytesFromStream(is);
        s.getOutputStream().write(bytes);
        s.getOutputStream().flush();

        BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String str = null;
        while ((str = r.readLine()) != null) {
            sb.append(str);
        }

        String aegisData = sb.toString();
        s.getInputStream().close();
        s.close();
        assertTrue(aegisData.contains("CXF in Action - 2"));
    }

}
 
Example 8
Source File: JaxWsDynamicClientTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvocation() throws Exception {
    JaxWsDynamicClientFactory dcf =
        JaxWsDynamicClientFactory.newInstance();
    URL wsdlURL = new URL("http://localhost:" + PORT + "/NoBodyParts/NoBodyPartsService?wsdl");
    Client client = dcf.createClient(wsdlURL);
    byte[] bucketOfBytes =
        IOUtils.readBytesFromStream(getClass().getResourceAsStream("/wsdl/no_body_parts.wsdl"));
    Operation1 parameters = new Operation1();
    parameters.setOptionString("opt-ion");
    parameters.setTargetType("tar-get");
    Object[] rparts = client.invoke("operation1", parameters, bucketOfBytes);
    Operation1Response r = (Operation1Response)rparts[0];
    assertEquals(digest(bucketOfBytes), r.getStatus());

    ClientCallback callback = new ClientCallback();
    client.invoke(callback, "operation1", parameters, bucketOfBytes);
    rparts = callback.get();
    r = (Operation1Response)rparts[0];
    assertEquals(digest(bucketOfBytes), r.getStatus());
}
 
Example 9
Source File: JMSTestMtom.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testOutMTOM() throws Exception {
    QName serviceName = new QName("http://cxf.apache.org/jms_mtom", "JMSMTOMService");
    QName portName = new QName("http://cxf.apache.org/jms_mtom", "MTOMPort");

    URL wsdl = getWSDLURL("/wsdl/jms_test_mtom.wsdl");
    JMSOutMTOMService service = new JMSOutMTOMService(wsdl, serviceName);

    JMSMTOMPortType mtom = service.getPort(portName, JMSMTOMPortType.class);
    URL fileURL = this.getClass().getResource("/org/apache/cxf/systest/jms/JMSClientServerTest.class");
    DataHandler handler1 = new DataHandler(fileURL);
    int size = handler1.getInputStream().available();
    DataHandler ret = mtom.testOutMtom();

    byte[] bytes = IOUtils.readBytesFromStream(ret.getInputStream());
    Assert.assertEquals("The response file is not same with the original file.", size, bytes.length);
    ((Closeable)mtom).close();
}
 
Example 10
Source File: Client.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void uploadToCatalog(final String url, final CloseableHttpClient httpClient,
        final String filename) throws IOException {

    System.out.println("Sent HTTP POST request to upload the file into catalog: " + filename);

    final HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity();
    byte[] bytes = IOUtils.readBytesFromStream(Client.class.getResourceAsStream("/" + filename));
    entity.addPart(filename, new ByteArrayBody(bytes, filename));

    post.setEntity(entity);

    try {
        CloseableHttpResponse response = httpClient.execute(post);
        if (response.getStatusLine().getStatusCode() == 201) {
            System.out.println(response.getFirstHeader("Location"));
        } else if (response.getStatusLine().getStatusCode() == 409) {
            System.out.println("Document already exists: " + filename);
        }

    } finally {
        post.releaseConnection();
    }
}
 
Example 11
Source File: BinaryDataProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testReadFrom() throws Exception {
    MessageBodyReader p = new BinaryDataProvider();
    byte[] bytes = (byte[])p.readFrom(byte[].class, byte[].class, new Annotation[]{},
                                      MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                      new MetadataMap<String, Object>(),
                                      new ByteArrayInputStream("hi".getBytes()));
    assertArrayEquals(new String("hi").getBytes(), bytes);

    InputStream is = (InputStream)p.readFrom(InputStream.class, InputStream.class, new Annotation[]{},
                                             MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                             new MetadataMap<String, Object>(),
        new ByteArrayInputStream("hi".getBytes()));
    bytes = IOUtils.readBytesFromStream(is);
    assertArrayEquals(new String("hi").getBytes(), bytes);

    Reader r = (Reader)p.readFrom(Reader.class, Reader.class, new Annotation[]{},
                                  MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                  new MetadataMap<String, Object>(),
                                  new ByteArrayInputStream("hi".getBytes()));
    assertEquals(IOUtils.toString(r), "hi");

    StreamingOutput so = (StreamingOutput)p.readFrom(StreamingOutput.class, StreamingOutput.class,
                                  new Annotation[]{},
                                  MediaType.APPLICATION_OCTET_STREAM_TYPE,
                                  new MetadataMap<String, Object>(),
                                  new ByteArrayInputStream("hi".getBytes()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    so.write(baos);
    bytes = baos.toByteArray();
    assertArrayEquals(new String("hi").getBytes(), bytes);
}
 
Example 12
Source File: AbstractSignatureInFilter.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected byte[] verifyDigest(MultivaluedMap<String, String> headers, InputStream entityStream) {
    byte[] messageBody = null;
    if (!enabled) {
        return messageBody;
    }

    // Verify digest if we have the appropriate header and a non-empty request body. Note that it is up to
    // the MessageVerifier configuration, or the HTTPSignatureConstants.RSSEC_HTTP_SIGNATURE_IN_HEADERS
    // configuration to require that the digest is signed (and hence present)
    if (entityStream != null && headers.containsKey("Digest")) {
        LOG.fine("Digesting message body");
        try {
            messageBody = IOUtils.readBytesFromStream(entityStream);
        } catch (IOException e) {
            throw new DigestFailureException("failed to validate the digest", e);
        }
        DigestVerifier digestVerifier = new DigestVerifier();

        try {
            digestVerifier.inspectDigest(messageBody, headers);
        } catch (DigestFailureException | DifferentDigestsException | MissingDigestException ex) {
            Message message = PhaseInterceptorChain.getCurrentMessage();
            if (MessageUtils.isRequestor(message)) {
                throw ex;
            }
            throw new BadRequestException(ex);
        }
    }

    LOG.fine("Finished digest message verification process");
    return messageBody;
}
 
Example 13
Source File: MultipartStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@POST
@Path("/xop")
@Consumes("multipart/related")
@Produces("multipart/related;type=text/xml")
@Multipart("xop")
public XopType addBookXop(@Multipart XopType type) throws Exception {
    if (!"xopName".equals(type.getName())) {
        throw new RuntimeException("Wrong name property");
    }
    String bookXsd = IOUtils.readStringFromStream(type.getAttachinfo().getInputStream());
    String bookXsd2 = IOUtils.readStringFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    if (!bookXsd.equals(bookXsd2)) {
        throw new RuntimeException("Wrong attachinfo property");
    }
    String bookXsdRef = IOUtils.readStringFromStream(type.getAttachInfoRef().getInputStream());
    if (!bookXsdRef.equals(bookXsd2)) {
        throw new RuntimeException("Wrong attachinforef property");
    }
    if (!Boolean.getBoolean("java.awt.headless") && type.getImage() == null) {
        throw new RuntimeException("Wrong image property");
    }
    context.put(org.apache.cxf.message.Message.MTOM_ENABLED,
                "true");

    XopType xop = new XopType();
    xop.setName("xopName");
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
    byte[] data = IOUtils.readBytesFromStream(is);
    xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachinfo2(bookXsd.getBytes());

    xop.setImage(ImageIO.read(getClass().getResource(
            "/org/apache/cxf/systest/jaxrs/resources/java.jpg")));
    return xop;
}
 
Example 14
Source File: BpmnProcessRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static byte[] getDiagram(final String key) {
    BpmnProcessService service = getService(BpmnProcessService.class);
    WebClient.client(service).accept(RESTHeaders.MEDIATYPE_IMAGE_PNG);
    Response response = service.exportDiagram(key);

    byte[] diagram;
    try {
        diagram = IOUtils.readBytesFromStream((InputStream) response.getEntity());
    } catch (Exception e) {
        LOG.error("Could not get workflow diagram", e);
        diagram = new byte[0];
    }
    return diagram;
}
 
Example 15
Source File: BpmnProcessRestClient.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static byte[] getDiagram(final String key) {
    BpmnProcessService service = getService(BpmnProcessService.class);
    WebClient.client(service).accept(RESTHeaders.MEDIATYPE_IMAGE_PNG);
    Response response = service.exportDiagram(key);

    byte[] diagram;
    try {
        diagram = IOUtils.readBytesFromStream((InputStream) response.getEntity());
    } catch (Exception e) {
        LOG.error("Could not get workflow diagram", e);
        diagram = new byte[0];
    }
    return diagram;
}
 
Example 16
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadImageFromForm() throws Exception {
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    String address = "http://localhost:" + PORT + "/bookstore/books/formimage";
    WebClient client = WebClient.create(address);
    HTTPConduit conduit = WebClient.getConfig(client).getHttpConduit();
    conduit.getClient().setReceiveTimeout(1000000);
    conduit.getClient().setConnectionTimeout(1000000);
    client.type("multipart/form-data").accept("multipart/form-data");

    ContentDisposition cd = new ContentDisposition("attachment;filename=java.jpg");
    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-ID", "image");
    headers.putSingle("Content-Disposition", cd.toString());
    headers.putSingle("Content-Location", "http://host/bar");
    headers.putSingle("custom-header", "custom");
    Attachment att = new Attachment(is1, headers);

    MultipartBody body = new MultipartBody(att);
    MultipartBody body2 = client.post(body, MultipartBody.class);
    InputStream is2 = body2.getRootAttachment().getDataHandler().getInputStream();
    byte[] image1 = IOUtils.readBytesFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);
    ContentDisposition cd2 = body2.getRootAttachment().getContentDisposition();
    assertEquals("attachment;filename=java.jpg", cd2.toString());
    assertEquals("java.jpg", cd2.getParameter("filename"));
    assertEquals("http://host/location", body2.getRootAttachment().getHeader("Content-Location"));
}
 
Example 17
Source File: NioBookStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getBookStream() throws IOException {
    final ByteArrayInputStream in = new ByteArrayInputStream(
        IOUtils.readBytesFromStream(getClass().getResourceAsStream("/files/books.txt")));
    final byte[] buffer = new byte[4096];

    return Response
        .ok()
        .entity(
            new NioWriteEntity(
            out -> {
                final int n = in.read(buffer);

                if (n >= 0) {
                    out.write(buffer, 0, n);
                    return true;
                }

                closeInputStream(in);

                return false;
            }
            // by default the runtime will throw the exception itself
            // if the error handler is not provided
            
            //,
            //throwable -> {
            //    throw throwable;
            //}
        ))
        .build();
}
 
Example 18
Source File: ClientServerSwaTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testSwaTypesWithDispatchAPI() throws Exception {
    URL url1 = this.getClass().getResource("resources/attach.text");
    URL url2 = this.getClass().getResource("resources/attach.html");
    URL url3 = this.getClass().getResource("resources/attach.xml");
    URL url4 = this.getClass().getResource("resources/attach.jpeg1");
    URL url5 = this.getClass().getResource("resources/attach.jpeg2");


    byte[] bytes = IOUtils.readBytesFromStream(url1.openStream());
    byte[] bigBytes = new byte[bytes.length * 50];
    for (int x = 0; x < 50; x++) {
        System.arraycopy(bytes, 0, bigBytes, x * bytes.length, bytes.length);
    }

    DataHandler dh1 = new DataHandler(new ByteArrayDataSource(bigBytes, "text/plain"));
    DataHandler dh2 = new DataHandler(url2);
    DataHandler dh3 = new DataHandler(url3);
    DataHandler dh4 = new DataHandler(url4);
    DataHandler dh5 = new DataHandler(url5);

    SwAService service = new SwAService();

    Dispatch<SOAPMessage> disp = service
        .createDispatch(SwAService.SwAServiceHttpPort,
                        SOAPMessage.class,
                        Service.Mode.MESSAGE);
    setAddress(disp, "http://localhost:" + serverPort + "/swa");


    SOAPMessage msg = MessageFactory.newInstance().createMessage();
    SOAPBody body = msg.getSOAPPart().getEnvelope().getBody();
    body.addBodyElement(new QName("http://cxf.apache.org/swa/types",
                                  "VoidRequest"));

    AttachmentPart att = msg.createAttachmentPart(dh1);
    att.setContentId("<[email protected]>");
    msg.addAttachmentPart(att);

    att = msg.createAttachmentPart(dh2);
    att.setContentId("<[email protected]>");
    msg.addAttachmentPart(att);

    att = msg.createAttachmentPart(dh3);
    att.setContentId("<[email protected]>");
    msg.addAttachmentPart(att);

    att = msg.createAttachmentPart(dh4);
    att.setContentId("<[email protected]>");
    msg.addAttachmentPart(att);

    att = msg.createAttachmentPart(dh5);
    att.setContentId("<[email protected]>");
    msg.addAttachmentPart(att);

    //Test for CXF-
    msg = disp.invoke(msg);
    assertEquals(5, msg.countAttachments());

}
 
Example 19
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testXopWebClient() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/xop";
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);
    bean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED,
                                                (Object)"true"));
    WebClient client = bean.createWebClient();
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart",
        "true");
    client.type("multipart/related").accept("multipart/related");

    XopType xop = new XopType();
    xop.setName("xopName");
    InputStream is =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
    byte[] data = IOUtils.readBytesFromStream(is);
    xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));

    String bookXsd = IOUtils.readStringFromStream(getClass().getResourceAsStream(
        "/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    xop.setAttachinfo2(bookXsd.getBytes());

    xop.setImage(getImage("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));

    XopType xop2 = client.post(xop, XopType.class);

    String bookXsdOriginal = IOUtils.readStringFromStream(getClass().getResourceAsStream(
            "/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    String bookXsd2 = IOUtils.readStringFromStream(xop2.getAttachinfo().getInputStream());
    assertEquals(bookXsdOriginal, bookXsd2);
    String bookXsdRef = IOUtils.readStringFromStream(xop2.getAttachInfoRef().getInputStream());
    assertEquals(bookXsdOriginal, bookXsdRef);

    String ctString =
        client.getResponse().getMetadata().getFirst("Content-Type").toString();
    MediaType mt = MediaType.valueOf(ctString);
    Map<String, String> params = mt.getParameters();
    assertEquals(4, params.size());
    assertNotNull(params.get("boundary"));
    assertNotNull(params.get("type"));
    assertNotNull(params.get("start"));
    assertNotNull(params.get("start-info"));
}
 
Example 20
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testAddBookJaxbJsonImageWebClientRelated2() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/books/jaxbimagejson";
    WebClient client = WebClient.create(address);
    WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    client.type("multipart/mixed").accept("multipart/mixed");

    Book jaxb = new Book("jaxb", 1L);
    Book json = new Book("json", 2L);
    InputStream is1 =
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg");
    Map<String, Object> objects = new LinkedHashMap<>();

    MultivaluedMap<String, String> headers = new MetadataMap<>();
    headers.putSingle("Content-Type", "application/xml");
    headers.putSingle("Content-ID", "theroot");
    headers.putSingle("Content-Transfer-Encoding", "customxml");
    Attachment attJaxb = new Attachment(headers, jaxb);

    headers = new MetadataMap<>();
    headers.putSingle("Content-Type", "application/json");
    headers.putSingle("Content-ID", "thejson");
    headers.putSingle("Content-Transfer-Encoding", "customjson");
    Attachment attJson = new Attachment(headers, json);

    headers = new MetadataMap<>();
    headers.putSingle("Content-Type", "application/octet-stream");
    headers.putSingle("Content-ID", "theimage");
    headers.putSingle("Content-Transfer-Encoding", "customstream");
    Attachment attIs = new Attachment(headers, is1);

    objects.put(MediaType.APPLICATION_XML, attJaxb);
    objects.put(MediaType.APPLICATION_JSON, attJson);
    objects.put(MediaType.APPLICATION_OCTET_STREAM, attIs);

    Collection<? extends Attachment> coll = client.postAndGetCollection(objects, Attachment.class);
    List<Attachment> result = new ArrayList<>(coll);
    Book jaxb2 = readBookFromInputStream(result.get(0).getDataHandler().getInputStream());
    assertEquals("jaxb", jaxb2.getName());
    assertEquals(1L, jaxb2.getId());
    Book json2 = readJSONBookFromInputStream(result.get(1).getDataHandler().getInputStream());
    assertEquals("json", json2.getName());
    assertEquals(2L, json2.getId());
    InputStream is2 = result.get(2).getDataHandler().getInputStream();
    byte[] image1 = IOUtils.readBytesFromStream(
        getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    byte[] image2 = IOUtils.readBytesFromStream(is2);
    assertArrayEquals(image1, image2);
}