Java Code Examples for org.apache.cxf.message.MessageImpl#put()

The following examples show how to use org.apache.cxf.message.MessageImpl#put() . 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: XACMLAuthorizingInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testDeny() throws Exception {
    // Mock up a Security Context
    SecurityContext sc = createSecurityContext("alice", "boss");

    String operation = "{http://www.example.org/contract/DoubleIt}DoubleIt";
    MessageImpl msg = new MessageImpl();
    msg.put(Message.WSDL_OPERATION, QName.valueOf(operation));
    String service = "{http://www.example.org/contract/DoubleIt}DoubleItService";
    msg.put(Message.WSDL_SERVICE, QName.valueOf(service));
    String resourceURI = "https://localhost:8080/doubleit";
    msg.put(Message.REQUEST_URI, resourceURI);
    msg.put(SecurityContext.class, sc);

    PolicyDecisionPoint pdp = new DummyPDP();
    XACMLAuthorizingInterceptor authorizingInterceptor = new XACMLAuthorizingInterceptor(pdp);

    try {
        authorizingInterceptor.handleMessage(msg);
        fail("Failure expected on deny");
    } catch (Exception ex) {
        // Failure expected
    }
}
 
Example 2
Source File: XACMLAuthorizingInterceptorTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testPermit() throws Exception {
    // Mock up a Security Context
    SecurityContext sc = createSecurityContext("alice", "manager");

    String operation = "{http://www.example.org/contract/DoubleIt}DoubleIt";
    MessageImpl msg = new MessageImpl();
    msg.put(Message.WSDL_OPERATION, QName.valueOf(operation));
    String service = "{http://www.example.org/contract/DoubleIt}DoubleItService";
    msg.put(Message.WSDL_SERVICE, QName.valueOf(service));
    String resourceURI = "https://localhost:8080/doubleit";
    msg.put(Message.REQUEST_URI, resourceURI);
    msg.put(SecurityContext.class, sc);

    PolicyDecisionPoint pdp = new DummyPDP();
    XACMLAuthorizingInterceptor authorizingInterceptor = new XACMLAuthorizingInterceptor(pdp);
    authorizingInterceptor.handleMessage(msg);
}
 
Example 3
Source File: PersistenceUtils.java    From cxf with Apache License 2.0 6 votes vote down vote up
public static void encodeRMContent(RMMessage rmmsg, Message msg, InputStream msgContent)
    throws IOException {
    CachedOutputStream cos = new CachedOutputStream();
    if (msg.getAttachments() == null) {
        rmmsg.setContentType((String)msg.get(Message.CONTENT_TYPE));
        IOUtils.copyAndCloseInput(msgContent, cos);
        cos.flush();
        rmmsg.setContent(cos);
    } else {
        MessageImpl msgImpl1 = new MessageImpl();
        msgImpl1.setContent(OutputStream.class, cos);
        msgImpl1.setAttachments(msg.getAttachments());
        msgImpl1.put(Message.CONTENT_TYPE, msg.get(Message.CONTENT_TYPE));
        msgImpl1.setContent(InputStream.class, msgContent);
        AttachmentSerializer serializer = new AttachmentSerializer(msgImpl1);
        serializer.setXop(false);
        serializer.writeProlog();
        // write soap root message into cached output stream
        IOUtils.copyAndCloseInput(msgContent, cos);
        cos.flush();
        serializer.writeAttachments();
        rmmsg.setContentType((String) msgImpl1.get(Message.CONTENT_TYPE));
        rmmsg.setContent(cos);
    }
}
 
Example 4
Source File: XACMLRequestBuilderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testXACMLRequestBuilder() throws Exception {
    // Mock up a request
    Principal principal = new Principal() {
        public String getName() {
            return "alice";
        }
    };

    String operation = "{http://www.example.org/contract/DoubleIt}DoubleIt";
    MessageImpl msg = new MessageImpl();
    msg.put(Message.WSDL_OPERATION, QName.valueOf(operation));
    String service = "{http://www.example.org/contract/DoubleIt}DoubleItService";
    msg.put(Message.WSDL_SERVICE, QName.valueOf(service));
    String resourceURL = "https://localhost:8080/doubleit";
    msg.put(Message.REQUEST_URI, resourceURL);

    XACMLRequestBuilder builder = new DefaultXACMLRequestBuilder();
    RequestType request =
        builder.createRequest(principal, Collections.singletonList("manager"), msg);
    assertNotNull(request);
}
 
