Example usage for org.apache.commons.io.input TeeInputStream TeeInputStream

List of usage examples for org.apache.commons.io.input TeeInputStream TeeInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input TeeInputStream TeeInputStream.

Prototype

public TeeInputStream(InputStream input, OutputStream branch) 

Source Link

Document

Creates a TeeInputStream that proxies the given InputStream and copies all read bytes to the given OutputStream .

Usage

From source file:org.dataconservancy.ui.services.UrlDepositDocumentResolver.java

@Override
public DepositDocument resolve(String depositId) {
    URL depositUrl = null;/* w  ww  .ja va  2 s  . c  o  m*/
    try {
        depositUrl = new URL(depositId);
    } catch (MalformedURLException e) {
        log.info("Deposit ID '" + depositId + "' cannot be converted to a URL.", e);
        return null;
    }

    InputStream in = null;
    try {
        in = depositUrl.openStream();
        if (log.isDebugEnabled() && in != null) {
            File tmp = File.createTempFile("feed-"
                    + Thread.currentThread().getName().replace(" ", "_").replace("/", "_").replace("\\", "_"),
                    ".xml");
            log.debug("Copy of deposit feed: {}", tmp);
            in = new TeeInputStream(in, new FileOutputStream(tmp));
        }
        return parser.parse(in);
    } catch (IOException e) {
        log.info("Could not open URL " + depositId + ": " + e.getMessage(), e);
        return null;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            // don't care
        }
    }
}

From source file:org.eclipse.koneki.protocols.omadm.client.basic.DMBasicSession.java

void sendPackageAndReceivePackage() throws IOException, DMClientException {
    this.dmClient.sendAndReceiveMessage(this.server, ENCODING, new DMMessenger() {
        @Override//from www.ja  v a2s .  c  om
        public void writeMessage(final OutputStream out) throws DMClientException {
            try {
                if (!DMBasicSession.this.isSetupPhaseFired) {
                    DMBasicSession.this.fireSetupPhaseBegin();
                    DMBasicSession.this.isSetupPhaseFired = true;
                }
                if (!DMBasicSession.this.isManagementPhaseFired && DMBasicSession.this.isClientAuthenticated) {
                    DMBasicSession.this.fireManagementPhaseBegin();
                    DMBasicSession.this.isManagementPhaseFired = true;
                }
                if (DMBasicSession.this.protocolLinsteners.length != 0) {
                    final ByteArrayOutputStream message = new ByteArrayOutputStream();
                    DMBasicSession.this.writeMessage(new TeeOutputStream(out, message));
                    DMBasicSession.this.fireNewClientPackage(message.toString(ENCODING));
                } else {
                    DMBasicSession.this.writeMessage(out);
                }
            } catch (final XMLStreamException e) {
                throw new DMClientException(e);
            } catch (final UnsupportedEncodingException e) {
                throw new DMClientException(e);
            }
        }

        @Override
        public void readMessage(final InputStream in) throws DMClientException {
            try {
                if (DMBasicSession.this.protocolLinsteners.length != 0) {
                    final ByteArrayOutputStream message = new ByteArrayOutputStream();
                    DMBasicSession.this.readMessage(new TeeInputStream(in, message));
                    DMBasicSession.this.fireNewServerPackage(message.toString(ENCODING));
                } else {
                    DMBasicSession.this.readMessage(in);
                }
                if (!DMBasicSession.this.isManagementPhaseFired && DMBasicSession.this.isClientAuthenticated) {
                    DMBasicSession.this.fireSetupPhaseEnd();
                }
                if (!DMBasicSession.this.isSessionContinue) {
                    DMBasicSession.this.fireManagementPhaseEnd();
                }
            } catch (final XMLStreamException e) {
                throw new DMClientException(e);
            } catch (final UnsupportedEncodingException e) {
                throw new DMClientException(e);
            }
        }
    });
}

From source file:org.iqvis.nvolv3.request.filter.RequestWrapper.java

@Override
public ServletInputStream getInputStream() throws IOException {
    return new ServletInputStream() {
        private TeeInputStream tee = new TeeInputStream(RequestWrapper.super.getInputStream(), bos);

        @Override// ww  w. j a  va 2 s.  com
        public int read() throws IOException {
            return tee.read();
        }

        @Override
        public boolean isFinished() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean isReady() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public void setReadListener(ReadListener arg0) {
            // TODO Auto-generated method stub

        }
    };
}

From source file:org.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImpl.java

