Example usage for com.google.common.io Closer create

List of usage examples for com.google.common.io Closer create

Introduction

In this page you can find the example usage for com.google.common.io Closer create.

Prototype

public static Closer create() 

Source Link

Document

Creates a new Closer .

Usage

From source file:com.googlecode.jmxtrans.test.TCPEchoServer.java

private void processRequests(ServerSocket server) throws IOException {
    Closer closer = Closer.create();
    try {/*  w  w  w.ja  v a 2s.  co  m*/
        Socket socket = server.accept();
        synchronized (startSynchro) {
            startSynchro.notifyAll();
        }
        BufferedReader in = closer
                .register(new BufferedReader(new InputStreamReader(socket.getInputStream(), UTF_8)));
        PrintWriter out = closer
                .register(new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8)));
        String line;
        while ((line = in.readLine()) != null) {
            receivedMessages.add(line);
            out.print(line);
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:biz.paluch.maven.configurator.AbstractConfigureMojo.java

/**
 * Perform Configuration.//from  w ww  .ja v a 2  s  . c om
 *
 * @param artifactFile
 * @throws MojoExecutionException
 */
protected void configure(File artifactFile) throws MojoExecutionException {

    Preconditions.checkArgument(tokenStart != null && !tokenStart.isEmpty(), "tokenStart must not be empty");
    Preconditions.checkArgument(tokenEnd != null && !tokenEnd.isEmpty(), "tokenEnd must not be empty");

    File targetConfigurator = new File(targetDir, "configurator");
    File targetWork = new File(targetConfigurator, "work");
    File finalFile = new File(targetConfigurator, artifactFile.getName());

    if (!targetWork.exists()) {
        targetWork.mkdirs();
    }

    getLog().debug("Resolved target artifact to " + artifactFile.toString());

    Closer closer = Closer.create();

    Container container = new Container(artifactFile.getName());

    try {
        ZipInputStream zis = closer
                .register(new ZipInputStream(new BufferedInputStream(new FileInputStream(artifactFile))));

        getLog().info("Extracting " + artifactFile + " to " + targetWork);
        ZipFileIteratorAndExtractor iterator = new ZipFileIteratorAndExtractor(container, zis, targetWork);
        iterator.extract();

        getLog().info("Retrieving Properties");
        Properties properties = getProperties();

        getLog().info("Processing Files");
        TemplateProcessor processor = new TemplateProcessor(properties, tokenStart, tokenEnd, getLog());
        FileTemplating.processFiles(getLog(), targetWork, processor);

        getLog().info("Compressing to " + finalFile);
        ZipOutputStream zos = closer
                .register(new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(finalFile))));
        ZipFileCompressor compressor = new ZipFileCompressor(container, zos, targetWork);
        compressor.compress(getLog());

        getLog().info("Done.");
    } catch (IOException e) {
        getLog().error(e);
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            throw new MojoExecutionException(e.getMessage(), e);
        }
    }
}

From source file:org.grouplens.lenskit.eval.traintest.TrainTestJob.java