Example 5
Source File: LocalConduit.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void dispatchDirect(Message message) throws IOException {
    if (destination.getMessageObserver() == null) {
        throw new IllegalStateException("Local destination does not have a MessageObserver on address "
                                        + destination.getAddress().getAddress().getValue());
    }

    MessageImpl copy = new MessageImpl();
    copy.put(IN_CONDUIT, this);
    copy.setDestination(destination);

    transportFactory.copy(message, copy);
    MessageImpl.copyContent(message, copy);

    OutputStream out = message.getContent(OutputStream.class);
    out.flush();
    out.close();

    CachedOutputStream stream = message.get(CachedOutputStream.class);
    copy.setContent(InputStream.class, stream.getInputStream());
    copy.removeContent(CachedOutputStream.class);
    stream.releaseTempFileHold();

    // Create a new incoming exchange and store the original exchange for the response
    ExchangeImpl ex = new ExchangeImpl();
    ex.setInMessage(copy);
    ex.put(IN_EXCHANGE, message.getExchange());
    ex.put(LocalConduit.DIRECT_DISPATCH, true);
    ex.setDestination(destination);

    destination.getMessageObserver().onMessage(copy);
}
 
Example 6
Source File: UDPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void processStreamIo(IoSession session, InputStream in, OutputStream out) {
    final MessageImpl m = new MessageImpl();
    final Exchange exchange = new ExchangeImpl();
    exchange.setDestination(UDPDestination.this);
    m.setDestination(UDPDestination.this);
    exchange.setInMessage(m);
    m.setContent(InputStream.class, in);
    out = new UDPDestinationOutputStream(out);
    m.put(OutputStream.class, out);
    queue.execute(() -> getMessageObserver().onMessage(m));
}
 
Example 7
Source File: LocalTransportFactoryTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void testInvocation(boolean isDirectDispatch) throws Exception {
    // Need to create a DefaultBus
    Bus bus = BusFactory.getDefaultBus();
    LocalTransportFactory factory = new LocalTransportFactory();

    EndpointInfo ei = new EndpointInfo(null, "http://schemas.xmlsoap.org/soap/http");
    ei.setAddress("http://localhost/test");

    LocalDestination d = (LocalDestination) factory.getDestination(ei, bus);
    d.setMessageObserver(new EchoObserver());

    // Set up a listener for the response
    Conduit conduit = factory.getConduit(ei, bus);
    TestMessageObserver obs = new TestMessageObserver();
    conduit.setMessageObserver(obs);

    MessageImpl m = new MessageImpl();
    if (isDirectDispatch) {
        m.put(LocalConduit.DIRECT_DISPATCH, Boolean.TRUE);
    }
    m.setDestination(d);
    Exchange ex = new ExchangeImpl();
    ex.put(Bus.class, bus);
    m.setExchange(ex);
    conduit.prepare(m);

    OutputStream out = m.getContent(OutputStream.class);

    StringBuilder builder = new StringBuilder();
    for (int x = 0; x < 1000; x++) {
        builder.append("hello");
    }
    out.write(builder.toString().getBytes());
    out.close();
    conduit.close(m);

    assertEquals(builder.toString(), obs.getResponseStream().toString());
}
 
