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

The following examples show how to use org.apache.cxf.helpers.IOUtils#copyAndCloseInput() . 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: SoapFaultHandlerTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testFaultThrowingHandler() throws Exception {
    // set the post request using url connection
    URL postUrl = new URL(addNumbersAddress);
    HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Content-Type",
        "text/xml; charset=UTF-8");
    connection.connect();
    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
    InputStream is = this.getClass().getResourceAsStream("resources/GreetMeDocLiteralReq.xml");

    IOUtils.copyAndCloseInput(is, out);
    out.flush();
    out.close();
    InputStream response = getInputStream(connection);
    // get the response fault message
    String result = IOUtils.toString(response, StandardCharsets.UTF_8.name());
    // just make sure the custom namespace is working
    assertTrue("The custom namespace is not working.", result.indexOf("cxf:Provider") > 0);

}
 
Example 2
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 3
Source File: BinaryDataProvider.java    From cxf with Apache License 2.0 6 votes vote down vote up
protected void copyInputToOutput(InputStream is, OutputStream os,
        Annotation[] anns, MultivaluedMap<String, Object> outHeaders) throws IOException {
    if (isRangeSupported()) {
        Message inMessage = PhaseInterceptorChain.getCurrentMessage().getExchange().getInMessage();
        handleRangeRequest(is, os, new HttpHeadersImpl(inMessage), outHeaders);
    } else {
        boolean nioWrite = AnnotationUtils.getAnnotation(anns, UseNio.class) != null;
        if (nioWrite) {
            ContinuationProvider provider = getContinuationProvider();
            if (provider != null) {
                copyUsingNio(is, os, provider.getContinuation());
            }
            return;
        }
        if (closeResponseInputStream) {
            IOUtils.copyAndCloseInput(is, os, bufferSize);
        } else {
            IOUtils.copy(is, os, bufferSize);
        }

    }
}
 
Example 4
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 5
Source File: CachedOutputStream.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
public void transferTo(File destinationFile) throws IOException {
    if (closed) {
        throw new IOException("Stream closed");
    }
    //We've cached the file so try renaming.
    boolean transfered = sourceFile.renameTo(destinationFile);
    if (!transfered) {
        // Data is in memory, or we failed to rename the file, try copying
        // the stream instead.
        try (OutputStream out = Files.newOutputStream(destinationFile.toPath())) {
            IOUtils.copyAndCloseInput(this, out);
        }
    }
}
 
Example 6
Source File: MessageContentUtil.java    From peer-os with Apache License 2.0 5 votes vote down vote up
public static void decryptContent( SecurityManager securityManager, Message message, String hostIdSource,
                                   String hostIdTarget )
{

    InputStream is = message.getContent( InputStream.class );
    if( is == null )
    {
        LOG.error( "Error decrypting content: No content: " + message.getExchange() );
        return;
    }

    CachedOutputStream os = new CachedOutputStream();

    LOG.debug( String.format( "Decrypting IDs: %s -> %s", hostIdSource, hostIdTarget ) );
    try
    {
        int copied = IOUtils.copyAndCloseInput( is, os );
        os.flush();

        byte[] data = copied > 0 ? decryptData( securityManager, hostIdSource, os.getBytes() ) : null;
        org.apache.commons.io.IOUtils.closeQuietly( os );

        if ( !ArrayUtils.isEmpty( data ) )
        {
            LOG.debug( String.format( "Decrypted payload: \"%s\"", new String( data ) ) );
            message.setContent( InputStream.class, new ByteArrayInputStream( data ) );
        }
        else
        {
            LOG.debug( "Decrypted data is NULL!!!" );
        }
    }
    catch ( Exception e )
    {
        LOG.error( "Error decrypting content", e );
    }
}
 
Example 7
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 8
Source File: ImageDataContentHandler.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void writeTo(Object obj, String mimeType, OutputStream os) throws IOException {
    if (obj instanceof Image) {
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByMIMEType(mimeType);
        if (writers.hasNext()) {
            ImageWriter writer = writers.next();

            BufferedImage bimg = convertToBufferedImage((Image)obj);
            ImageOutputStream out = ImageIO.createImageOutputStream(os);
            writer.setOutput(out);
            writer.write(bimg);
            writer.dispose();
            out.flush();
            out.close();
            return;
        }
    } else if (obj instanceof byte[]) {
        os.write((byte[])obj);
    } else if (obj instanceof InputStream) {
        IOUtils.copyAndCloseInput((InputStream)obj, os);
    } else if (obj instanceof File) {
        InputStream file = Files.newInputStream(((File)obj).toPath());
        IOUtils.copyAndCloseInput(file, os);
    } else {
        throw new IOException("Attachment type not spported " + obj.getClass());
    }

}
 
