Example usage for com.google.common.io Closeables closeQuietly

List of usage examples for com.google.common.io Closeables closeQuietly

Introduction

In this page you can find the example usage for com.google.common.io Closeables closeQuietly.

Prototype

public static void closeQuietly(@Nullable Reader reader) 

Source Link

Document

Closes the given Reader , logging any IOException that's thrown rather than propagating it.

Usage

From source file:co.cask.cdap.logging.gateway.handlers.AbstractChunkedCallback.java

@Override
public void close() {
    // If closed already, then return
    if (!closed.compareAndSet(false, true)) {
        return;/*from   w w  w.j a v  a 2s.com*/
    }

    try {
        // Write the last chunk
        writeFinal();
        // Flush the encoder
        CoderResult coderResult;
        do {
            coderResult = charsetEncoder.flush(chunkBuffer);
            chunkBuffer.flip();
            chunkResponder.sendChunk(ChannelBuffers.copiedBuffer(chunkBuffer));
            chunkBuffer.clear();
        } while (coderResult.isOverflow());
    } catch (IOException e) {
        // If cannot send chunks, nothing can be done (since the client closed connection).
        // Just log the error as debug.
        LOG.debug("Failed to send chunk", e);
    } finally {
        Closeables.closeQuietly(chunkResponder);
    }
}

From source file:org.kitesdk.apps.cli.commands.InstallCommand.java

/**
 * Returns a complete properties file with contents to be used for the
 * application properties, or null if no properties are set.
 *//*from   w  w  w.  j  a v  a2 s  .  c  o  m*/
private File completePropertiesFile() throws IOException {
    File settingsFile = propertiesFileName != null ? new File(propertiesFileName) : null;

    // No explicit settings, so just use the original file.
    if (settings == null || settings.size() == 0) {

        return settingsFile;
    }

    // We append the specified settings to the properties file
    // so any comments or formatting are preserved.
    File appendedFile = File.createTempFile("kite", "props");

    appendedFile.deleteOnExit();

    FileOutputStream stream = new FileOutputStream(appendedFile);
    OutputStreamWriter streamWriter = new OutputStreamWriter(stream, Charsets.UTF_8);
    BufferedWriter writer = new BufferedWriter(streamWriter);

    try {
        if (settingsFile != null) {

            Files.copy(settingsFile, stream);
            writer.newLine();
        }

        for (String setting : settings) {

            // Validate the setting.
            String[] parts = setting.split("=");

            if (parts.length != 2)
                throw new IllegalArgumentException("Malformed input setting: " + setting);

            writer.append(setting);
            writer.newLine();
        }

    } finally {
        Closeables.closeQuietly(writer);
    }

    return appendedFile;
}

From source file:org.sonar.plugins.checkstyle.CheckstyleExecutor.java

/**
 * Execute Checkstyle and return the generated XML report.
 *//*  w  ww.  j  av  a 2  s  . co  m*/
public void execute() {
    TimeProfiler profiler = new TimeProfiler().start("Execute Checkstyle " + CheckstyleVersion.getVersion());
    ClassLoader initialClassLoader = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(PackageNamesLoader.class.getClassLoader());
    URLClassLoader projectClassloader = createClassloader();

    Locale initialLocale = Locale.getDefault();
    Locale.setDefault(Locale.ENGLISH);
    Checker checker = new Checker();
    OutputStream xmlOutput = null;
    try {
        checker.setClassLoader(projectClassloader);
        checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());
        checker.addListener(listener);

        File xmlReport = configuration.getTargetXMLReport();
        if (xmlReport != null) {
            LOG.info("Checkstyle output report: " + xmlReport.getAbsolutePath());
            xmlOutput = FileUtils.openOutputStream(xmlReport);
            checker.addListener(new XMLLogger(xmlOutput, true));
        }

        checker.setCharset(configuration.getCharset().name());
        checker.configure(configuration.getCheckstyleConfiguration());
        checker.process(configuration.getSourceFiles());

        profiler.stop();

    } catch (Exception e) {
        throw new IllegalStateException("Can not execute Checkstyle", e);
    } finally {
        checker.destroy();
        Closeables.closeQuietly(xmlOutput);
        Thread.currentThread().setContextClassLoader(initialClassLoader);
        Locale.setDefault(initialLocale);
        Closeables.closeQuietly(projectClassloader);
    }
}

