org.apache.cxf.helpers.IOUtils Java Examples

The following examples show how to use org.apache.cxf.helpers.IOUtils. 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: 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 #2
Source File: HTTPConnector.java    From cloud-sfsf-benefits-ext with Apache License 2.0 6 votes vote down vote up
private SimpleHttpResponse executePOST(HttpURLConnection connection, String data, String contentType) throws IOException, InvalidResponseException {        
    connection.setRequestMethod(POST_METHOD);
    
    if (!StringUtils.isEmpty(contentType)) {
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty( "charset", StandardCharsets.UTF_8.toString());
        byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8.toString());
        connection.setRequestProperty("Content-Length", dataBytes.toString());
        OutputStream output = connection.getOutputStream();
        output.write(dataBytes);
        output.close();
    }
    int responseCode = connection.getResponseCode();
    SimpleHttpResponse httpResponse = new SimpleHttpResponse(connection.getURL().toString(), responseCode, connection.getResponseMessage());
    httpResponse.setContentType(connection.getContentType());
    httpResponse.setContent(IOUtils.toString(connection.getInputStream()));
    logResponse(httpResponse);
    validateResponse(httpResponse);
    return httpResponse;
}
 
Example #3
Source File: PlugInClassLoaderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadSlashResourceWithPluginClassLoader()
    throws Exception {
    Class<?> resultClass = plugInClassLoader.loadClass(
            "org.apache.cxf.jca.dummy.Dummy");
    URL url = resultClass.getResource("/META-INF/MANIFEST.MF");
    LOG.info("URL: " + url);
    assertTrue("bad url: " + url, url.toString().startsWith("classloader:"));

    InputStream configStream = url.openStream();
    assertNotNull("stream must not be null. ", configStream);
    assertTrue("unexpected stream class: " + configStream.getClass(),
        configStream instanceof java.io.ByteArrayInputStream);

    byte[] bytes = new byte[21];
    configStream.read(bytes, 0, bytes.length);

    String result = IOUtils.newStringFromBytes(bytes);
    LOG.fine("dummy.txt contents: " + result);
    assertTrue("unexpected dummy.txt contents:"  + result, result.indexOf("Manifest-Version: 1.0") != -1);
}
 
Example #4
Source File: PlugInClassLoaderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadResourceWithPluginClassLoader()
    throws Exception {
    Class<?> resultClass = plugInClassLoader.loadClass(
            "org.apache.cxf.jca.dummy.Dummy");
    URL url = resultClass.getResource("dummy.txt");
    LOG.info("URL: " + url);
    assertTrue("bad url: " + url, url.toString().startsWith("classloader:"));


    InputStream configStream = url.openStream();
    assertNotNull("stream must not be null. ", configStream);
    assertTrue("unexpected stream class: " + configStream.getClass(),
        configStream instanceof java.io.ByteArrayInputStream);

    byte[] bytes = new byte[10];
    configStream.read(bytes, 0, bytes.length);

    String result = IOUtils.newStringFromBytes(bytes);
    LOG.fine("dummy.txt contents: " + result);
    assertEquals("unexpected dummy.txt contents.", "blah,blah.", result);
}
 
Example #5
Source File: RMTxStoreTestBase.java    From cxf with Apache License 2.0 6 votes vote down vote up
private RMMessage createRMMessage(Long mn, String to) throws IOException {
    RMMessage msg = control.createMock(RMMessage.class);
    EasyMock.expect(msg.getMessageNumber()).andReturn(mn).anyTimes();
    EasyMock.expect(msg.getTo()).andReturn(to).anyTimes();

    EasyMock.expect(msg.getContentType()).andReturn("text/xml").anyTimes();
    EasyMock.expect(msg.getCreatedTime()).andReturn(TIME);
    byte[] value = ("Message " + mn.longValue()).getBytes();
    ByteArrayInputStream bais = new ByteArrayInputStream(value);
    CachedOutputStream cos = new CachedOutputStream();
    IOUtils.copy(bais, cos);
    cos.flush();
    bais.close();
    EasyMock.expect(msg.getContent()).andReturn(cos).anyTimes();
    return msg;
}
 
