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

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

Introduction

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

Prototype

public ProxyOutputStream(OutputStream proxy) 

Source Link

Document

Constructs a new ProxyOutputStream.

Usage

From source file:com.kurento.kmf.repository.internal.RepositoryHttpEndpointImpl.java

@Override
public OutputStream getRepoItemOutputStream() {

    if (outputStreamClosed) {
        throw new IllegalStateException("The outputStream is closed");
    }/*from w w w  . ja  v  a2  s  .  c  o m*/

    if (os == null) {
        os = new ProxyOutputStream(repositoryItem.createOutputStreamToWrite()) {

            @Override
            protected void afterWrite(int n) throws IOException {
                addWrittenBytes(n);
            }

            @Override
            public void close() throws IOException {
                super.close();
                outputStreamClosed = true;
            }
        };
    }
    return os;
}

From source file:ch.cyberduck.core.local.FinderLocal.java

@Override
public OutputStream getOutputStream(boolean append) throws AccessDeniedException {
    final NSURL resolved;
    try {//  w  ww. ja v a  2  s  .c om
        resolved = this.lock(false);
    } catch (LocalAccessDeniedException e) {
        return super.getOutputStream(append);
    }
    try {
        return new ProxyOutputStream(new FileOutputStream(new File(resolved.path()), append)) {
            @Override
            public void close() throws IOException {
                try {
                    super.close();
                } finally {
                    release(resolved);
                }
            }
        };
    } catch (FileNotFoundException e) {
        throw new LocalAccessDeniedException(e.getMessage(), e);
    }
}

From source file:com.streamsets.datacollector.io.DataStore.java

/**
 * Returns an output stream for the requested file.
 *
 * After completing the write the contents must be committed using the {@link #commit(java.io.OutputStream)}
 * method and the stream must be released using the {@link #release()} method.
 *
 * Example usage:/*from w  ww . j ava  2 s  .  c  o  m*/
 *
 * DataStore dataStore = new DataStore(...);
 * try (OutputStream os = dataStore.getOutputStream()) {
 *   os.write(..);
 *   dataStore.commit(os);
 * } catch (IOException e) {
 *   ...
 * } finally {
 *   dataStore.release();
 * }
 *
 * @return
 * @throws IOException
 */
public OutputStream getOutputStream() throws IOException {
    acquireLock();
    try {
        isClosed = false;
        forWrite = true;
        LOG.trace("Starts write '{}'", file);
        verifyAndRecover();
        if (Files.exists(file)) {
            Files.move(file, fileOld);
            LOG.trace("Starting write, move '{}' to '{}'", file, fileOld);
        }
        OutputStream os = new ProxyOutputStream(new FileOutputStream(fileTmp.toFile())) {
            @Override
            public void close() throws IOException {
                if (isClosed) {
                    return;
                }
                try {
                    super.close();
                } finally {
                    isClosed = true;
                    stream = null;
                }
                LOG.trace("Finishes write '{}'", file);
            }
        };
        stream = os;
        return os;
    } catch (Exception ex) {
        release();
        throw ex;
    }
}

From source file:org.apache.marmotta.ldpath.ldquery.LDQuery.java

public static void main(String[] args) {
    Options options = buildOptions();/*from  w w  w. j  a v  a2s.co  m*/

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        Level logLevel = Level.WARN;

        if (cmd.hasOption("loglevel")) {
            String logLevelName = cmd.getOptionValue("loglevel");
            if ("DEBUG".equals(logLevelName.toUpperCase())) {
                logLevel = Level.DEBUG;
            } else if ("INFO".equals(logLevelName.toUpperCase())) {
                logLevel = Level.INFO;
            } else if ("WARN".equals(logLevelName.toUpperCase())) {
                logLevel = Level.WARN;
            } else if ("ERROR".equals(logLevelName.toUpperCase())) {
                logLevel = Level.ERROR;
            } else {
                log.error("unsupported log level: {}", logLevelName);
            }
        }

        if (logLevel != null) {
            for (String logname : new String[] { "at", "org", "net", "com" }) {

                ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
                        .getLogger(logname);
                logger.setLevel(logLevel);
            }
        }

        File tmpDir = null;
        LDCacheBackend backend = new LDCacheBackend();

        Resource context = null;
        if (cmd.hasOption("context")) {
            context = backend.createURI(cmd.getOptionValue("context"));
        }

        if (backend != null && context != null) {
            LDPath<Value> ldpath = new LDPath<Value>(backend);

            if (cmd.hasOption("path")) {
                String path = cmd.getOptionValue("path");

                for (Value v : ldpath.pathQuery(context, path, null)) {
                    System.out.println(v.stringValue());
                }
            } else if (cmd.hasOption("program")) {
                File file = new File(cmd.getOptionValue("program"));

                Map<String, Collection<?>> result = ldpath.programQuery(context, new FileReader(file));

                if (cmd.hasOption("format")) {
                    final String format = cmd.getOptionValue("format");
                    if (format.equals("json")) {
                        // Jackson.jr closes the output stream.
                        final ProxyOutputStream proxyOutputStream = new ProxyOutputStream(System.out) {
                            @Override
                            public void close() throws IOException {
                                flush();
                            }
                        };
                        JSON.std.write(result, proxyOutputStream);
                        System.out.println("");
                    } else {
                        System.err.println("Unknown format: " + format);
                        System.exit(1);
                    }
                } else {
                    for (String field : result.keySet()) {
                        StringBuilder line = new StringBuilder();
                        line.append(field);
                        line.append(" = ");
                        line.append("{");
                        for (Iterator<?> it = result.get(field).iterator(); it.hasNext();) {
                            line.append(it.next().toString());
                            if (it.hasNext()) {
                                line.append(", ");
                            }
                        }
                        line.append("}");
                        System.out.println(line);

                    }
                }
            }
        }

        if (tmpDir != null) {
            FileUtils.deleteDirectory(tmpDir);
        }

    } catch (ParseException e) {
        System.err.println("invalid arguments");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (LDPathParseException e) {
        System.err.println("path or program could not be parsed");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        System.err.println("file or program could not be found");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    } catch (IOException e) {
        System.err.println("could not access cache data directory");
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("LDQuery", options, true);
    }

}