Example 8
Source File: UDPDestination.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void run() {
    while (true) {
        if (mcast == null) {
            return;
        }
        try {
            byte[] bytes = new byte[64 * 1024];
            final DatagramPacket p = new DatagramPacket(bytes, bytes.length);
            mcast.receive(p);

            LoadingByteArrayOutputStream out = new LoadingByteArrayOutputStream() {
                public void close() throws IOException {
                    super.close();
                    final DatagramPacket p2 = new DatagramPacket(getRawBytes(),
                                                                 0,
                                                                 this.size(),
                                                                 p.getSocketAddress());
                    mcast.send(p2);
                }
            };

            final MessageImpl m = new MessageImpl();
            final Exchange exchange = new ExchangeImpl();
            exchange.setDestination(UDPDestination.this);
            m.setDestination(UDPDestination.this);
            exchange.setInMessage(m);
            m.setContent(InputStream.class, new ByteArrayInputStream(bytes, 0, p.getLength()));
            m.put(OutputStream.class, out);
            queue.execute(() -> getMessageObserver().onMessage(m));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
 
Example 9
Source File: LocalDestinationTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Tests if the status code is available after closing the destination so that it can be logged.
 * Note that this test verifies the current approach of setting the status code if it is not set earlier.
 *
 * @throws Exception
 */
@Test
public void testStatusCodeSetAfterClose() throws Exception {
    Bus bus = BusFactory.getDefaultBus();
    LocalTransportFactory factory = new LocalTransportFactory();

    EndpointInfo ei = new EndpointInfo(null, "http://schemas.xmlsoap.org/soap/http");
    ei.setAddress("http://localhost/test");

    LocalDestination d = (LocalDestination) factory.getDestination(ei, bus);
    MessageImpl m = new MessageImpl();

    Conduit conduit = factory.getConduit(ei, bus);
    m.put(LocalConduit.IN_CONDUIT, conduit);
    Exchange ex = new ExchangeImpl();
    ex.put(Bus.class, bus);
    m.setExchange(ex);

    Integer code = (Integer)m.get(Message.RESPONSE_CODE);
    assertNull(code);

    Conduit backChannel = d.getBackChannel(m);

    backChannel.close(m);

    code = (Integer)m.get(Message.RESPONSE_CODE);
    assertNotNull(code);
    assertEquals(200, code.intValue());
}
 
Example 10
Source File: XACMLRequestBuilderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testAction() throws Exception {
    // Mock up a request
    Principal principal = new Principal() {
        public String getName() {
            return "alice";
        }
    };

    String operation = "{http://www.example.org/contract/DoubleIt}DoubleIt";
    MessageImpl msg = new MessageImpl();
    msg.put(Message.WSDL_OPERATION, QName.valueOf(operation));
    String service = "{http://www.example.org/contract/DoubleIt}DoubleItService";
    msg.put(Message.WSDL_SERVICE, QName.valueOf(service));
    String resourceURL = "https://localhost:8080/doubleit";
    msg.put(Message.REQUEST_URI, resourceURL);

    DefaultXACMLRequestBuilder builder = new DefaultXACMLRequestBuilder();
    RequestType request =
        builder.createRequest(principal, Collections.singletonList("manager"), msg);
    assertNotNull(request);

    String action =
        request.getAction().getAttributes().get(0).getAttributeValues().get(0).getValue();
    assertEquals("execute", action);

    builder.setAction("write");
    request = builder.createRequest(principal, Collections.singletonList("manager"), msg);
    assertNotNull(request);

    action =
        request.getAction().getAttributes().get(0).getAttributeValues().get(0).getValue();
    assertEquals("write", action);
}
 
Example 11
Source File: AttachmentDeserializerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testCXF2542() throws Exception {
    StringBuilder buf = new StringBuilder(512);
    buf.append("------=_Part_0_2180223.1203118300920\n");
    buf.append("Content-Type: application/xop+xml; charset=UTF-8; type=\"text/xml\"\n");
    buf.append("Content-Transfer-Encoding: 8bit\n");
    buf.append("Content-ID: <[email protected]>\n");
    buf.append('\n');
    buf.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" "
               + "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" "
               + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">"
               + "<soap:Body><getNextMessage xmlns=\"http://foo.bar\" /></soap:Body>"
               + "</soap:Envelope>\n");
    buf.append("------=_Part_0_2180223.1203118300920--\n");

    InputStream rawInputStream = new ByteArrayInputStream(buf.toString().getBytes());
    MessageImpl message = new MessageImpl();
    message.setContent(InputStream.class, rawInputStream);
    message.put(Message.CONTENT_TYPE,
                "multipart/related; type=\"application/xop+xml\"; "
                + "start=\"<[email protected]>\"; "
                + "start-info=\"text/xml\"; boundary=\"----=_Part_0_2180223.1203118300920\"");
    new AttachmentDeserializer(message).initializeAttachments();
    InputStream inputStreamWithoutAttachments = message.getContent(InputStream.class);
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(inputStreamWithoutAttachments, new DefaultHandler());

    inputStreamWithoutAttachments.close();
    rawInputStream.close();
}
 
Example 12
Source File: RequestImplTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    m = new MessageImpl();
    metadata = new MetadataMap<>();
    m.put(Message.PROTOCOL_HEADERS, metadata);
    m.put(Message.HTTP_REQUEST_METHOD, "GET");
}
 
Example 13
Source File: AttachmentDeserializerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoBoundaryInCT() throws Exception {
    //CXF-2623
    String message = "SomeHeader: foo\n"
        + "------=_Part_34950_1098328613.1263781527359\n"
        + "Content-Type: text/xml; charset=UTF-8\n"
        + "Content-Transfer-Encoding: binary\n"
        + "Content-Id: <318731183421.1263781527359.IBM.WEBSERVICES@auhpap02>\n"
        + "\n"
        + "<envelope/>\n"
        + "------=_Part_34950_1098328613.1263781527359\n"
        + "Content-Type: text/xml\n"
        + "Content-Transfer-Encoding: binary\n"
        + "Content-Id: <b86a5f2d-e7af-4e5e-b71a-9f6f2307cab0>\n"
        + "\n"
        + "<message>\n"
        + "------=_Part_34950_1098328613.1263781527359--";

    Matcher m = Pattern.compile("^--(\\S*)$").matcher(message);
    assertFalse(m.find());
    m = Pattern.compile("^--(\\S*)$", Pattern.MULTILINE).matcher(message);
    assertTrue(m.find());

    msg = new MessageImpl();
    msg.setContent(InputStream.class, new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)));
    msg.put(Message.CONTENT_TYPE, "multipart/related");
    AttachmentDeserializer ad = new AttachmentDeserializer(msg);
    ad.initializeAttachments();
    assertEquals(1, msg.getAttachments().size());
}
 