@SuppressWarnings("PMD.AvoidCatchingThrowable")
private void runEvaluation() throws IOException, RecommenderBuildException {
    EventBus bus = task.getProject().getEventBus();
    bus.post(JobEvents.started(this));
    Closer closer = Closer.create();
    try {/*from  www  .  j  a v a  2s.  c  o  m*/
        outputs = task.getOutputs().getPrefixed(algorithmInfo, dataSet);
        TableWriter userResults = outputs.getUserWriter();
        List<Object> outputRow = Lists.newArrayList();

        logger.info("Building {} on {}", algorithmInfo, dataSet);
        StopWatch buildTimer = new StopWatch();
        buildTimer.start();
        buildRecommender();
        buildTimer.stop();
        logger.info("Built {} in {}", algorithmInfo.getName(), buildTimer);

        logger.info("Measuring {} on {}", algorithmInfo.getName(), dataSet.getName());

        StopWatch testTimer = new StopWatch();
        testTimer.start();
        List<Object> userRow = Lists.newArrayList();

        List<MetricWithAccumulator<?>> accumulators = Lists.newArrayList();

        for (Metric<?> eval : outputs.getMetrics()) {
            accumulators.add(makeMetricAccumulator(eval));
        }

        LongSet testUsers = dataSet.getTestData().getUserDAO().getUserIds();
        final NumberFormat pctFormat = NumberFormat.getPercentInstance();
        pctFormat.setMaximumFractionDigits(2);
        pctFormat.setMinimumFractionDigits(2);
        final int nusers = testUsers.size();
        logger.info("Testing {} on {} ({} users)", algorithmInfo, dataSet, nusers);
        int ndone = 0;
        for (LongIterator iter = testUsers.iterator(); iter.hasNext();) {
            if (Thread.interrupted()) {
                throw new InterruptedException("eval job interrupted");
            }
            long uid = iter.nextLong();
            userRow.add(uid);
            userRow.add(null); // placeholder for the per-user time
            assert userRow.size() == 2;

            Stopwatch userTimer = Stopwatch.createStarted();
            TestUser test = getUserResults(uid);

            userRow.add(test.getTrainHistory().size());
            userRow.add(test.getTestHistory().size());

            for (MetricWithAccumulator<?> accum : accumulators) {
                List<Object> ures = accum.measureUser(test);
                if (ures != null) {
                    userRow.addAll(ures);
                }
            }
            userTimer.stop();
            userRow.set(1, userTimer.elapsed(TimeUnit.MILLISECONDS) * 0.001);
            if (userResults != null) {
                try {
                    userResults.writeRow(userRow);
                } catch (IOException e) {
                    throw new RuntimeException("error writing user row", e);
                }
            }
            userRow.clear();

            ndone += 1;
            if (ndone % 100 == 0) {
                testTimer.split();
                double time = testTimer.getSplitTime();
                double tpu = time / ndone;
                double tleft = (nusers - ndone) * tpu;
                logger.info("tested {} of {} users ({}), ETA {}", ndone, nusers,
                        pctFormat.format(((double) ndone) / nusers),
                        DurationFormatUtils.formatDurationHMS((long) tleft));
            }
        }
        testTimer.stop();
        logger.info("Tested {} in {}", algorithmInfo.getName(), testTimer);

        writeMetricValues(buildTimer, testTimer, outputRow, accumulators);
        bus.post(JobEvents.finished(this));
    } catch (Throwable th) {
        bus.post(JobEvents.failed(this, th));
        throw closer.rethrow(th, RecommenderBuildException.class);
    } finally {
        try {
            cleanup();
        } finally {
            outputs = null;
            closer.close();
        }
    }
}

From source file:brooklyn.util.ShellUtils.java

/**
 * Executes the given command./*from  w w w  .j a  va 2s. com*/
 * <p>
 * Uses the given environmnet (inherited if null) and cwd ({@literal .} if null),
 * feeding it the given input stream (if not null) and logging I/O at debug (if not null).
 * <p>
 * flags:  timeout (Duration), 0 for forever; default 60 seconds
 *
 * @throws IllegalStateException if return code non-zero
 * @return lines from stdout.
 */