From source file:org.codice.ddf.configuration.migration.ExportMigrationContextImpl.java

@SuppressWarnings("PMD.DefaultPackage" /* designed to be called from ExportMigrationEntryImpl within this package */)
OutputStream getOutputStreamFor(ExportMigrationEntryImpl entry) {
    try {//w w  w  .  j a v a  2 s .c om
        close();
        // zip entries are always Unix style based on our convention
        final ZipEntry ze = new ZipEntry(id + '/' + entry.getName());

        ze.setTime(entry.getLastModifiedTime()); // save the current modified time
        zipOutputStream.putNextEntry(ze);
        final OutputStream oos = new ProxyOutputStream(zipOutputStream) {
            @Override
            public void close() throws IOException {
                if (!(super.out instanceof ClosedOutputStream)) {
                    super.out = ClosedOutputStream.CLOSED_OUTPUT_STREAM;
                    zipOutputStream.closeEntry();
                }
            }

            @Override
            protected void handleIOException(IOException e) throws IOException {
                super.handleIOException(new ExportIOException(e));
            }
        };

        CipherOutputStream cos = cipherUtils.getCipherOutputStream(oos);
        this.currentOutputStream = cos;
        return cos;
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:org.nuxeo.ecm.web.resources.wro.processor.FlavorResourceProcessor.java

@Override
protected void process(final Resource resource, final Reader reader, final Writer writer, String flavorName)
        throws IOException {
    final InputStream is = new ProxyInputStream(new ReaderInputStream(reader, getEncoding())) {
    };/*from  w  ww.  j  a  v a2s  . c  om*/
    final OutputStream os = new ProxyOutputStream(new WriterOutputStream(writer, getEncoding()));
    try {
        Map<String, String> presets = null;
        if (flavorName != null) {
            ThemeStylingService s = Framework.getService(ThemeStylingService.class);
            presets = s.getPresetVariables(flavorName);
        }
        if (presets == null || presets.isEmpty()) {
            IOUtils.copy(is, os);
        } else {
            String content = IOUtils.toString(reader);
            for (Map.Entry<String, String> preset : presets.entrySet()) {
                content = Pattern.compile("\"" + preset.getKey() + "\"", Pattern.LITERAL).matcher(content)
                        .replaceAll(Matcher.quoteReplacement(preset.getValue()));
            }
            writer.write(content);
            writer.flush();
        }
        is.close();
    } catch (final Exception e) {
        log.error("Error while serving resource " + resource.getUri(), e);
        throw WroRuntimeException.wrap(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:org.nuxeo.theme.styling.wro.FlavorResourceProcessor.java

protected void process(final Resource resource, final Reader reader, final Writer writer, String flavorName)
        throws IOException {
    final InputStream is = new ProxyInputStream(new ReaderInputStream(reader, getEncoding())) {
    };/*from ww  w  .  jav  a2  s . c  o m*/
    final OutputStream os = new ProxyOutputStream(new WriterOutputStream(writer, getEncoding()));
    try {
        Map<String, String> presets = null;
        if (flavorName != null) {
            ThemeStylingService s = Framework.getService(ThemeStylingService.class);
            presets = s.getPresetVariables(flavorName);
        }
        if (presets == null || presets.isEmpty()) {
            IOUtils.copy(is, os);
        } else {
            String content = IOUtils.toString(reader);
            for (Map.Entry<String, String> preset : presets.entrySet()) {
                content = Pattern.compile(String.format("\"%s\"", preset.getKey()), Pattern.LITERAL)
                        .matcher(content).replaceAll(Matcher.quoteReplacement(preset.getValue()));
            }
            writer.write(content);
            writer.flush();
        }
        is.close();
        os.close();
    } catch (final Exception e) {
        throw WroRuntimeException.wrap(e);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

From source file:pxb.android.dex2jar.dump.Dump.java

public static void doData(byte[] data, File destJar) throws IOException {
    final ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(destJar)));
    new DexFileReader(data).accept(new Dump(new EmptyVisitor(), new WriterManager() {

        public PrintWriter get(String name) {
            try {
                String s = name.replace('.', '/') + ".dump.txt";
                ZipEntry zipEntry = new ZipEntry(s);
                zos.putNextEntry(zipEntry);
                return new PrintWriter(new ProxyOutputStream(zos) {
                    @Override//from www  . jav  a 2 s  .  com
                    public void close() throws IOException {
                        zos.closeEntry();
                    }
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }));
    zos.finish();
    zos.close();
}