Example 14
Source File: AttachmentDeserializerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testManyAttachments() throws Exception {
    StringBuilder sb = new StringBuilder(1000);
    sb.append("SomeHeader: foo\n")
        .append("------=_Part_34950_1098328613.1263781527359\n")
        .append("Content-Type: text/xml; charset=UTF-8\n")
        .append("Content-Transfer-Encoding: binary\n")
        .append("Content-Id: <318731183421.1263781527359.IBM.WEBSERVICES@auhpap02>\n")
        .append('\n')
        .append("<envelope/>\n");

    // Add many attachments
    IntStream.range(0, 100000).forEach(i -> {
        sb.append("------=_Part_34950_1098328613.1263781527359\n")
            .append("Content-Type: text/xml\n")
            .append("Content-Transfer-Encoding: binary\n")
            .append("Content-Id: <b86a5f2d-e7af-4e5e-b71a-9f6f2307cab0>\n")
            .append('\n')
            .append("<message>\n")
            .append("------=_Part_34950_1098328613.1263781527359--\n");
    });

    msg = new MessageImpl();
    msg.setContent(InputStream.class, new ByteArrayInputStream(sb.toString().getBytes(StandardCharsets.UTF_8)));
    msg.put(Message.CONTENT_TYPE, "multipart/related");
    AttachmentDeserializer ad = new AttachmentDeserializer(msg);
    ad.initializeAttachments();

    // Force it to load the attachments
    try {
        msg.getAttachments().size();
        fail("Failure expected on too many attachments");
    } catch (RuntimeException ex) {
        // expected
    }
}
 