From source file:org.apache.s4.base.util.S4RLoaderFactory.java

/**
 * Explodes the s4r archive in a subdirectory of a user specified directory through "s4.tmp.dir" parameter, and
 * prepares a classloader that will load classes and resources from, first, the application classes, then the
 * dependencies.//  w w w. ja  v a2 s.  c  o  m
 * 
 * Uses a temporary directory if s4.tmp.dir is not provided.
 * 
 * Inspired from Hadoop's application classloading implementation (RunJar class).
 * 
 * @param s4rPath
 *            path to s4r
 * @return classloader that loads resources from the s4r in a predefined order
 */
public S4RLoader createS4RLoader(String s4rPath) {
    File s4rDir = null;
    if (tmpDir == null) {
        s4rDir = Files.createTempDir();
        s4rDir.deleteOnExit();
        logger.warn(
                "s4.tmp.dir not specified, using temporary directory [{}] for unpacking S4R. You may want to specify a parent non-temporary directory.",
                s4rDir.getAbsolutePath());
    } else {
        s4rDir = new File(tmpDir,
                s4rPath.substring(s4rPath.lastIndexOf(File.separator)) + "-" + System.currentTimeMillis());
        if (!s4rDir.mkdir()) {
            throw new RuntimeException("Cannot create directory for unzipping S4R file in ["
                    + s4rDir.getAbsolutePath() + "]. Aborting deployment.");
        }
    }
    logger.info("Unzipping S4R archive in [{}]", s4rDir.getAbsolutePath());

    JarFile jar = null;
    try {
        jar = new JarFile(s4rPath);
        Enumeration<JarEntry> entries = jar.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                File to = new File(s4rDir, entry.getName());
                Files.createParentDirs(to);
                InputStream is = jar.getInputStream(entry);
                OutputStream os = new FileOutputStream(to);
                try {
                    ByteStreams.copy(is, os);
                } finally {
                    Closeables.closeQuietly(is);
                    Closeables.closeQuietly(os);
                }
            }
        }

        List<URL> classpath = new ArrayList<URL>();
        addDirLibsToClassPath(classpath, s4rDir, "/app");
        addDirLibsToClassPath(classpath, s4rDir, "/lib");

        S4RLoader s4rLoader = new S4RLoader(classpath.toArray(new URL[] {}));
        return s4rLoader;

    } catch (IOException e) {
        logger.error("Cannot process S4R [{}]: {}", s4rPath, e.getClass().getName() + "/" + e.getMessage());
        throw new RuntimeException("Cannot create S4R classloader", e);
    }
}

From source file:com.proofpoint.event.monitor.s3.S3EventStore.java

@Override
public boolean recentEventExists(String eventType, EventPredicate filter, DateTime limit) {
    for (URI dateBaseUri : storageSystem
            .listDirectoriesNewestFirst(buildS3Directory(eventStagingLocation, eventType))) {
        DateTime dateBucket = DATE_FORMAT.parseDateTime(getS3FileName(dateBaseUri));
        for (URI hourBaseUri : storageSystem.listDirectoriesNewestFirst(dateBaseUri)) {
            int hour = Integer.parseInt(getS3FileName(hourBaseUri));
            // The bucket may contain events up to the start of the following hour
            DateTime bucketDateTime = dateBucket.hourOfDay().setCopy(hour).plusHours(1);

            if (bucketDateTime.isBefore(limit)) {
                return false;
            }//from   w  w w .j  a  v a  2 s .  c om

            for (URI eventFile : storageSystem.listObjects(hourBaseUri)) {
                InputStream s3Object = null;
                try {
                    s3Object = storageSystem.getInputSupplier(eventFile).getInput();
                    Iterator<Event> eventIterator = getEventIterator(s3Object, objectMapper);
                    while (eventIterator.hasNext()) {
                        Event event = eventIterator.next();
                        if (filter.apply(event) && event.getTimestamp().isAfter(limit)) {
                            return true;
                        }
                    }
                } catch (IOException e) {
                    log.warn(e, "Exception while checking S3 object %s for recent event of type %s (filter %s)",
                            eventFile, eventType, filter);
                } finally {
                    Closeables.closeQuietly(s3Object);
                }
            }
        }
    }
    return false;
}

