Example usage for org.apache.commons.io.output TeeOutputStream TeeOutputStream

List of usage examples for org.apache.commons.io.output TeeOutputStream TeeOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.output TeeOutputStream TeeOutputStream.

Prototype

public TeeOutputStream(OutputStream out, OutputStream branch) 

Source Link

Document

Constructs a TeeOutputStream.

Usage

From source file:com.joyent.manta.http.entity.DigestedEntity.java

@Override
public void writeTo(final OutputStream out) throws IOException {
    digest.reset(); // reset the digest state in case we're in a retry

    // If our wrapped entity is backed by a buffer of some form
    // we can read easily read the whole buffer into our message digest.
    if (wrapped instanceof MemoryBackedEntity) {
        final MemoryBackedEntity entity = (MemoryBackedEntity) wrapped;
        final ByteBuffer backingBuffer = entity.getBackingBuffer();

        if (backingBuffer.hasArray()) {
            final byte[] bytes = backingBuffer.array();
            final int offset = backingBuffer.arrayOffset();
            final int position = backingBuffer.position();
            final int limit = backingBuffer.limit();

            digest.update(bytes, offset + position, limit - position);
            backingBuffer.position(limit);

            wrapped.writeTo(out);/*  w  w  w. jav a  2  s  .  c  o  m*/
        }
    } else {
        try (DigestOutputStream dout = new DigestOutputStream(digest);
                TeeOutputStream teeOut = new TeeOutputStream(out, dout)) {
            wrapped.writeTo(teeOut);
            teeOut.flush();
        }
    }
}

From source file:com.sonar.scanner.api.it.tools.CommandExecutor.java

private ExecuteStreamHandler createStreamHandler() throws IOException {
    logs = new ByteArrayOutputStream();
    PipedOutputStream outPiped = new PipedOutputStream();
    InputStream inPiped = new PipedInputStream(outPiped);
    in = outPiped;//from w  w w.  j  a va 2 s.  c o m

    TeeOutputStream teeOut = new TeeOutputStream(logs, System.out);
    TeeOutputStream teeErr = new TeeOutputStream(logs, System.err);

    return new PumpStreamHandler(teeOut, teeErr, inPiped);
}

From source file:it.sonarlint.cli.tools.CommandExecutor.java