Example 15
Source File: AttachmentSerializerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageMTOM() throws Exception {
    MessageImpl msg = new MessageImpl();

    Collection<Attachment> atts = new ArrayList<>();
    AttachmentImpl a = new AttachmentImpl("test.xml");

    InputStream is = getClass().getResourceAsStream("my.wav");
    ByteArrayDataSource ds = new ByteArrayDataSource(is, "application/octet-stream");
    a.setDataHandler(new DataHandler(ds));

    atts.add(a);

    msg.setAttachments(atts);

    // Set the SOAP content type
    msg.put(Message.CONTENT_TYPE, "application/soap+xml");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    msg.setContent(OutputStream.class, out);

    AttachmentSerializer serializer = new AttachmentSerializer(msg);

    serializer.writeProlog();

    String ct = (String) msg.get(Message.CONTENT_TYPE);
    assertTrue(ct.indexOf("multipart/related;") == 0);
    assertTrue(ct.indexOf("start=\"<[email protected]>\"") > -1);
    assertTrue(ct.indexOf("start-info=\"application/soap+xml\"") > -1);

    out.write("<soap:Body/>".getBytes());

    serializer.writeAttachments();

    out.flush();
    DataSource source = new ByteArrayDataSource(new ByteArrayInputStream(out.toByteArray()), ct);
    MimeMultipart mpart = new MimeMultipart(source);
    Session session = Session.getDefaultInstance(new Properties());
    MimeMessage inMsg = new MimeMessage(session);
    inMsg.setContent(mpart);

    inMsg.addHeaderLine("Content-Type: " + ct);

    MimeMultipart multipart = (MimeMultipart) inMsg.getContent();

    MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(0);
    assertEquals("application/xop+xml; charset=UTF-8; type=\"application/soap+xml\"",
                 part.getHeader("Content-Type")[0]);
    assertEquals("binary", part.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<[email protected]>", part.getHeader("Content-ID")[0]);

    InputStream in = part.getDataHandler().getInputStream();
    ByteArrayOutputStream bodyOut = new ByteArrayOutputStream();
    IOUtils.copy(in, bodyOut);
    out.close();
    in.close();

    assertEquals("<soap:Body/>", bodyOut.toString());

    MimeBodyPart part2 = (MimeBodyPart) multipart.getBodyPart(1);
    assertEquals("application/octet-stream", part2.getHeader("Content-Type")[0]);
    assertEquals("binary", part2.getHeader("Content-Transfer-Encoding")[0]);
    assertEquals("<test.xml>", part2.getHeader("Content-ID")[0]);

}
 
Example 16
Source File: XACMLRequestBuilderTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSOAPResourceDifferentNamespace() throws Exception {
    // Mock up a request
    Principal principal = new Principal() {
        public String getName() {
            return "alice";
        }
    };

    String operation = "{http://www.example.org/contract/DoubleIt}DoubleIt";
    MessageImpl msg = new MessageImpl();
    msg.put(Message.WSDL_OPERATION, QName.valueOf(operation));
    String service = "{http://www.example.org/contract/DoubleItService}DoubleItService";
    msg.put(Message.WSDL_SERVICE, QName.valueOf(service));
    String resourceURL = "https://localhost:8080/doubleit";
    msg.put(Message.REQUEST_URL, resourceURL);

    XACMLRequestBuilder builder = new DefaultXACMLRequestBuilder();
    RequestType request =
        builder.createRequest(principal, Collections.singletonList("manager"), msg);
    assertNotNull(request);

    List<ResourceType> resources = request.getResources();
    assertNotNull(resources);
    assertEquals(1, resources.size());

    ResourceType resource = resources.get(0);
    assertEquals(4, resource.getAttributes().size());

    boolean resourceIdSatisfied = false;
    boolean soapServiceSatisfied = false;
    boolean soapOperationSatisfied = false;
    boolean resourceURISatisfied = false;
    String expectedResourceId =
        service + "#" + operation;
    for (AttributeType attribute : resource.getAttributes()) {
        String attributeValue = attribute.getAttributeValues().get(0).getValue();
        if (XACMLConstants.RESOURCE_ID.equals(attribute.getAttributeId())
            && expectedResourceId.equals(attributeValue)) {
            resourceIdSatisfied = true;
        } else if (XACMLConstants.RESOURCE_WSDL_SERVICE_ID.equals(attribute.getAttributeId())
            && service.equals(attributeValue)) {
            soapServiceSatisfied = true;
        } else if (XACMLConstants.RESOURCE_WSDL_OPERATION_ID.equals(attribute.getAttributeId())
            && operation.equals(attributeValue)) {
            soapOperationSatisfied = true;
        } else if (XACMLConstants.RESOURCE_WSDL_ENDPOINT.equals(attribute.getAttributeId())
            && resourceURL.equals(attributeValue)) {
            resourceURISatisfied = true;
        }
    }

    assertTrue(resourceIdSatisfied && soapServiceSatisfied && soapOperationSatisfied
               && resourceURISatisfied);
}
 
Example 17
Source File: MtomPolicyTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void sendMtomMessage(String a) throws Exception {
    EndpointInfo ei = new EndpointInfo(null, "http://schemas.xmlsoap.org/wsdl/http");
    ei.setAddress(a);

    ConduitInitiatorManager conduitMgr = getStaticBus().getExtension(ConduitInitiatorManager.class);
    ConduitInitiator conduitInit = conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
    Conduit conduit = conduitInit.getConduit(ei, getStaticBus());

    TestUtilities.TestMessageObserver obs = new TestUtilities.TestMessageObserver();
    conduit.setMessageObserver(obs);

    Message m = new MessageImpl();
    String ct = "multipart/related; type=\"application/xop+xml\"; "
                + "start=\"<[email protected]>\"; "
                + "start-info=\"text/xml; charset=utf-8\"; "
                + "boundary=\"----=_Part_4_701508.1145579811786\"";

    m.put(Message.CONTENT_TYPE, ct);
    conduit.prepare(m);

    OutputStream os = m.getContent(OutputStream.class);
    InputStream is = testUtilities.getResourceAsStream("request");
    if (is == null) {
        throw new RuntimeException("Could not find resource " + "request");
    }

    IOUtils.copy(is, os);

    os.flush();
    is.close();
    os.close();

    byte[] res = obs.getResponseStream().toByteArray();
    MessageImpl resMsg = new MessageImpl();
    resMsg.setContent(InputStream.class, new ByteArrayInputStream(res));
    resMsg.put(Message.CONTENT_TYPE, obs.getResponseContentType());
    resMsg.setExchange(new ExchangeImpl());
    AttachmentDeserializer deserializer = new AttachmentDeserializer(resMsg);
    deserializer.initializeAttachments();

    Collection<Attachment> attachments = resMsg.getAttachments();
    assertNotNull(attachments);
    assertEquals(1, attachments.size());

    Attachment inAtt = attachments.iterator().next();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        IOUtils.copy(inAtt.getDataHandler().getInputStream(), out);
        assertEquals(27364, out.size());
    }
}
 