From source file:org.kitesdk.apps.spark.spi.streaming.SparkStreamingJobManager.java

private static void writeDescription(FileSystem fs, Path appRoot, StreamDescription description) {

    Path streamingJobPath = jobDescriptionFile(appRoot, description.getJobName());

    try {/*w w  w.java  2 s  .co m*/
        fs.mkdirs(streamingJobPath.getParent());
    } catch (IOException e) {
        throw new AppException(e);
    }

    OutputStream output = null;

    try {
        output = fs.append(streamingJobPath);
        OutputStreamWriter writer = new OutputStreamWriter(output);
        writer.write(description.toString());

    } catch (IOException e) {
        throw new AppException(e);
    } finally {
        Closeables.closeQuietly(output);
    }
}

From source file:edu.cmu.lti.oaqa.framework.collection.AbstractCollectionReaderProducer.java

@Override
public void close() throws IOException {
    persistence.updateExperimentMeta(getUUID(), count, topics);
    Closeables.closeQuietly(producer);
}

From source file:org.apache.drill.exec.service.ServiceEngine.java

@Override
public void close() throws IOException {
    Closeables.closeQuietly(userServer);
    Closeables.closeQuietly(dataPool);
    Closeables.closeQuietly(controller);
}

From source file:interactivespaces.resource.repository.internal.SimpleActivityRepositoryManager.java

@Override
public Activity addActivity(InputStream activityStream) {
    String stageHandle = repositoryStorageManager.stageResource(activityStream);
    InputStream activityDescriptionStream = null;
    try {/*  w  w w.  j  a  v a2  s  .co m*/
        activityDescriptionStream = repositoryStorageManager.getStagedResourceDescription("activity.xml",
                stageHandle);
        ActivityDescriptionReader reader = new JdomActivityDescriptionReader();
        ActivityDescription activityDescription = reader.readDescription(activityDescriptionStream);

        repositoryStorageManager.commitResource(ResourceRepositoryStorageManager.RESOURCE_CATEGORY_ACTIVITY,
                activityDescription.getIdentifyingName(),
                Version.parseVersion(activityDescription.getVersion()), stageHandle);

        // TODO(keith): Might want to edit what it gives to the import so
        // this may need to move.
        Activity finalActivity = activityRepository.getActivityByNameAndVersion(
                activityDescription.getIdentifyingName(), activityDescription.getVersion());
        if (finalActivity == null) {
            finalActivity = activityRepository.newActivity();
            finalActivity.setIdentifyingName(activityDescription.getIdentifyingName());
            finalActivity.setVersion(activityDescription.getVersion());
        }

        ActivityUtils.copy(activityDescription, finalActivity);

        // TODO(peringknife): Use appropriate TimeProvider for this.
        finalActivity.setLastUploadDate(new Date());

        copyDependencies(activityDescription, finalActivity);

        calculateBundleContentHash(finalActivity);

        activityRepository.saveActivity(finalActivity);

        return finalActivity;
    } finally {
        Closeables.closeQuietly(activityDescriptionStream);
        repositoryStorageManager.removeStagedReource(stageHandle);
    }

}

From source file:org.apache.drill.exec.rpc.control.ControlConnection.java

public void shutdownIfClient() {
    if (bus.isClient()) {
        Closeables.closeQuietly(bus);
    }
}