/**
 * Extracts a {@link List} of {@link Calendar}s from the {@link InputStream}, if present.
 * /*from   w w  w  .j  av  a2s  .c om*/
 * @param inputStream
 * @return a never null, but possibly empty {@link List} of {@link Calendar}s from the {@link InputStream}
 * @throws XmlParsingException in the event the stream could not be properly parsed
 */
public List<CalendarWithURI> extractCalendars(InputStream inputStream) {
    List<CalendarWithURI> results = new ArrayList<CalendarWithURI>();
    ByteArrayOutputStream capturedContent = null;
    XMLInputFactory factory = XMLInputFactory.newInstance();
    try {
        InputStream localReference = inputStream;
        if (log.isDebugEnabled()) {
            capturedContent = new ByteArrayOutputStream();
            localReference = new TeeInputStream(inputStream, capturedContent);
        }
        BufferedInputStream buffered = new BufferedInputStream(localReference);
        buffered.mark(1);
        int firstbyte = buffered.read();
        if (-1 == firstbyte) {
            // short circuit on empty stream
            return results;
        }
        buffered.reset();
        XMLStreamReader parser = factory.createXMLStreamReader(buffered);

        String currentUri = null;
        String currentEtag = null;
        for (int eventType = parser.next(); eventType != XMLStreamConstants.END_DOCUMENT; eventType = parser
                .next()) {
            switch (eventType) {
            case XMLStreamConstants.START_ELEMENT:
                QName name = parser.getName();
                if (isWebdavHrefElement(name)) {
                    currentUri = parser.getElementText();
                } else if (isWebdavEtagElement(name)) {
                    currentEtag = parser.getElementText();
                } else if (isCalendarDataElement(name)) {
                    Calendar cal = extractCalendar(parser.getElementText());
                    if (cal != null) {
                        CalendarWithURI withUri = new CalendarWithURI(cal, currentUri, currentEtag);
                        results.add(withUri);
                    } else if (log.isDebugEnabled()) {
                        log.debug("extractCalendar returned null for " + currentUri + ", skipping");
                    }
                }
                break;
            }
        }

        if (log.isDebugEnabled()) {
            log.debug("extracted " + results.size() + " calendar from " + capturedContent.toString());
        }

    } catch (XMLStreamException e) {
        if (capturedContent != null) {
            log.error("caught XMLStreamException in extractCalendars, captured content: "
                    + capturedContent.toString(), e);
        } else {
            log.error("caught XMLStreamException in extractCalendars, no captured content available", e);
        }
        throw new XmlParsingException("caught XMLStreamException in extractCalendars", e);
    } catch (IOException e) {
        log.error("caught IOException in extractCalendars", e);
        throw new XmlParsingException("caught IOException in extractCalendars", e);
    }

    return results;
}

From source file:org.paxle.core.doc.impl.BasicDocumentFactoryTest.java

public void testLoadUnmarshalledCommand() throws IOException, ParseException {
    final ZipFile zf = new ZipFile(new File("src/test/resources/command.zip"));

    // process attachments
    final Map<String, DataHandler> attachments = new HashMap<String, DataHandler>();
    for (Enumeration<? extends ZipEntry> entries = zf.entries(); entries.hasMoreElements();) {
        final ZipEntry entry = entries.nextElement();
        final String name = entry.getName();
        if (name.equals("command.xml"))
            continue;

        // create a data-source to load the attachment
        final DataSource source = new DataSource() {
            private ZipFile zip = zf;
            private ZipEntry zipEntry = entry;

            public String getContentType() {
                return "application/x-java-serialized-object";
            }/*from   w w w.j  av  a2 s .  c  o  m*/

            public InputStream getInputStream() throws IOException {
                return this.zip.getInputStream(this.zipEntry);
            }

            public String getName() {
                return this.zipEntry.getName();
            }

            public OutputStream getOutputStream() throws IOException {
                throw new UnsupportedOperationException();
            }
        };
        final DataHandler handler = new DataHandler(source);
        attachments.put(name, handler);
    }

    // process command
    final ZipEntry commandEntry = zf.getEntry("command.xml");
    final InputStream commandInput = zf.getInputStream(commandEntry);

    // marshal command
    TeeInputStream input = new TeeInputStream(commandInput, System.out);
    final ICommand cmd1 = this.docFactory.unmarshal(input, attachments);
    assertNotNull(cmd1);
    zf.close();

    final ICommand cmd2 = this.createTestCommand();
    assertEquals(cmd2, cmd1);
}

From source file:org.warlock.spine.connection.Transmitter.java