Example 9
Source File: NettyServerTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetWsdl() throws Exception {
    URL url = new URL("http://localhost:" + PORT + "/SoapContext/SoapPort?wsdl");

    InputStream in = url.openStream();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copyAndCloseInput(in, bos);
    String result = bos.toString();
    assertTrue("Expect the SOAPService", result.indexOf("<service name=\"SOAPService\">") > 0);
}
 
Example 10
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 11
Source File: CachedWriter.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(Writer out, boolean copyOldContent) throws IOException {
    if (out == null) {
        out = new LoadingCharArrayWriter();
    }

    if (currentStream instanceof CachedWriter) {
        CachedWriter ac = (CachedWriter) currentStream;
        Reader in = ac.getReader();
        IOUtils.copyAndCloseInput(in, out);
    } else {
        if (inmem) {
            if (currentStream instanceof LoadingCharArrayWriter) {
                LoadingCharArrayWriter byteOut = (LoadingCharArrayWriter) currentStream;
                if (copyOldContent && byteOut.size() > 0) {
                    byteOut.writeTo(out);
                }
            } else {
                throw new IOException("Unknown format of currentStream");
            }
        } else {
            // read the file
            currentStream.close();
            if (copyOldContent) {
                InputStreamReader fin = createInputStreamReader(tempFile);
                IOUtils.copyAndCloseInput(fin, out);
            }
            streamList.remove(currentStream);
            deleteTempFile();
            inmem = true;
        }
    }
    currentStream = out;
    outputLocked = false;
}
 
Example 12
Source File: CachedOutputStream.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void writeCacheTo(OutputStream out) throws IOException {
    flush();
    if (inmem) {
        if (currentStream instanceof ByteArrayOutputStream) {
            ((ByteArrayOutputStream)currentStream).writeTo(out);
        } else {
            throw new IOException("Unknown format of currentStream");
        }
    } else {
        // read the file
        InputStream fin = createInputStream(tempFile);
        IOUtils.copyAndCloseInput(fin, out);
    }
}
 
Example 13
Source File: BinaryDataProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void handleRangeRequest(InputStream is,
                                  OutputStream os,
                                  HttpHeaders inHeaders,
                                  MultivaluedMap<String, Object> outHeaders) throws IOException {
    String range = inHeaders.getRequestHeaders().getFirst("Range");
    if (range == null) {
        IOUtils.copyAndCloseInput(is, os, bufferSize);
    } else {
        // implement
    }

}
 
Example 14
Source File: DataSourceProvider.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void writeTo(T src, Class<?> cls, Type genericType, Annotation[] annotations,
                    MediaType type, MultivaluedMap<String, Object> headers, OutputStream os)
    throws IOException {
    DataSource ds = DataSource.class.isAssignableFrom(cls)
        ? (DataSource)src : ((DataHandler)src).getDataSource();
    if (useDataSourceContentType) {
        setContentTypeIfNeeded(type, headers, ds.getContentType());
    }
    IOUtils.copyAndCloseInput(ds.getInputStream(), os);
}
 
Example 15
Source File: DataSourceType.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Override
protected byte[] getBytes(Object object) {
    DataSource dataSource = (DataSource) object;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        IOUtils.copyAndCloseInput(dataSource.getInputStream(), baos);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return baos.toByteArray();
}
 
Example 16
Source File: JAXRSAtomBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
private InputStream copyIn(InputStream in) throws Exception {
    try (CachedOutputStream bos = new CachedOutputStream()) {
        IOUtils.copyAndCloseInput(in, bos);
        in = bos.getInputStream();
        bos.close();
        return in;
    }
}
 
Example 17
Source File: JAXRSClientServerResourceCreatedSpringProviderTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testPostPetStatus2() throws Exception {


    try (Socket s = new Socket("localhost", Integer.parseInt(PORT))) {
        IOUtils.copyAndCloseInput(getClass().getResource("resources/formRequest.txt").openStream(),
                                  s.getOutputStream());

        s.getOutputStream().flush();
        assertTrue("Wrong status returned", getStringFromInputStream(s.getInputStream())
                   .contains("open"));
    }
}
 
Example 18
Source File: CachedStreamTestBase.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected static String readFromStream(InputStream is) throws IOException {
    try (ByteArrayOutputStream buf = new ByteArrayOutputStream()) {
        IOUtils.copyAndCloseInput(is, buf);
        return new String(buf.toByteArray(), StandardCharsets.UTF_8);
    }
}
 
Example 19
Source File: WireTapIn.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void handleReader(Message message, Reader reader) throws IOException {
    CachedWriter writer = new CachedWriter();
    IOUtils.copyAndCloseInput(reader, writer);
    message.setContent(Reader.class, writer.getReader());
    message.setContent(CachedWriter.class, writer);
}
 
Example 20
Source File: CachedStreamTestBase.java    From cxf with Apache License 2.0 4 votes vote down vote up
protected static String readFromReader(Reader is) throws IOException {
    try (StringWriter writer = new StringWriter()) {
        IOUtils.copyAndCloseInput(is, writer);
        return writer.toString();
    }
}