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

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

Introduction

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

Prototype

public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException 

Source Link

Document

Closes a Closeable , with control over whether an IOException may be thrown.

Usage

From source file:com.cloudera.data.filesystem.FileSystemDatasetWriter.java

@Override
public void close() throws IOException {
    if (state.equals(ReaderWriterState.OPEN)) {
        logger.debug("Closing pathTmp:{}", pathTmp);

        Closeables.close(dataFileWriter, false);

        logger.debug("Committing pathTmp:{} to path:{}", pathTmp, path);

        if (!fileSystem.rename(pathTmp, path)) {
            throw new IOException("Failed to move " + pathTmp + " to " + path);
        }//  w w w. j a  v a2 s. co m

        state = ReaderWriterState.CLOSED;
    }
}

From source file:org.jclouds.examples.rackspace.cloudnetworks.CreateSecurityGroup.java

/**
 * Always close your service when you're done with it.
 *
 * Note that closing quietly like this is not necessary in Java 7.
 * You would use try-with-resources in the main method instead.
 *///from   www  . ja  va  2 s.co  m
public void close() throws IOException {
    Closeables.close(neutronApi, true);
}

From source file:com.netflix.client.testutil.SimpleSSLTestServer.java

public void accept() throws Exception {

    new Thread() {

        @Override/*from w  w w  .j  a  v a 2s .c o  m*/
        public void run() {

            Socket sock = null;
            BufferedReader reader = null;
            BufferedWriter writer = null;

            try {
                sock = ss.accept();

                reader = new BufferedReader(
                        new InputStreamReader(sock.getInputStream(), Charset.defaultCharset()));
                writer = new BufferedWriter(
                        new OutputStreamWriter(sock.getOutputStream(), Charset.defaultCharset()));

                reader.readLine(); // we really don't care what the client says, he's getting the special regardless...

                writer.write(CANNED_RESPONSE);
                writer.flush();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    Closeables.close(reader, true);
                    Closeables.close(writer, true);
                    sock.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }.start();
}

From source file:eu.interedition.image.ImageFile.java

public void write(RenderedImage image) throws IOException {
    OutputStream stream = null;//  w ww. ja v  a 2 s .co  m
    try {
        write(image, format, stream = new BufferedOutputStream(new FileOutputStream(file)));
    } finally {
        Closeables.close(stream, false);
    }
}

From source file:com.simpligility.maven.plugins.android.DefaultJavaProcessExecutor.java

/**
 * Get the stderr/stdout outputs of a process and return when the process is done.
 * Both <b>must</b> be read or the process will block on windows.
 *
 * @param process The process to get the output from.
 * @param output The processOutput containing where to send the output.
 *      Note that on Windows capturing the output is not optional. If output is null
 *      the stdout/stderr will be captured and discarded.
 * @return the process return code.//from w w w . j  av a2 s . c  o m
 * @throws InterruptedException if {@link Process#waitFor()} was interrupted.
 */
private static int grabProcessOutput(@NonNull final Process process, @NonNull final ProcessOutput output)
        throws InterruptedException {
    Thread threadErr = new Thread("stderr") {
        @Override
        public void run() {
            InputStream stderr = process.getErrorStream();
            OutputStream stream = output.getErrorOutput();
            try {
                ByteStreams.copy(stderr, stream);
                stream.flush();
            } catch (IOException e) {
                // ignore?
            } finally {
                try {
                    Closeables.close(stderr, true /* swallowIOException */ );
                } catch (IOException e) {
                    // cannot happen
                }
                try {
                    Closeables.close(stream, true /* swallowIOException */ );
                } catch (IOException e) {
                    // cannot happen
                }
            }
        }
    };
    Thread threadOut = new Thread("stdout") {
        @Override
        public void run() {
            InputStream stdout = process.getInputStream();
            OutputStream stream = output.getStandardOutput();
            try {
                ByteStreams.copy(stdout, stream);
                stream.flush();
            } catch (IOException e) {
                // ignore?
            } finally {
                try {
                    Closeables.close(stdout, true /* swallowIOException */ );
                } catch (IOException e) {
                    // cannot happen
                }
                try {
                    Closeables.close(stream, true /* swallowIOException */ );
                } catch (IOException e) {
                    // cannot happen
                }
            }
        }
    };
    threadErr.start();
    threadOut.start();
    // it looks like on windows process#waitFor() can return
    // before the thread have filled the arrays, so we wait for both threads and the
    // process itself.
    threadErr.join();
    threadOut.join();
    // get the return code from the process
    return process.waitFor();
}

From source file:org.plista.kornakapi.core.training.LDATopicFactorizer.java

/**
 * //  ww  w .jav a  2s.c  om
 * @throws IOException
 */
private void indexItem() throws IOException {
    if (indexItem == null) {
        indexItem = new HashMap<Integer, String>();
        itemIndex = new HashMap<String, Integer>();
        Reader reader = new SequenceFile.Reader(fs, new Path(this.conf.getCVBInputPath() + "/docIndex"), lconf);
        IntWritable key = new IntWritable();
        Text newVal = new Text();
        while (reader.next(key, newVal)) {
            indexItem.put(key.get(), newVal.toString().substring(1));
            itemIndex.put(newVal.toString().substring(1), key.get());
        }
        Closeables.close(reader, false);
    }
}

From source file:sonia.legman.maven.GuavaMigrationMojo.java

/**
 * Method description/*from  w  ww  . j ava2 s . co m*/
 *
 *
 * @param file
 *
 * @throws IOException
 */
void processClassFile(File file) throws IOException {
    InputStream stream = null;

    try {
        stream = new FileInputStream(file);

        ClassReader reader = new ClassReader(stream);

        Builder builder = MethodAnnotationClassVisitor.builder();

        builder.api(Opcodes.ASM4);
        builder.annotateClasses(Subscribe.class, AllowConcurrentEvents.class);
        builder.methodAnnotationHandler(new MethodAnnotationHandler() {

            @Override
            public void handleMethodAnnotation(String className, String methodName, String annotationName) {
                //J-
                String message = template.replace("{class}", className).replace("{method}", methodName)
                        .replace("{annotation}", annotationName)
                        .replace("{subscribe}", com.github.legman.Subscribe.class.getName());
                //J+ 

                getLog().warn(message);
            }
        });

        reader.accept(builder.build(), 0);
    } finally {
        Closeables.close(stream, true);
    }
}

From source file:guipart.view.Utils.java

static void rfTestFile(Path inPath, Path outPath, DataConverter converter, DecisionForest forest,
        Dataset dataset, Collection<double[]> results, Random rng, FileSystem outFS, FileSystem dataFS,
        GUIPart guiPart) throws IOException {
    // create the predictions file
    FSDataOutputStream ofile = null;/*from w  w  w . j  a v  a 2 s. co  m*/
    String gender;

    if (outPath != null) {
        ofile = outFS.create(outPath);
    }

    FSDataInputStream input = dataFS.open(inPath);
    try {
        Scanner scanner = new Scanner(input, "UTF-8");

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            if (line.isEmpty()) {
                continue; // skip empty lines
            }
            System.out.println(line);

            String[] split = line.split(",");

            if (split[1].contentEquals("1"))
                gender = "male";
            else
                gender = "female";

            Instance instance = converter.convert(line);

            double prediction = forest.classify(dataset, rng, instance);

            boolean booltemp = prediction != 0;

            System.out.println("Preditction: " + prediction);

            if (ofile != null) {
                ofile.writeChars(Double.toString(prediction)); // write the prediction
                ofile.writeChar('\n');
            }

            Person temp = new Person(Integer.parseInt(split[0]), Integer.parseInt(split[4]),
                    Integer.parseInt(split[7]), booltemp, gender, Integer.parseInt(split[5]),
                    Integer.parseInt(split[6]), Integer.parseInt(split[3]));

            guiPart.addPerson(temp);

            results.add(new double[] { dataset.getLabel(instance), prediction });
        }

        scanner.close();
    } finally {
        Closeables.close(input, true);
    }
}

From source file:org.jclouds.cloudsigma2.handlers.CloudSigmaErrorHandler.java

public void handleError(HttpCommand command, HttpResponse response) {
    // it is important to always read fully and close streams
    String message = parseMessage(response);
    Exception exception = message != null ? new HttpResponseException(command, response, message)
            : new HttpResponseException(command, response);
    try {/*from w  w  w .j  a v  a 2  s.  c om*/
        message = message != null ? message
                : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(),
                        response.getStatusLine());
        switch (response.getStatusCode()) {
        case 400:
            if ((command.getCurrentRequest().getEndpoint().getPath().endsWith("/info"))
                    || (message != null && message.indexOf("could not be found") != -1))
                exception = new ResourceNotFoundException(message, exception);
            else if (message != null && message.indexOf("currently in use") != -1)
                exception = new IllegalStateException(message, exception);
            else
                exception = new IllegalArgumentException(message, exception);
            break;
        case 401:
            exception = new AuthorizationException(message, exception);
            break;
        case 402:
            exception = new IllegalStateException(message, exception);
            break;
        case 404:
            if (!command.getCurrentRequest().getMethod().equals("DELETE")) {
                exception = new ResourceNotFoundException(message, exception);
            }
            break;
        case 405:
            exception = new IllegalArgumentException(message, exception);
            break;
        case 409:
            exception = new IllegalStateException(message, exception);
            break;
        }
    } finally {
        try {
            Closeables.close(response.getPayload(), true);
        } catch (IOException e) {
            // This code will never be reached
            throw Throwables.propagate(e);
        }
        command.setException(exception);
    }
}

From source file:com.google.dart.compiler.backend.dart.DartBackend.java

@Override
public void packageApp(LibrarySource app, Collection<LibraryUnit> libraries, DartCompilerContext context,
        CoreTypeProvider typeProvider) throws IOException {
    Writer out = context.getArtifactWriter(app, "", EXTENSION_DART);
    boolean failed = true;
    try {//  w  ww.j a  va2  s.  co m
        // Emit the concatenated Javascript sources in dependency order.
        packageLibs(libraries, out, context);

        // Emit entry point call.
        // TODO: How does a dart app start?
        // out.write(app.getEntryMethod() + "();");
        failed = false;
    } finally {
        Closeables.close(out, failed);
    }
}