Example 18
Source File: MtomServerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testURLBasedAttachment() throws Exception {
    JaxWsServerFactoryBean sf = new JaxWsServerFactoryBean();
    sf.setServiceBean(new EchoService());
    sf.setBus(getStaticBus());
    String address = "http://localhost:" + PORT2 + "/EchoService";
    sf.setAddress(address);
    Map<String, Object> props = new HashMap<>();
    props.put(Message.MTOM_ENABLED, "true");
    sf.setProperties(props);
    Server server = sf.create();
    server.getEndpoint().getService().getDataBinding().setMtomThreshold(0);

    servStatic(getClass().getResource("mtom-policy.xml"),
               "http://localhost:" + PORT2 + "/policy.xsd");

    EndpointInfo ei = new EndpointInfo(null, HTTP_ID);
    ei.setAddress(address);

    ConduitInitiatorManager conduitMgr = getStaticBus().getExtension(ConduitInitiatorManager.class);
    ConduitInitiator conduitInit = conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
    Conduit conduit = conduitInit.getConduit(ei, getStaticBus());

    TestUtilities.TestMessageObserver obs = new TestUtilities.TestMessageObserver();
    conduit.setMessageObserver(obs);

    Message m = new MessageImpl();
    String ct = "multipart/related; type=\"application/xop+xml\"; "
                + "start=\"<[email protected]>\"; "
                + "start-info=\"text/xml; charset=utf-8\"; "
                + "boundary=\"----=_Part_4_701508.1145579811786\"";

    m.put(Message.CONTENT_TYPE, ct);
    conduit.prepare(m);

    OutputStream os = m.getContent(OutputStream.class);
    InputStream is = testUtilities.getResourceAsStream("request-url-attachment");
    if (is == null) {
        throw new RuntimeException("Could not find resource " + "request");
    }
    try (ByteArrayOutputStream bout = new ByteArrayOutputStream()) {
        IOUtils.copy(is, bout);
        String s = bout.toString(StandardCharsets.UTF_8.name());
        s = s.replaceAll(":9036/", ":" + PORT2 + "/");

        os.write(s.getBytes(StandardCharsets.UTF_8));
    }
    os.flush();
    is.close();
    os.close();

    byte[] res = obs.getResponseStream().toByteArray();
    MessageImpl resMsg = new MessageImpl();
    resMsg.setContent(InputStream.class, new ByteArrayInputStream(res));
    resMsg.put(Message.CONTENT_TYPE, obs.getResponseContentType());
    resMsg.setExchange(new ExchangeImpl());
    AttachmentDeserializer deserializer = new AttachmentDeserializer(resMsg);
    deserializer.initializeAttachments();

    Collection<Attachment> attachments = resMsg.getAttachments();
    assertNotNull(attachments);
    assertEquals(1, attachments.size());

    Attachment inAtt = attachments.iterator().next();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        IOUtils.copy(inAtt.getDataHandler().getInputStream(), out);
        assertTrue("Wrong size: " + out.size()
                + "\n" + out.toString(),
                out.size() > 970 && out.size() < 1020);
    }
    unregisterServStatic("http://localhost:" + PORT2 + "/policy.xsd");

}
 
