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

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

Introduction

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

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes all Closeable instances that have been added to this Closer .

Usage

From source file:gobblin.runtime.Task.java

private void publishTaskData() throws IOException {
    Closer closer = Closer.create();
    try {//w  ww.  j  a v  a2  s  . com
        Class<? extends DataPublisher> dataPublisherClass = getTaskPublisherClass();
        SingleTaskDataPublisher publisher = closer
                .register(SingleTaskDataPublisher.getInstance(dataPublisherClass, this.taskState));

        LOG.info("Publishing data from task " + this.taskId);
        publisher.publish(this.taskState);
    } catch (ClassCastException e) {
        LOG.error(String.format("To publish data in task, the publisher class must extend %s",
                SingleTaskDataPublisher.class.getSimpleName()), e);
        this.taskState.setTaskFailureException(e);
        throw closer.rethrow(e);
    } catch (Throwable t) {
        this.taskState.setTaskFailureException(t);
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:io.macgyver.core.script.ScriptExecutor.java

public Object run(Resource f, Map<String, Object> vars, boolean failIfNotFound) {

    Closer closer = Closer.create();
    Object rval = null;/* ww w. jav a2  s.c o  m*/
    try {

        logger.debug("script {}", f);
        if (!f.exists() && !failIfNotFound) {
            logger.info("init script not found: {}", f);
            return null;
        }
        ScriptEngine engine = null;

        if (!scriptEngineManagerCachingEnabled) {
            ScriptEngineManager factory = new ScriptEngineManager();
            engine = factory.getEngineByExtension(getExtension(f));
        } else {
            engine = getEngineByExtensionFromCache(getExtension(f));
        }

        if (engine == null) {
            throw new ScriptExecutionException(
                    "could not create ScriptEngine for extension: " + getExtension(f));
        }

        Reader fr = new InputStreamReader(f.openInputStream());
        closer.register(fr);

        if (vars != null) {
            bindings.putAll(vars);
        }

        collectBindings(bindings, Optional.fromNullable(engine.getFactory().getLanguageName()));

        rval = engine.eval(fr, bindings);

        fr.close();

    } catch (ScriptExecutionException e) {
        throw e;

    } catch (ScriptException e) {
        throw new ScriptExecutionException(e);
    } catch (IOException e) {
        throw new ScriptExecutionException(e);
    } catch (RuntimeException e) {
        throw new ScriptExecutionException(e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            logger.warn("problem closing reader", e);
        }

    }
    return rval;

}

From source file:org.basepom.mojo.duplicatefinder.classpath.ClasspathDescriptor.java

private void addArchive(final ClasspathCacheElement.Builder cacheBuilder, final File element)
        throws IOException {
    final Closer closer = Closer.create();

    try {//  w  w w  .  j a  v a  2 s . c  om
        final InputStream input = closer.register(element.toURI().toURL().openStream());
        final ZipInputStream zipInput = closer.register(new ZipInputStream(input));

        ZipEntry entry;

        while ((entry = zipInput.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                final String name = entry.getName();
                if ("class".equals(Files.getFileExtension(name))) {
                    final List<String> nameElements = Splitter.on("/").splitToList(name); // ZIP/Jars always use "/" as separators
                    if (nameElements.isEmpty()) {
                        LOG.warn("ZIP entry '%s' split into empty list!", entry);
                    } else {
                        final PackageNameHolder packageName = new PackageNameHolder(
                                nameElements.subList(0, nameElements.size() - 1));
                        final String className = packageName
                                .getQualifiedName(Files.getNameWithoutExtension(name));
                        cacheBuilder.addClass(className);
                    }
                } else {
                    final String resourcePath = name.replace('\\', File.separatorChar);
                    cacheBuilder.addResource(resourcePath);
                }
            }
        }
    } finally {
        closer.close();
    }
}

From source file:com.facebook.buck.android.exopackage.RealAndroidDevice.java

private void doMultiInstall(String filesType, Map<Path, Path> installPaths) throws Exception {
    Closer closer = Closer.create();
    BuckInitiatedInstallReceiver receiver = new BuckInitiatedInstallReceiver(closer, filesType, installPaths);

    String command = "umask 022 && " + agent.get().getAgentCommand() + "multi-receive-file " + "-" + " "
            + agentPort + " " + "1" + ECHO_COMMAND_SUFFIX;
    LOG.debug("Executing %s", command);

    // If we fail to execute the command, stash the exception.  My experience during development
    // has been that the exception from checkReceiverOutput is more actionable.
    Exception shellException = null;
    try {// w ww  . ja  v a2 s  . co m
        device.executeShellCommand(command, receiver);
    } catch (Exception e) {
        shellException = e;
    }

    // Close the client socket, if we opened it.
    closer.close();

    if (receiver.getError().isPresent()) {
        Exception prev = shellException;
        shellException = receiver.getError().get();
        if (prev != null) {
            shellException.addSuppressed(prev);
        }
    }

    try {
        checkReceiverOutput(command, receiver);
    } catch (Exception e) {
        if (shellException != null) {
            e.addSuppressed(shellException);
        }
        throw e;
    }

    if (shellException != null) {
        throw shellException;
    }

    for (Path targetFileName : installPaths.keySet()) {
        chmod644(targetFileName);
    }
}

From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java

@Override
public void destroyNode(String vmName) {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstance.get();
    closer.register(instance);//w ww.  j  a v a2  s  . co  m
    try {
        try {
            VirtualMachine virtualMachine = getVM(vmName, instance.getInstance().getRootFolder());
            Task powerOffTask = virtualMachine.powerOffVM_Task();
            if (powerOffTask.waitForTask().equals(Task.SUCCESS))
                logger.debug(String.format("VM %s powered off", vmName));
            else
                logger.debug(String.format("VM %s could not be powered off", vmName));

            Task destroyTask = virtualMachine.destroy_Task();
            if (destroyTask.waitForTask().equals(Task.SUCCESS))
                logger.debug(String.format("VM %s destroyed", vmName));
            else
                logger.debug(String.format("VM %s could not be destroyed", vmName));
        } catch (Exception e) {
            logger.error("Can't destroy vm " + vmName, e);
            throw closer.rethrow(e);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        logger.trace(e.getMessage(), e);
    }

}

From source file:org.apache.gobblin.runtime.mapreduce.MRJobLauncher.java

/**
 * Prepare the job input.//  w w  w.  ja v a 2s  .c o  m
 * @throws IOException
 */
private void prepareJobInput(List<WorkUnit> workUnits) throws IOException {
    Closer closer = Closer.create();
    try {
        ParallelRunner parallelRunner = closer
                .register(new ParallelRunner(this.parallelRunnerThreads, this.fs));

        int multiTaskIdSequence = 0;
        // Serialize each work unit into a file named after the task ID
        for (WorkUnit workUnit : workUnits) {

            String workUnitFileName;
            if (workUnit instanceof MultiWorkUnit) {
                workUnitFileName = JobLauncherUtils.newMultiTaskId(this.jobContext.getJobId(),
                        multiTaskIdSequence++) + MULTI_WORK_UNIT_FILE_EXTENSION;
            } else {
                workUnitFileName = workUnit.getProp(ConfigurationKeys.TASK_ID_KEY) + WORK_UNIT_FILE_EXTENSION;
            }
            Path workUnitFile = new Path(this.jobInputPath, workUnitFileName);
            LOG.debug("Writing work unit file " + workUnitFileName);

            parallelRunner.serializeToFile(workUnit, workUnitFile);

            // Append the work unit file path to the job input file
        }
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:org.ow2.proactive.scheduler.rest.SchedulerClient.java

@Override
public void renewSession() throws NotConnectedException {
    Closer closer = Closer.create();
    try {/*from w  w  w . j a v  a2s  . c om*/
        LoginForm loginForm = new LoginForm();
        loginForm.setUsername(connectionInfo.getLogin());
        loginForm.setPassword(connectionInfo.getPassword());
        if (connectionInfo.getCredentialFile() != null) {
            FileInputStream inputStream = new FileInputStream(connectionInfo.getCredentialFile());
            closer.register(inputStream);
            loginForm.setCredential(inputStream);
        }
        sid = restApi().loginOrRenewSession(sid, loginForm);

    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
            // ignore
        }
    }
}

From source file:org.pantsbuild.tools.jar.JarBuilder.java

/**
 * As an optimization, use {@link JarEntryCopier} to copy one jar file to
 * another without decompressing and recompressing.
 *
 * @param writer target to copy JAR file entries to.
 * @param entries entries that came from a jar file
 *///from ww w  .j  a  v a2 s .com
private void copyJarFiles(JarWriter writer, Iterable<ReadableJarEntry> entries) throws IOException {
    // Walk the entries to bucketize by input jar file names
    Multimap<JarSource, ReadableJarEntry> jarEntries = HashMultimap.create();
    for (ReadableJarEntry entry : entries) {
        Preconditions.checkState(entry.getSource() instanceof JarSource);
        jarEntries.put((JarSource) entry.getSource(), entry);
    }

    // Copy the data from each jar input file to the output
    for (JarSource source : jarEntries.keySet()) {
        Closer jarFileCloser = Closer.create();
        try {
            final InputSupplier<JarFile> jarSupplier = jarFileCloser
                    .register(new JarSupplier(new File(source.name())));
            JarFile jarFile = jarSupplier.getInput();
            for (ReadableJarEntry readableJarEntry : jarEntries.get(source)) {
                JarEntry jarEntry = readableJarEntry.getJarEntry();
                String resource = jarEntry.getName();
                writer.copy(resource, jarFile, jarEntry);
            }
        } catch (IOException ex) {
            throw jarFileCloser.rethrow(ex);
        } finally {
            jarFileCloser.close();
        }
    }
}

From source file:com.pants.examples.annotation.processor.ExampleProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }//from   w w w.j a va  2s  .  co m

    FileObject outputFile = createResource("" /* no package */, EXAMPLES_FILE_NAME);
    if (outputFile != null) {
        Closer closer = Closer.create();
        try {
            PrintWriter writer = closer.register(new PrintWriter(outputFile.openWriter()));
            writer.println("{");
            for (TypeElement appAnnotation : annotations) {
                Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(appAnnotation);
                Set<TypeElement> exampleElements = ElementFilter.typesIn(annotatedElements);
                for (Element elem : exampleElements) {
                    String typeName = elem.getSimpleName().toString();
                    for (AnnotationMirror mirror : elem.getAnnotationMirrors()) {
                        String n = ((TypeElement) mirror.getAnnotationType().asElement()).getQualifiedName()
                                .toString();
                        if (Example.class.getCanonicalName().equals(n)) {
                            Map<? extends ExecutableElement, ? extends AnnotationValue> values = mirror
                                    .getElementValues();
                            for (ExecutableElement key : values.keySet()) {
                                if ("value".equals(key.getSimpleName().toString())) {
                                    String exampleValue = (String) values.get(key).getValue();
                                    if (exampleValue != null) {
                                        writer.println("  {'type' : '" + typeName + "', 'value': '"
                                                + exampleValue + "'},");
                                    }
                                }
                            }
                        }
                    }
                }
                writer.println("}\n");
            }
            closer.close();
            log(Diagnostic.Kind.NOTE, "Generated resource '%s'", outputFile.toUri());
        } catch (IOException e) {
            error("Couldn't write to '%s': %s", outputFile.toUri(), e);
        }
    }
    return true;
}

From source file:com.adobe.epubcheck.xml.XMLParser.java

public void process() {
    try {//w w  w  .  ja va2  s . co m
        Closer closer = Closer.create();
        try {
            InputStream in = closer.register(context.resourceProvider.getInputStream(path));
            // System.err.println("DEBUG XMLParser#process on" + resource);
            if (!in.markSupported()) {
                in = new BufferedInputStream(in);
            }

            String encoding = sniffEncoding(in);
            if (encoding != null && !encoding.equals("UTF-8") && !encoding.equals("UTF-16")) {
                report.message(MessageId.CSS_003, EPUBLocation.create(path, ""), encoding);
            }

            InputSource ins = new InputSource(in);
            ins.setSystemId(zipRoot + path);
            parser.parse(ins, this);

        } catch (Throwable e) {
            // ensure that any checked exception types other than IOException that
            // could be thrown are
            // provided here, e.g. throw closer.rethrow(e,
            // CheckedException.class);
            // throw closer.rethrow(e);
            throw closer.rethrow(e, SAXException.class);
        } finally {
            closer.close();
        }
    } catch (FileNotFoundException e) {
        String message = e.getMessage();
        message = new File(message).getName();
        int p = message.indexOf("(");
        if (p > 0) {
            message = message.substring(0, message.indexOf("("));
        }
        message = message.trim();
        report.message(MessageId.RSC_001, EPUBLocation.create(path), message);
    } catch (IOException e) {
        report.message(MessageId.PKG_008, EPUBLocation.create(path), path);
    } catch (IllegalArgumentException e) {
        report.message(MessageId.RSC_005, EPUBLocation.create(path), e.getMessage());
    } catch (SAXException e) {
        report.message(MessageId.RSC_005, EPUBLocation.create(path), e.getMessage());
    }
}