List of usage examples for com.google.common.io Closeables close
public static void close(@Nullable Closeable closeable, boolean swallowIOException) throws IOException
From source file:com.google.dart.tools.debug.core.util.DebuggerUtils.java
public static String extractFileLine(InputStream contents, String charset, int lineNumber) { if (contents == null) { return null; }//w ww. j a v a2 s .c om try { Reader r = charset != null ? new InputStreamReader(contents, charset) : new InputStreamReader(contents); List<String> lines = CharStreams.readLines(r); Closeables.close(r, true); if (lineNumber >= 0 && lineNumber < lines.size()) { String lineStr = lines.get(lineNumber).trim(); return lineStr.length() == 0 ? null : lineStr; } } catch (IOException ioe) { } return null; }
From source file:com.flexive.rest.BinaryService.java
@GET public Response downloadBinary(@PathParam("id") long id, @QueryParam("quality") String qualityParam) throws FxApplicationException { final BinaryDescriptor desc; // get the binary descriptor to determine the MIME type for the response (security will kick in // when actually streaming the binary, so we can use supervisor privileges here) FxContext.startRunningAsSystem();// w w w .j av a 2 s.c o m try { desc = EJBLookup.getContentEngine().getBinaryDescriptor(id); } finally { FxContext.stopRunningAsSystem(); } final BinaryDescriptor.PreviewSizes quality = StringUtils.isBlank(qualityParam) ? BinaryDescriptor.PreviewSizes.ORIGINAL : BinaryDescriptor.PreviewSizes.valueOf(qualityParam.trim().toUpperCase(Locale.ENGLISH)); final InputStream in = FxStreamUtils.getBinaryStream(desc, quality); return Response.ok(new StreamingOutput() { public void write(OutputStream outputStream) throws IOException, WebApplicationException { try { ByteStreams.copy(in, outputStream); } finally { Closeables.close(in, false); } } }).type(desc.getMimeType()).build(); }
From source file:org.apache.mahout.math.hadoop.stochasticsvd.SSVDHelper.java
/** * sniff label type in the input files/*from w w w . j a va 2 s. c o m*/ */ static Class<? extends Writable> sniffInputLabelType(Path[] inputPath, Configuration conf) throws IOException { FileSystem fs = FileSystem.get(conf); for (Path p : inputPath) { FileStatus[] fstats = fs.globStatus(p); if (fstats == null || fstats.length == 0) { continue; } FileStatus firstSeqFile; if (fstats[0].isDir()) { firstSeqFile = fs.listStatus(fstats[0].getPath(), PathFilters.logsCRCFilter())[0]; } else { firstSeqFile = fstats[0]; } SequenceFile.Reader r = null; try { r = new SequenceFile.Reader(fs, firstSeqFile.getPath(), conf); return r.getKeyClass().asSubclass(Writable.class); } finally { Closeables.close(r, true); } } throw new IOException("Unable to open input files to determine input label type."); }
From source file:org.apache.mahout.text.wikipedia.WikipediaDatasetCreatorMapper.java
@Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String document = value.toString(); document = StringEscapeUtils.unescapeHtml4(CLOSE_TEXT_TAG_PATTERN .matcher(OPEN_TEXT_TAG_PATTERN.matcher(document).replaceFirst("")).replaceAll("")); String catMatch = findMatchingCategory(document); if (!"Unknown".equals(catMatch)) { StringBuilder contents = new StringBuilder(1000); TokenStream stream = analyzer.tokenStream(catMatch, new StringReader(document)); CharTermAttribute termAtt = stream.addAttribute(CharTermAttribute.class); stream.reset();/*from w ww .ja va 2s . c o m*/ while (stream.incrementToken()) { contents.append(termAtt.buffer(), 0, termAtt.length()).append(' '); } context.write(new Text(SPACE_NON_ALPHA_PATTERN.matcher(catMatch).replaceAll("_")), new Text(contents.toString())); stream.end(); Closeables.close(stream, true); } }
From source file:com.android.utils.GrabProcessOutput.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 Optional object to capture stdout/stderr. * Note that on Windows capturing the output is not optional. If output is null * the stdout/stderr will be captured and discarded. * @param waitMode Whether to wait for the process and/or the readers to finish. * @return the process return code./* www . j av a 2s.co m*/ * @throws InterruptedException if {@link Process#waitFor()} was interrupted. */ public static int grabProcessOutput(@NonNull final Process process, Wait waitMode, @Nullable final IProcessOutput output) throws InterruptedException { // read the lines as they come. if null is returned, it's // because the process finished Thread threadErr = new Thread("stderr") { @Override public void run() { // create a buffer to read the stderr output InputStream is = process.getErrorStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader errReader = new BufferedReader(isr); try { while (true) { String line = errReader.readLine(); if (output != null) { output.err(line); } if (line == null) { break; } } } catch (IOException e) { // do nothing. } finally { try { Closeables.close(is, true /* swallowIOException */); } catch (IOException e) { // cannot happen } try { Closeables.close(isr, true /* swallowIOException */); } catch (IOException e) { // cannot happen } try { Closeables.close(errReader, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } } }; Thread threadOut = new Thread("stdout") { @Override public void run() { InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader outReader = new BufferedReader(isr); try { while (true) { String line = outReader.readLine(); if (output != null) { output.out(line); } if (line == null) { break; } } } catch (IOException e) { // do nothing. } finally { try { Closeables.close(is, true /* swallowIOException */); } catch (IOException e) { // cannot happen } try { Closeables.close(isr, true /* swallowIOException */); } catch (IOException e) { // cannot happen } try { Closeables.close(outReader, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } } }; threadErr.start(); threadOut.start(); if (waitMode == Wait.ASYNC) { return 0; } // 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. if (waitMode == Wait.WAIT_FOR_READERS) { try { threadErr.join(); } catch (InterruptedException e) { } try { threadOut.join(); } catch (InterruptedException e) { } } // get the return code from the process return process.waitFor(); }
From source file:com.google.android.stardroid.data.AbstractProtoWriter.java
public void writeFiles(String prefix, AstronomicalSourcesProto sources) throws IOException { /*FileOutputStream out = null; try {/*from w w w .j a v a 2s. c o m*/ out = new FileOutputStream(prefix + ".binary"); sources.writeTo(out); } finally { Closeables.closeSilently(out); }*/ PrintWriter writer = null; try { writer = new PrintWriter(new FileWriter(prefix + "_R.ascii")); writer.append(sources.toString()); } finally { Closeables.close(writer, false); } System.out.println("Successfully wrote " + sources.getSourceCount() + " sources."); }
From source file:org.jclouds.examples.rackspace.clouddns.DeleteRecords.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. *///w w w . ja va 2s.co m public void close() throws IOException { Closeables.close(dnsApi, true); }
From source file:mahoutdemo.classification.LogisticModelParametersPredict.java
/** * Reads a model from a file./*from ww w. jav a2 s. co m*/ * @throws IOException If there is an error opening or closing the file. */ public static LogisticModelParametersPredict loadFrom(File in) throws IOException { InputStream input = new FileInputStream(in); try { return loadFrom(input); } finally { Closeables.close(input, true); } }
From source file:org.apache.mahout.classifier.sgd.TrainLogistic.java
static void mainToOutput(String[] args, PrintWriter output) throws Exception { if (parseArgs(args)) { double logPEstimate = 0; int samples = 0; CsvRecordFactory csv = lmp.getCsvRecordFactory(); OnlineLogisticRegression lr = lmp.createRegression(); for (int pass = 0; pass < passes; pass++) { BufferedReader in = open(inputFile); try { // read variable names csv.firstLine(in.readLine()); String line = in.readLine(); while (line != null) { // for each new line, get target and predictors Vector input = new RandomAccessSparseVector(lmp.getNumFeatures()); int targetValue = csv.processLine(line, input); // check performance while this is still news double logP = lr.logLikelihood(targetValue, input); if (!Double.isInfinite(logP)) { if (samples < 20) { logPEstimate = (samples * logPEstimate + logP) / (samples + 1); } else { logPEstimate = 0.95 * logPEstimate + 0.05 * logP; }// w w w. j a va 2s .co m samples++; } double p = lr.classifyScalar(input); if (scores) { output.printf(Locale.ENGLISH, "%10d %2d %10.2f %2.4f %10.4f %10.4f%n", samples, targetValue, lr.currentLearningRate(), p, logP, logPEstimate); } // now update model lr.train(targetValue, input); line = in.readLine(); } } finally { Closeables.close(in, true); } } OutputStream modelOutput = new FileOutputStream(outputFile); try { lmp.saveTo(modelOutput); } finally { Closeables.close(modelOutput, false); } output.println(lmp.getNumFeatures()); output.println(lmp.getTargetVariable() + " ~ "); String sep = ""; for (String v : csv.getTraceDictionary().keySet()) { double weight = predictorWeight(lr, 0, csv, v); if (weight != 0) { output.printf(Locale.ENGLISH, "%s%.3f*%s", sep, weight, v); sep = " + "; } } output.printf("%n"); model = lr; for (int row = 0; row < lr.getBeta().numRows(); row++) { for (String key : csv.getTraceDictionary().keySet()) { double weight = predictorWeight(lr, row, csv, key); if (weight != 0) { output.printf(Locale.ENGLISH, "%20s %.5f%n", key, weight); } } for (int column = 0; column < lr.getBeta().numCols(); column++) { output.printf(Locale.ENGLISH, "%15.9f ", lr.getBeta().get(row, column)); } output.println(); } } }
From source file:org.sonatype.nexus.apachehttpclient.NexusSSLConnectionSocketFactory.java
@Override public Socket connectSocket(final int connectTimeout, final Socket socket, final HttpHost host, final InetSocketAddress remoteAddress, final InetSocketAddress localAddress, final HttpContext context) throws IOException { checkNotNull(host);/* w ww . j a va 2 s . co m*/ checkNotNull(remoteAddress); final Socket sock = socket != null ? socket : createSocket(context); if (localAddress != null) { sock.bind(localAddress); } try { sock.connect(remoteAddress, connectTimeout); } catch (final IOException e) { Closeables.close(sock, true); throw e; } // Setup SSL layering if necessary if (sock instanceof SSLSocket) { final SSLSocket sslsock = (SSLSocket) sock; sslsock.startHandshake(); verifyHostname(sslsock, host.getHostName()); return sock; } else { return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context); } }