Example #6
Source File: SwAServiceImpl.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void echoDataWithHeader(Holder<String> text,
                               Holder<DataHandler> data,
                               Holder<String> headerText) {
    try {
        InputStream bis = null;
        bis = data.value.getDataSource().getInputStream();
        byte[] b = new byte[6];
        bis.read(b, 0, 6);
        String string = IOUtils.newStringFromBytes(b);

        ByteArrayDataSource source =
            new ByteArrayDataSource(("test" + string).getBytes(), "application/octet-stream");
        data.value = new DataHandler(source);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #7
Source File: PersistenceUtilsTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testDecodeRMContentWithAttachment() throws Exception {
    InputStream is = getClass().getResourceAsStream("SerializedRMMessage.txt");
    CachedOutputStream cos = new CachedOutputStream();
    IOUtils.copyAndCloseInput(is, cos);
    cos.flush();
    RMMessage msg = new RMMessage();
    msg.setContent(cos);
    msg.setContentType(MULTIPART_TYPE);
    Message messageImpl = new MessageImpl();
    PersistenceUtils.decodeRMContent(msg, messageImpl);

    assertEquals(1, messageImpl.getAttachments().size());
    CachedOutputStream cos1 = (CachedOutputStream)messageImpl
        .get(RMMessageConstants.SAVED_CONTENT);
    assertStartsWith(cos1.getInputStream(), "<soap:Envelope");
}
 
Example #8
Source File: CrossOriginSimpleTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void assertAllOrigin(boolean allOrigins, String[] originList, String[] requestOrigins,
                             boolean permitted) throws ClientProtocolException, IOException {
    configureAllowOrigins(allOrigins, originList);

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet httpget = new HttpGet("http://localhost:" + PORT + "/untest/simpleGet/HelloThere");
    if (requestOrigins != null) {
        StringBuilder ob = new StringBuilder();
        for (String requestOrigin : requestOrigins) {
            ob.append(requestOrigin);
            ob.append(' '); // extra trailing space won't hurt.
        }
        httpget.addHeader("Origin", ob.toString());
    }
    HttpResponse response = httpclient.execute(httpget);
    assertEquals(200, response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    String e = IOUtils.toString(entity.getContent());

    assertEquals("HelloThere", e); // ensure that we didn't bust the operation itself.
    assertOriginResponse(allOrigins, requestOrigins, permitted, response);
    if (httpclient instanceof Closeable) {
        ((Closeable)httpclient).close();
    }

}
 
Example #9
Source File: JweClientResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
    if (isMethodWithNoContent(req.getMethod())
            || isStatusCodeWithNoContent(res.getStatus())
            || isCheckEmptyStream() && !res.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(res.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    JweDecryptionOutput out = decrypt(encryptedContent);
    byte[] bytes = out.getContent();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(res.getHeaders(), out.getHeaders());
    }
}
 
Example #10
Source File: InterpretNullAsOnewayProviderTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static HttpURLConnection postRequest(String address) throws Exception {
    URL url = new URL(address);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    InputStream in = InterpretNullAsOnewayProviderTest.class.
        getResourceAsStream("resources/sayHiDocLiteralReq.xml");
    assertNotNull("could not load test data", in);

    conn.setRequestMethod("POST");
    conn.addRequestProperty("Content-Type", "text/xml");
    OutputStream out = conn.getOutputStream();
    IOUtils.copy(in, out);
    out.close();

    return conn;
}
 
Example #11
Source File: MtomTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testAcceptDataHandlerNoMTOM() throws Exception {
    setupForTest(false);
    DataHandlerBean dhBean = new DataHandlerBean();
    dhBean.setName("some name");
    // some day, we might need this to be longer than some threshold.
    String someData = "This is the cereal shot from guns.";
    DataHandler dataHandler = new DataHandler(someData, "text/plain;charset=utf-8");
    dhBean.setDataHandler(dataHandler);
    client.acceptDataHandler(dhBean);
    DataHandlerBean accepted = impl.getLastDhBean();
    Assert.assertNotNull(accepted);
    InputStream data = accepted.getDataHandler().getInputStream();
    Assert.assertNotNull(data);
    String dataString = IOUtils.toString(data);
    Assert.assertEquals("This is the cereal shot from guns.", dataString);
}
 
Example #12
Source File: GenericWebServiceServlet.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
protected void serveStaticContent(HttpServletRequest request, HttpServletResponse response, String pathInfo) throws ServletException {
	InputStream is = super.getServletContext().getResourceAsStream(pathInfo);
	if (is == null) {
		throw new ServletException("Static resource " + pathInfo + " is not available");
	}
	try {
		int ind = pathInfo.lastIndexOf(".");
		if (ind != -1 && ind < pathInfo.length()) {
			String type = STATIC_CONTENT_TYPES.get(pathInfo.substring(ind + 1));
			if (type != null) {
				response.setContentType(type);
			}
		}

		ServletOutputStream os = response.getOutputStream();
		IOUtils.copy(is, os);
		os.flush();
	} catch (IOException ex) {
		throw new ServletException("Static resource " + pathInfo + " can not be written to the output stream");
	}
}
 
Example #13
Source File: LoggingInInterceptor.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void logReader(Message message, Reader reader, LoggingMessage buffer) {
    try {
        CachedWriter writer = new CachedWriter();
        IOUtils.copyAndCloseInput(reader, writer);
        message.setContent(Reader.class, writer.getReader());

        if (writer.getTempFile() != null) {
            //large thing on disk...
            buffer.getMessage().append("\nMessage (saved to tmp file):\n");
            buffer.getMessage().append("Filename: " + writer.getTempFile().getAbsolutePath() + "\n");
        }
        if (writer.size() > limit && limit != -1) {
            buffer.getMessage().append("(message truncated to " + limit + " bytes)\n");
        }
        writer.writeCacheTo(buffer.getPayload(), limit);
        writer.close();
    } catch (Exception e) {
        throw new Fault(e);
    }
}
 
Example #14
Source File: JweJsonClientResponseFilter.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ClientRequestContext req, ClientResponseContext res) throws IOException {
    if (isMethodWithNoContent(req.getMethod())
        || isStatusCodeWithNoContent(res.getStatus())
        || isCheckEmptyStream() && !res.hasEntity()) {
        return;
    }
    final byte[] encryptedContent = IOUtils.readBytesFromStream(res.getEntityStream());
    if (encryptedContent.length == 0) {
        return;
    }
    JweDecryptionOutput out = decrypt(encryptedContent);
    byte[] bytes = out.getContent();
    res.setEntityStream(new ByteArrayInputStream(bytes));
    res.getHeaders().putSingle("Content-Length", Integer.toString(bytes.length));
    String ct = JoseUtils.checkContentType(out.getHeaders().getContentType(), getDefaultMediaType());
    if (ct != null) {
        res.getHeaders().putSingle("Content-Type", ct);
    }
    if (super.isValidateHttpHeaders()) {
        super.validateHttpHeadersIfNeeded(res.getHeaders(), out.getHeaders());
    }
}
 
Example #15
Source File: ClientCacheTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTimeStringAsInputStream() throws Exception {
    CacheControlFeature feature = new CacheControlFeature();
    try {
        final WebTarget base = ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
        final Invocation.Builder cached = base.request("text/plain").header(HttpHeaders.CACHE_CONTROL, "public");
        final Response r = cached.get();
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        InputStream is = r.readEntity(InputStream.class);
        final String r1 = IOUtils.readStringFromStream(is);
        waitABit();
        is = cached.get().readEntity(InputStream.class);
        final String r2 = IOUtils.readStringFromStream(is);
        assertEquals(r1, r2);
    } finally {
        feature.close();
    }
}
 
Example #16
Source File: ClientCacheTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetTimeStringAsInputStreamAndString() throws Exception {
    CacheControlFeature feature = new CacheControlFeature();
    try {
        feature.setCacheResponseInputStream(true);
        final WebTarget base = ClientBuilder.newBuilder().register(feature).build().target(ADDRESS);
        final Invocation.Builder cached = base.request("text/plain").header(HttpHeaders.CACHE_CONTROL, "public");
        final Response r = cached.get();
        assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
        InputStream is = r.readEntity(InputStream.class);
        final String r1 = IOUtils.readStringFromStream(is);
        waitABit();
        // CassCastException would occur without a cached stream support
        final String r2 = cached.get().readEntity(String.class);
        assertEquals(r1, r2);
    } finally {
        feature.close();
    }
}
 
Example #17
Source File: EngineLifecycleTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
private static void verifyStaticHtml() throws Exception {
    String response = null;
    for (int i = 0; i < 50 && null == response; i++) {
        try (InputStream in = new URL("http://localhost:" + PORT2 + "/test.html").openConnection()
                .getInputStream()) {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            IOUtils.copy(in, os);
            response = new String(os.toByteArray());
        } catch (Exception ex) {
            Thread.sleep(100L);
        }
    }
    assertNotNull("Test doc can not be read", response);

    String html;
    try (InputStream htmlFile = EngineLifecycleTest.class.getResourceAsStream("test.html")) {
        byte[] buf = new byte[htmlFile.available()];
        htmlFile.read(buf);
        html = new String(buf);
    }
    assertEquals("Can't get the right test html", html, response);
}
 
Example #18
Source File: PolicyTestHelper.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void updatePolicyRef(String file, String oldData,
                                   String newData) throws IOException {
    File f = FileUtils.getDefaultTempDir();
    InputStream in = PolicyTestHelper.class.getResourceAsStream(file);
    String s = IOUtils.readStringFromStream(in);
    s = s.replaceAll(oldData, newData);
    File newFile = new File(f, file);
    FileWriter fw = new FileWriter(newFile);
    fw.write(s);
    fw.close();
}
 
Example #19
Source File: JAXWSServicesListingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceListingUnformatted() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/service_listing/services?formatted=false";
    String expectedResult =
        "http://localhost:" + PORT + "/service_listing/services/SoapContext/GreeterPort";

    URL url = new URL(endpointAddress);
    try (InputStream input = url.openStream()) {
        String result = IOUtils.readStringFromStream(input);
        assertTrue(result.contains(expectedResult));
    }
}
 
Example #20
Source File: JAXWSServicesListingTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testServiceListing() throws Exception {

    String endpointAddress =
        "http://localhost:" + PORT + "/service_listing/services";
    String expectedResult =
        "http://localhost:" + PORT + "/service_listing/services/SoapContext/GreeterPort";

    URL url = new URL(endpointAddress);
    try (InputStream input = url.openStream()) {
        String result = IOUtils.readStringFromStream(input);
        assertTrue(result.contains(expectedResult));
    }
}
 
Example #21
Source File: Base64UtilityTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testEncodeDecodeStreams() throws Exception {
    byte[] bytes = new byte[100];
    for (int x = 0; x < bytes.length; x++) {
        bytes[x] = (byte)x;
    }
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ByteArrayOutputStream bout2 = new ByteArrayOutputStream();
    Base64Utility.encodeChunk(bytes, 0, bytes.length, bout);
    String encodedString = IOUtils.newStringFromBytes(bout.toByteArray());
    Base64Utility.decode(encodedString.toCharArray(),
                         0,
                         encodedString.length(),
                         bout2);
    assertArrayEquals(bytes, bout2.toByteArray());


    String in = "QWxhZGRpbjpvcGVuIHNlc2FtZQ==";
    bout.reset();
    bout2.reset();
    Base64Utility.decode(in, bout);
    bytes = bout.toByteArray();
    assertEquals("Aladdin:open sesame", IOUtils.newStringFromBytes(bytes));
    StringWriter writer = new StringWriter();
    Base64Utility.encode(bytes, 0, bytes.length, writer);
    assertEquals(in, writer.toString());

}
 
Example #22
Source File: CachedOutputStream.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
 * Replace the original stream with the new one, optionally copying the content of the old one
 * into the new one.
 * When with Attachment, needs to replace the xml writer stream with the stream used by
 * AttachmentSerializer or copy the cached output stream to the "real"
 * output stream, i.e. onto the wire.
 *
 * @param out the new output stream
 * @param copyOldContent flag indicating if the old content should be copied
 * @throws IOException
 */
public void resetOut(OutputStream out, boolean copyOldContent) throws IOException {
    if (out == null) {
        out = new LoadingByteArrayOutputStream();
    }

    if (currentStream instanceof CachedOutputStream) {
        CachedOutputStream ac = (CachedOutputStream) currentStream;
        InputStream in = ac.getInputStream();
        IOUtils.copyAndCloseInput(in, out);
    } else {
        if (inmem) {
            if (currentStream instanceof ByteArrayOutputStream) {
                ByteArrayOutputStream byteOut = (ByteArrayOutputStream) currentStream;
                if (copyOldContent && byteOut.size() > 0) {
                    byteOut.writeTo(out);
                }
            } else {
                throw new IOException("Unknown format of currentStream");
            }
        } else {
            // read the file
            try {
                currentStream.close();
                if (copyOldContent) {
                    InputStream fin = createInputStream(tempFile);
                    IOUtils.copyAndCloseInput(fin, out);
                }
            } finally {
                streamList.remove(currentStream);
                deleteTempFile();
                inmem = true;
            }
        }
    }
    currentStream = out;
    outputLocked = false;
}
 
Example #23
Source File: JavascriptGetInterceptor.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void writeUtilsToResponseStream(Class<?> referenceClass, OutputStream outputStream) {
    InputStream utils = referenceClass.getResourceAsStream(JS_UTILS_PATH);
    if (utils == null) {
        throw new RuntimeException("Unable to get stream for " + JS_UTILS_PATH);
    }
    try {
        IOUtils.copyAndCloseInput(utils, outputStream);
        outputStream.flush();
    } catch (IOException e) {
        throw new RuntimeException("Failed to write javascript utils to HTTP response.", e);
    }
}
 
Example #24
Source File: ClientServerSwaTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testSwaNoMimeCodeGen() throws Exception {
    org.apache.cxf.swa_nomime.SwAService service = new org.apache.cxf.swa_nomime.SwAService();

    org.apache.cxf.swa_nomime.SwAServiceInterface port = service.getSwAServiceHttpPort();
    setAddress(port, "http://localhost:" + serverPort + "/swa-nomime");

    Holder<String> textHolder = new Holder<>("Hi");
    Holder<byte[]> data = new Holder<>("foobar".getBytes());

    port.echoData(textHolder, data);
    String string = IOUtils.newStringFromBytes(data.value);
    assertEquals("testfoobar", string);
    assertEquals("Hi", textHolder.value);

    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");

    Holder<String> attach1 = new Holder<>(IOUtils.toString(url1.openStream()));
    Holder<String> attach2 = new Holder<>(IOUtils.toString(url2.openStream()));
    Holder<String> attach3 = new Holder<>(IOUtils.toString(url3.openStream()));
    Holder<byte[]> attach4 = new Holder<>(IOUtils.readBytesFromStream(url4.openStream()));
    Holder<byte[]> attach5 = new Holder<>(IOUtils.readBytesFromStream(url5.openStream()));
    org.apache.cxf.swa_nomime.types.VoidRequest request
        = new org.apache.cxf.swa_nomime.types.VoidRequest();
    org.apache.cxf.swa_nomime.types.OutputResponseAll response
        = port.echoAllAttachmentTypes(request,
                                      attach1,
                                      attach2,
                                      attach3,
                                      attach4,
                                      attach5);
    assertNotNull(response);
}
 
Example #25
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void addDigest(WriterInterceptorContext context) throws IOException {
    // make sure we have all content
    OutputStream originalOutputStream = context.getOutputStream();
    CachedOutputStream cachedOutputStream = new CachedOutputStream();
    context.setOutputStream(cachedOutputStream);

    context.proceed();
    cachedOutputStream.flush();

    // then digest using requested encoding
    String encoding = context.getMediaType().getParameters()
        .getOrDefault(MediaType.CHARSET_PARAMETER, StandardCharsets.UTF_8.toString());
    // not so nice - would be better to have a stream

    String digest = digestAlgorithmName + "=";
    try {
        MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithmName);
        messageDigest.update(new String(cachedOutputStream.getBytes(), encoding).getBytes());
        if (!emptyDigestValue) {
            if (changeDigestValue) {
                byte[] bytes = messageDigest.digest();
                bytes[0] += 1;
                digest += Base64.getEncoder().encodeToString(bytes);
            } else {
                digest += Base64.getEncoder().encodeToString(messageDigest.digest());
            }
        }
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // add header
    context.getHeaders().add(DIGEST_HEADER_NAME, digest);
    sign(context);

    // write the contents
    context.setOutputStream(originalOutputStream);
    IOUtils.copy(cachedOutputStream.getInputStream(), originalOutputStream);
}
 
Example #26
Source File: MtomTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testMtomReply() throws Exception {
    setupForTest(true);
    DataHandlerBean dhBean = client.produceDataHandlerBean();
    Assert.assertNotNull(dhBean);
    String result = IOUtils.toString(dhBean.getDataHandler().getInputStream());
    Assert.assertEquals(MtomTestImpl.STRING_DATA, result);
}
 
Example #27
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookQueryGZIP() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/";
    WebClient wc = WebClient.create(address);
    wc.acceptEncoding("gzip,deflate");
    wc.encoding("gzip");
    InputStream r = wc.get(InputStream.class);
    assertNotNull(r);
    GZIPInputStream in = new GZIPInputStream(r);
    String s = IOUtils.toString(in);
    in.close();
    assertTrue(s, s.contains("id>124"));
}
 