@Override
public void run() {
    ConnectionManager c = ConnectionManager.getInstance();
    if (!sendable.recordTry()) {
        if (sendable.getMessageId() != null) {
            c.removeRequest(sendable.getMessageId());
            sendable.expire();// w  w  w.  j a v a 2 s . c  om
        }
        return;
    }

    SpineSecurityContext tlsContext = c.getSecurityContext();
    //        SSLSocketFactory sf = tlsContext.getSocketFactory();
    String h = sendable.getResolvedUrl();
    String host = null;
    int port = 443;
    try {
        if (h == null) {
            // Retry of persisted reliable message from previous MHS session
            //
            host = ((org.warlock.spine.messaging.EbXmlMessage) sendable).getHost();
        } else {
            sendable.persist();
            URL u = new URL(h);
            host = u.getHost();
            port = (u.getPort() == -1) ? u.getDefaultPort() : u.getPort();
        }
        //Override host and port when using Proxy
        String proxyhost = System.getProperty(PROXYHOST);
        if (proxyhost != null && (proxyhost.trim().length() != 0)) {
            host = proxyhost;
        }
        String p = System.getProperty(PROXYPORT);
        if ((p != null) && (p.trim().length() != 0)) {
            try {
                int proxyport = Integer.parseInt(p);
                port = proxyport;
            } catch (NumberFormatException e) {
                System.err.println("Asynchronous wait period not a valid integer - " + e.toString());
            }
        }
        try (Socket s = tlsContext.createSocket(host, port)) {
            int replyLength = -1;
            SessionCaptor sc = c.getSessionCaptor();
            if (sc == null) {
                sendable.write(s.getOutputStream());
                replyLength = getHeader(s.getInputStream());
                if (replyLength == -1) {
                    SpineToolsLogger.getInstance().log("org.warlock.spine.connection.Transmitter.noResponse",
                            "Could not read response sending " + sendable.getMessageId());
                    s.close();
                    return;
                }
                if (replyLength > 0)
                    readSynchronousReply(s.getInputStream(), replyLength);
            } else {
                ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                TeeOutputStream tos = new TeeOutputStream(s.getOutputStream(), outStream);
                sendable.write(tos);
                sendable.setOnTheWireRequest(outStream.toByteArray());
                ByteArrayOutputStream inStream = new ByteArrayOutputStream();
                TeeInputStream tis = new TeeInputStream(s.getInputStream(), inStream);
                replyLength = getHeader(tis);
                if (replyLength == -1) {
                    SpineToolsLogger.getInstance().log("org.warlock.spine.connection.Transmitter.noResponse",
                            "Could not read response sending " + sendable.getMessageId());
                    s.close();
                    sc.capture(sendable);
                    return;
                }
                if (replyLength > 0) {
                    readSynchronousReply(tis, replyLength);
                    sendable.setOnTheWireResponse(inStream.toByteArray());
                }
                sc.capture(sendable);
            }
        }
        if (sendable.getType() == Sendable.SOAP) {
            if (sendable.getSynchronousResponse() == null) {
                SpineToolsLogger.getInstance().log(
                        "org.warlock.spine.connection.Transmitter.noResponseReceived",
                        "No response to " + sendable.getMessageId());
                return;
            }
            SynchronousResponseHandler handler = c.getSynchronousResponseHandler(sendable.getSoapAction());
            handler.handle((SpineSOAPRequest) sendable);
            return;
        }
        if (sendable.getMessageId() != null) { // Don't do this for asynchronous acks
            if (sendable.getSynchronousResponse() != null) {
                if ((responseHeader != null) && (responseHeader.contains("HTTP 5"))) {
                    SpineToolsLogger.getInstance().log(
                            "org.warlock.spine.connection.Transmitter.HTTP500received",
                            "HTTP 500 received sending " + sendable.getMessageId());
                    c.removeRequest(sendable.getMessageId());

                } else {
                    if (sendable.getSynchronousResponse().contains(sendable.getMessageId())) {
                        c.registerAck(sendable.getMessageId());
                    }
                    if (sendable.getSynchronousResponse().contains("Bad request")) {
                        c.registerAck(sendable.getMessageId());
                        SpineToolsLogger.getInstance().log(
                                "org.warlock.spine.connection.Transmitter.HTTP500received",
                                "Bad request received sending " + sendable.getMessageId());
                    }
                }
            }
        }
    } catch (Exception eIo) {
        SpineToolsLogger.getInstance().log("org.warlock.spine.connection.Transmitter.IOException",
                "IOException sending " + sendable.getMessageId() + eIo.getMessage());
    }
}