private ExecuteStreamHandler createStreamHandler() throws IOException {
    out = new ByteArrayOutputStream();
    err = new ByteArrayOutputStream();
    PipedOutputStream outPiped = new PipedOutputStream();
    InputStream inPiped = new PipedInputStream(outPiped);
    in = outPiped;/*  w  w w.  j a  va 2 s  .  co m*/

    TeeOutputStream teeOut = new TeeOutputStream(out, System.out);
    TeeOutputStream teeErr = new TeeOutputStream(err, System.err);

    return new PumpStreamHandler(teeOut, teeErr, inPiped);
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java

@Override
public void encrypt(String fileName, int size, InputStream inputStream, OutputStream outputStream)
        throws InvalidCipherTextException, IOException {
    final TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(outputStream, 512,
            ENCODING);//from   www .j a  v  a 2 s  . c  o  m

    final BufferedBlockCipher cipher = createCipher(tarArchiveOutputStream);

    startEncryptedFile(fileName, size, tarArchiveOutputStream, cipher);

    //Setup cipher output stream, has to protect from close as the cipher stream must close but the tar cannot get closed yet
    final CipherOutputStream cipherOutputStream = new CipherOutputStream(
            new CloseShieldOutputStream(tarArchiveOutputStream), cipher);

    //Setup digester
    final DigestOutputStream digestOutputStream = new DigestOutputStream(this.createDigester());

    //Perform streaming encryption and hashing of the file
    IOUtils.copy(inputStream, new TeeOutputStream(cipherOutputStream, digestOutputStream));
    cipherOutputStream.close();

    tarArchiveOutputStream.closeArchiveEntry();

    //Capture the hash code of the encrypted file
    digestOutputStream.close();
    final byte[] hashBytes = digestOutputStream.getDigest();

    this.writeHashfile(tarArchiveOutputStream, hashBytes);

    //Close the TAR stream, nothing else should be written to it
    tarArchiveOutputStream.close();
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileDecrypter.java

@Override
public void decrypt(InputStream inputStream, OutputStream outputStream)
        throws InvalidCipherTextException, IOException, DecoderException {
    final TarArchiveInputStream tarInputStream = new TarArchiveInputStream(inputStream, FileEncrypter.ENCODING);

    final BufferedBlockCipher cipher = createCipher(tarInputStream);

    //Advance to the next entry in the tar file
    tarInputStream.getNextTarEntry();/*from  ww  w .ja  v a2s  .  c  o m*/

    //Create digest output stream used to generate digest while decrypting
    final DigestOutputStream digestOutputStream = new DigestOutputStream(this.createDigester());

    //Do a streaming decryption of the file output
    final CipherOutputStream cipherOutputStream = new CipherOutputStream(
            new TeeOutputStream(outputStream, digestOutputStream), cipher);
    IOUtils.copy(tarInputStream, cipherOutputStream);
    cipherOutputStream.close();

    //Capture the hash of the decrypted output
    final byte[] hashBytes = digestOutputStream.getDigest();
    verifyOutputHash(tarInputStream, hashBytes);
}

From source file:com.magnet.tools.tests.CukeCommandExecutor.java

/**
 * Ctor/*from w  w w.  j  av a2  s .c om*/
 *
 * @param workingDirectory working directory for execution
 * @param async            whether to wait for command to return
 * @param subsMap          variables substitution
 * @param vars             variables where to save optional expression evaluation
 * @param testEnv          test environment
 * @param command          command line to execute
 * @throws java.io.IOException if an exception occurred
 */
public CukeCommandExecutor(String command, String workingDirectory, boolean async, Map<String, String> subsMap,
        Map<String, Object> vars, Map<String, String> testEnv) throws IOException {

    this.substitutionMap = subsMap;
    this.testEnvironment = testEnv;
    this.variables = vars;
    // Must get the existing environment so it inherits but overrides
    Map<String, String> env = new HashMap<String, String>(System.getenv());
    if (null != testEnvironment) {
        env.putAll(testEnvironment);
    }
    env.put("user.home", System.getProperty("user.home"));

    ExecuteWatchdog watchdog = new ExecuteWatchdog(TIMEOUT);
    setWatchdog(watchdog);
    String[] args = command.split("\\s+");
    commandLine = new CommandLine(args[0]);
    if (args.length > 0) {
        for (int i = 1; i < args.length; i++) {
            commandLine.addArgument(args[i]);
        }
    }
    commandLine.setSubstitutionMap(substitutionMap);

    this.environment = env;
    this.command = command;
    this.async = async;
    setWorkingDirectory(new File(workingDirectory));
    String logFileName = command.replaceAll("[:\\.\\-\\s\\/\\\\]", "_");
    if (logFileName.length() > 128) {
        logFileName = logFileName.substring(0, 100);
    }
    this.logFile = new File(getWorkingDirectory(),
            "cuke_logs" + File.separator + +System.currentTimeMillis() + "-" + logFileName + ".log");

    FileUtils.forceMkdir(logFile.getParentFile());

    OutputStream outputStream = new FileOutputStream(logFile);
    this.teeOutputStream = new TeeOutputStream(outputStream, System.out); // also redirected to stdout
    ExecuteStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    this.setStreamHandler(streamHandler);
}

From source file:hu.bme.mit.sette.common.tasks.RunnerProjectRunner.java

/**
 * Runs the runner project.//from w  w  w . jav a 2  s. co  m
 *
 * @param pLogger
 *            the logger stream
 * @throws RunnerProjectRunnerException
 *             if running has failed
 */
public final void run(final PrintStream pLogger) throws RunnerProjectRunnerException {
    String phase = null;
    PrintStream logger = null;

    try {
        this.cleanUp();

        // validate preconditions
        phase = "validate (do)";
        validate();
        phase = "validate (after)";
        afterValidate();

        // prepare
        phase = "prepare (do)";
        prepare();
        phase = "prepare (after)";
        afterPrepare();

        // create logger
        File logFile = RunnerProjectUtils.getRunnerLogFile(getRunnerProjectSettings());

        if (pLogger != null) {
            pLogger.println("Log file: " + logFile.getCanonicalPath());
            logger = new PrintStream(new TeeOutputStream(new FileOutputStream(logFile), pLogger), true);
        } else {
            logger = new PrintStream(new FileOutputStream(logFile), true);
        }

        // run all
        phase = "run all (do)";
        runAll(logger);
        phase = "run all (after)";
        afterRunAll();

        cleanUp();
        phase = "complete";
    } catch (Exception e) {
        String message = String.format("The runner project run has failed\n" + "(phase: [%s])\n(tool: [%s])",
                phase, getTool().getFullName());
        throw new RunnerProjectRunnerException(message, this, e);
    } finally {
        IOUtils.closeQuietly(logger);
    }
}

From source file:net.community.chest.gitcloud.facade.backend.git.BackendReceivePackFactory.java

@Override
public ReceivePack create(C request, Repository db)
        throws ServiceNotEnabledException, ServiceNotAuthorizedException {
    final String logPrefix;
    if (request instanceof HttpServletRequest) {
        HttpServletRequest req = (HttpServletRequest) request;
        logPrefix = "create(" + req.getMethod() + ")[" + req.getRequestURI() + "][" + req.getQueryString()
                + "]";
    } else {//from   ww w  .ja v  a2  s .c  o  m
        logPrefix = "create(" + db.getDirectory() + ")";
    }
    if (logger.isDebugEnabled()) {
        logger.debug(logPrefix + ": " + db.getDirectory());
    }

    ReceivePack receive = new ReceivePack(db) {
        @Override
        @SuppressWarnings("synthetic-access")
        public void receive(InputStream input, OutputStream output, OutputStream messages) throws IOException {
            InputStream effIn = input;
            OutputStream effOut = output, effMessages = messages;
            if (logger.isTraceEnabled()) {
                LineLevelAppender inputAppender = new LineLevelAppender() {
                    @Override
                    public void writeLineData(CharSequence lineData) throws IOException {
                        logger.trace(logPrefix + " upload(C): " + lineData);
                    }

                    @Override
                    public boolean isWriteEnabled() {
                        return true;
                    }
                };
                effIn = new TeeInputStream(effIn, new HexDumpOutputStream(inputAppender), true);

                LineLevelAppender outputAppender = new LineLevelAppender() {
                    @Override
                    public void writeLineData(CharSequence lineData) throws IOException {
                        logger.trace(logPrefix + " upload(S): " + lineData);
                    }

                    @Override
                    public boolean isWriteEnabled() {
                        return true;
                    }
                };
                effOut = new TeeOutputStream(effOut, new HexDumpOutputStream(outputAppender));

                if (effMessages != null) {
                    LineLevelAppender messagesAppender = new LineLevelAppender() {
                        @Override
                        public void writeLineData(CharSequence lineData) throws IOException {
                            logger.trace(logPrefix + " upload(M): " + lineData);
                        }

                        @Override
                        public boolean isWriteEnabled() {
                            return true;
                        }
                    };
                    // TODO review the decision to use an AsciiLineOutputStream here
                    effMessages = new TeeOutputStream(effMessages, new AsciiLineOutputStream(messagesAppender));
                }
            }

            super.receive(effIn, effOut, effMessages);
        }
    };
    receive.setTimeout(receiveTimeoutValue);

    // TODO set pushing user identity for reflog
    // receive.setRefLogIdent(new PersonIdent(user.username, user.username + "@" + origin))

    // TODO set advanced options
    // receive.setAllowCreates(user.canCreateRef(repository));
    // receive.setAllowDeletes(user.canDeleteRef(repository));
    // receive.setAllowNonFastForwards(user.canRewindRef(repository));

    // TODO setup the receive hooks
    // receive.setPreReceiveHook(preRcvHook);
    // receive.setPostReceiveHook(postRcvHook);

    return receive;
}

From source file:ch.entwine.weblounge.cache.impl.CacheableHttpServletResponse.java

/**
 * Returns the modified writer that enables the <code>CacheManager</cache>
 * to copy the response to the cache./*from  w  w w . j  a  v  a2 s. co  m*/
 * 
 * @return a PrintWriter object that can return character data to the client
 * @throws IOException
 *           if the writer could not be allocated
 * @see javax.servlet.ServletResponse#getWriter()
 * @see ch.entwine.weblounge.OldCacheManager.cache.CacheManager
 */
@Override
public PrintWriter getWriter() throws IOException {
    // Check whether there's already a writer allocated
    if (out != null)
        return out;

    // Check whether getOutputStream() has already been called
    if (osCalled)
        throw new IllegalStateException("An output stream has already been allocated");

    // Get the character encoding
    String encoding = getCharacterEncoding();
    if (encoding == null) {
        encoding = DEFAULT_ENCODING;
        setCharacterEncoding(encoding);
    }

    // Allocate a new writer. If there is a transaction, the output is written
    // to both the original response and the cache output stream.
    try {
        if (tx == null || tx.getFilter() == null)
            out = new PrintWriter(new OutputStreamWriter(super.getOutputStream(), encoding));
        else
            out = new PrintWriter(new BufferedWriter(new FilterWriter(
                    new OutputStreamWriter(new TeeOutputStream(super.getOutputStream(), tx.getOutputStream()),
                            encoding),
                    tx.getFilter(), contentType)));
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }

    // Check whether the new writer is usable
    if (out == null)
        throw new IOException("Unable to allocate writer");

    // Return the new writer
    return out;
}

From source file:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java

@Override
public OutputStream encrypt(String fileName, int size, OutputStream outputStream)
        throws InvalidCipherTextException, IOException, DecoderException {
    final TarArchiveOutputStream tarOutputStream = new TarArchiveOutputStream(outputStream, ENCODING);

    final BufferedBlockCipher cipher = createCipher(tarOutputStream);

    startEncryptedFile(fileName, size, tarOutputStream, cipher);

    //Protect the underlying TAR stream from being closed by the cipher stream
    final CloseShieldOutputStream closeShieldTarStream = new CloseShieldOutputStream(tarOutputStream);

    //Setup the encrypting cipher stream
    final CipherOutputStream chipherStream = new CipherOutputStream(closeShieldTarStream, cipher);

    //Generate a digest of the pre-encryption data
    final GeneralDigest digest = this.createDigester();
    final DigestOutputStream digestOutputStream = new DigestOutputStream(digest);

    //Write data to both the digester and cipher
    final TeeOutputStream teeStream = new TeeOutputStream(digestOutputStream, chipherStream);
    return new EncryptingOutputStream(teeStream, tarOutputStream, digest);
}