Example #28
Source File: HTTPConnector.java    From cloud-sfsf-benefits-ext with Apache License 2.0 5 votes vote down vote up
private SimpleHttpResponse executeGET(HttpURLConnection connection) throws IOException, InvalidResponseException {
    connection.setRequestMethod(GET_METHOD);
    int responseCode = connection.getResponseCode();
    SimpleHttpResponse httpResponse = new SimpleHttpResponse(connection.getURL().toString(), responseCode, connection.getResponseMessage());
    httpResponse.setContentType(connection.getContentType());
    httpResponse.setContent(IOUtils.toString(connection.getInputStream()));
    logResponse(httpResponse);
    validateResponse(httpResponse);
    return httpResponse;
}
 
Example #29
Source File: RMMessageTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testContentCachedOutputStream() throws Exception {
    RMMessage msg = new RMMessage();
    CachedOutputStream co = new CachedOutputStream();
    co.write(DATA);
    msg.setContent(co);

    byte[] msgbytes = IOUtils.readBytesFromStream(msg.getContent().getInputStream());

    assertArrayEquals(DATA, msgbytes);
    co.close();
}
 
Example #30
Source File: JAXRSMultipartTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void doTestNullPart(String address) throws Exception {
    WebClient client = WebClient.create(address);
    client.type("multipart/form-data").accept("text/plain");
    List<Attachment> atts = new LinkedList<>();
    atts.add(new Attachment("somepart", "text/plain", "hello there"));
    Response r = client.postCollection(atts, Attachment.class);
    assertEquals(Response.Status.OK.getStatusCode(), r.getStatus());
    assertEquals("nobody home", IOUtils.readStringFromStream((InputStream)r.getEntity()));
}