public static String[] exec(Map flags, final String[] cmd, String[] envp, File dir, String input,
        final Logger log, final Object context) {
    if (log.isDebugEnabled()) {
        log.debug("Running local command: {}% {}", context, Strings.join(cmd, " "));
    }
    Closer closer = Closer.create();
    try {
        final Process proc = Runtime.getRuntime().exec(cmd, envp, dir); // Call *execute* on the string
        ByteArrayOutputStream stdoutB = new ByteArrayOutputStream();
        ByteArrayOutputStream stderrB = new ByteArrayOutputStream();
        PrintStream stdoutP = new GroovyPrintStream(stdoutB);
        PrintStream stderrP = new GroovyPrintStream(stderrB);
        @SuppressWarnings("resource")
        StreamGobbler stdoutG = new StreamGobbler(proc.getInputStream(), stdoutP, log)
                .setLogPrefix("[" + context + ":stdout] ");
        stdoutG.start();
        closer.register(stdoutG);
        @SuppressWarnings("resource")
        StreamGobbler stderrG = new StreamGobbler(proc.getErrorStream(), stderrP, log)
                .setLogPrefix("[" + context + ":stderr] ");
        stderrG.start();
        closer.register(stderrG);
        if (input != null && input.length() > 0) {
            proc.getOutputStream().write(input.getBytes());
            proc.getOutputStream().flush();
        }

        final long timeout = getTimeoutMs(flags);
        final AtomicBoolean ended = new AtomicBoolean(false);
        final AtomicBoolean killed = new AtomicBoolean(false);

        //if a timeout was specified, this thread will kill the process. This is a work around because the process.waitFor'
        //doesn't accept a timeout.
        Thread timeoutThread = new Thread(new Runnable() {
            public void run() {
                if (timeout <= 0)
                    return;
                try {
                    Thread.sleep(timeout);
                    if (!ended.get()) {
                        if (log.isDebugEnabled()) {
                            log.debug("Timeout exceeded for " + context + "% " + Strings.join(cmd, " "));
                        }
                        proc.destroy();
                        killed.set(true);
                    }
                } catch (Exception e) {
                }
            }
        });
        if (timeout > 0)
            timeoutThread.start();
        int exitCode = proc.waitFor();
        ended.set(true);
        if (timeout > 0)
            timeoutThread.interrupt();

        stdoutG.blockUntilFinished();
        stderrG.blockUntilFinished();
        if (exitCode != 0 || killed.get()) {
            String message = killed.get() ? "terminated after timeout" : "exit code " + exitCode;
            if (log.isDebugEnabled()) {
                log.debug("Completed local command (problem, throwing): " + context + "% "
                        + Strings.join(cmd, " ") + " - " + message);
            }
            String e = "Command failed (" + message + "): " + Strings.join(cmd, " ");
            log.warn(e + "\n" + stdoutB + (stderrB.size() > 0 ? "\n--\n" + stderrB : ""));
            throw new IllegalStateException(e + " (details logged)");
        }
        if (log.isDebugEnabled()) {
            log.debug("Completed local command: " + context + "% " + Strings.join(cmd, " ") + " - exit code 0");
        }
        return stdoutB.toString().split("\n");
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    } catch (InterruptedException e) {
        throw Exceptions.propagate(e);
    } finally {
        Streams.closeQuietly(closer);
    }
}

From source file:alluxio.client.file.FileOutStream.java

/**
 * Creates a new file output stream.//from w  w w .  ja v a  2 s .  c o m
 *
 * @param path the file path
 * @param options the client options
 * @param context the file system context
 * @throws IOException if an I/O error occurs
 */
public FileOutStream(AlluxioURI path, OutStreamOptions options, FileSystemContext context) throws IOException {
    mCloser = Closer.create();
    mUri = Preconditions.checkNotNull(path, "path");
    mBlockSize = options.getBlockSizeBytes();
    mAlluxioStorageType = options.getAlluxioStorageType();
    mUnderStorageType = options.getUnderStorageType();
    mOptions = options;
    mContext = context;
    mBlockStore = AlluxioBlockStore.create(mContext);
    mPreviousBlockOutStreams = new LinkedList<>();
    mClosed = false;
    mCanceled = false;
    mShouldCacheCurrentBlock = mAlluxioStorageType.isStore();
    mBytesWritten = 0;

    if (!mUnderStorageType.isSyncPersist()) {
        mUnderStorageOutputStream = null;
    } else { // Write is through to the under storage, create mUnderStorageOutputStream
        try {
            WorkerNetAddress worker = // not storing data to Alluxio, so block size is 0
                    options.getLocationPolicy().getWorkerForNextBlock(mBlockStore.getWorkerInfoList(), 0);
            InetSocketAddress location = new InetSocketAddress(worker.getHost(), worker.getDataPort());
            mUnderStorageOutputStream = mCloser
                    .register(UnderFileSystemFileOutStream.create(mContext, location, mOptions));
        } catch (AlluxioException | IOException e) {
            CommonUtils.closeQuietly(mCloser);
            throw CommonUtils.castToIOException(e);
        }
    }
}