Example 19
Source File: MtomServerTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@Test
public void testMtomRequest() throws Exception {
    JaxWsServerFactoryBean sf = new JaxWsServerFactoryBean();
    sf.setServiceBean(new EchoService());
    sf.setBus(getStaticBus());
    String address = "http://localhost:" + PORT1 + "/EchoService";
    sf.setAddress(address);
    Map<String, Object> props = new HashMap<>();
    props.put(Message.MTOM_ENABLED, "true");
    sf.setProperties(props);
    sf.create();

    EndpointInfo ei = new EndpointInfo(null, HTTP_ID);
    ei.setAddress(address);

    ConduitInitiatorManager conduitMgr = getStaticBus().getExtension(ConduitInitiatorManager.class);
    ConduitInitiator conduitInit = conduitMgr.getConduitInitiator("http://schemas.xmlsoap.org/soap/http");
    Conduit conduit = conduitInit.getConduit(ei, getStaticBus());

    TestUtilities.TestMessageObserver obs = new TestUtilities.TestMessageObserver();
    conduit.setMessageObserver(obs);

    Message m = new MessageImpl();
    String ct = "multipart/related; type=\"application/xop+xml\"; "
                + "start=\"<[email protected]>\"; "
                + "start-info=\"text/xml\"; "
                + "boundary=\"----=_Part_4_701508.1145579811786\"";

    m.put(Message.CONTENT_TYPE, ct);
    conduit.prepare(m);

    OutputStream os = m.getContent(OutputStream.class);
    InputStream is = testUtilities.getResourceAsStream("request");
    if (is == null) {
        throw new RuntimeException("Could not find resource " + "request");
    }

    IOUtils.copy(is, os);

    os.flush();
    is.close();
    os.close();

    byte[] res = obs.getResponseStream().toByteArray();
    MessageImpl resMsg = new MessageImpl();
    resMsg.setContent(InputStream.class, new ByteArrayInputStream(res));
    resMsg.put(Message.CONTENT_TYPE, obs.getResponseContentType());
    resMsg.setExchange(new ExchangeImpl());
    AttachmentDeserializer deserializer = new AttachmentDeserializer(resMsg);
    deserializer.initializeAttachments();

    Collection<Attachment> attachments = resMsg.getAttachments();
    assertNotNull(attachments);
    assertEquals(1, attachments.size());

    Attachment inAtt = attachments.iterator().next();
    try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
        IOUtils.copy(inAtt.getDataHandler().getInputStream(), out);
        assertEquals(27364, out.size());
    }
}
 
Example 20
Source File: WebServiceContextBean.java    From kumuluzee with MIT License 4 votes vote down vote up
public WebServiceContextBean(String id) {
    MessageImpl message = new MessageImpl();
    message.put("id", id);
    messageContext = new LogicalMessageContextImpl(message);
}