From source file:com.sk89q.worldguard.six2five.util.SwingHelper.java

public static BufferedImage readIconImage(Class<?> clazz, String path) {
    Closer closer = Closer.create();
    try {//from   w  ww .ja v a 2  s.c  o  m
        try {
            InputStream in = closer.register(clazz.getResourceAsStream(path));
            if (in != null) {
                return ImageIO.read(in);
            }
        } finally {
            closer.close();
        }
    } catch (IOException ignored) {
    }

    return null;
}

From source file:ch.ledcom.maven.sitespeed.analyzer.SiteSpeedAnalyzer.java

private File extractYSlow() throws IOException {
    File yslow = File.createTempFile("yslow", ".js");
    Closer closer = Closer.create();
    try {// ww w. j av  a  2 s . co m

        InputStream in = this.getClass().getClassLoader().getResourceAsStream(YSLOW);
        OutputStream out = new FileOutputStream(yslow);
        closer.register(in);
        closer.register(out);
        IOUtils.copy(in, out);
    } catch (Throwable t) {
        closer.rethrow(t);
    } finally {
        closer.close();
    }
    yslow.deleteOnExit();
    return yslow;
}

From source file:org.apache.gobblin.metrics.reporter.EventReporter.java

public EventReporter(Builder builder) {
    super(builder.context, builder.name, builder.filter, builder.rateUnit, builder.durationUnit);

    this.closer = Closer.create();
    this.immediateReportExecutor = MoreExecutors
            .getExitingExecutorService(/*from  w w  w . j a va  2s.  c om*/
                    (ThreadPoolExecutor) Executors.newFixedThreadPool(1,
                            ExecutorsUtils.newThreadFactory(Optional.of(LOGGER),
                                    Optional.of("EventReporter-" + builder.name + "-%d"))),
                    5, TimeUnit.MINUTES);

    this.metricContext = builder.context;
    this.notificationTargetKey = builder.context.addNotificationTarget(new Function<Notification, Void>() {
        @Nullable
        @Override
        public Void apply(Notification notification) {
            notificationCallback(notification);
            return null;
        }
    });
    this.reportingQueue = Queues.newLinkedBlockingQueue(QUEUE_CAPACITY);
}

From source file:eu.interedition.text.index.IndexServiceBase.java

@Override
protected void startUp() throws Exception {
    if (LOG.isLoggable(Level.INFO)) {
        LOG.log(Level.INFO, "Starting {0}", getClass().getName());
    }//from  ww  w  . ja  v a 2  s. c o  m
    final Closer closer = Closer.create();
    try {
        closer.register(writer()).commit();
    } finally {
        closer.close();
    }
}

From source file:com.android.builder.compiling.BuildConfigGenerator.java

/**
 * Generates the BuildConfig class.//from   w  w  w .  ja v  a  2 s .c  o m
 */
public void generate() throws IOException {
    File pkgFolder = getFolderPath();
    if (!pkgFolder.isDirectory()) {
        if (!pkgFolder.mkdirs()) {
            throw new RuntimeException("Failed to create " + pkgFolder.getAbsolutePath());
        }
    }

    File buildConfigJava = new File(pkgFolder, BUILD_CONFIG_NAME);

    Closer closer = Closer.create();
    try {
        FileOutputStream fos = closer.register(new FileOutputStream(buildConfigJava));
        OutputStreamWriter out = closer.register(new OutputStreamWriter(fos, Charsets.UTF_8));
        JavaWriter writer = closer.register(new JavaWriter(out));

        writer.emitJavadoc("Automatically generated file. DO NOT MODIFY").emitPackage(mBuildConfigPackageName)
                .beginType("BuildConfig", "class", PUBLIC_FINAL);

        for (ClassField field : mFields) {
            emitClassField(writer, field);
        }

        for (Object item : mItems) {
            if (item instanceof ClassField) {
                emitClassField(writer, (ClassField) item);
            } else if (item instanceof String) {
                writer.emitSingleLineComment((String) item);
            }
        }

        writer.endType();
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}