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:cosmos.impl.CosmosImpl.java
@Override public void close() { synchronized (curator) { CuratorFrameworkState state = curator.getState(); // Stop unless we're already stopped if (!CuratorFrameworkState.STOPPED.equals(state)) { try { Closeables.close(curator, true); } catch (IOException e) { log.warn("Caught IOException closing Curator connection", e); }/*from w w w . ja va 2 s . c o m*/ } } }
From source file:com.android.ide.common.signing.KeystoreHelper.java
/** * Creates a new store with a self-signed certificate. The certificate will be valid starting * from the current date up to the number of years provided. * * @param storeType an optional type of keystore; if {@code null} the default * @param storeFile the file where the store should be created * @param storePassword a password for the key store * @param keyPassword a password for the key * @param keyAlias the alias under which the key is stored in the store * @param dn the distinguished name of the owner and issuer of the certificate * @param validityYears number of years the certificate should be valid * @throws KeytoolException failed to generate the self-signed certificate or the store *//*from www . ja v a 2s . c o m*/ private static boolean createNewStore(@Nullable String storeType, @NonNull File storeFile, @NonNull String storePassword, @NonNull String keyPassword, @NonNull String keyAlias, @NonNull String dn, int validityYears) throws KeytoolException { Preconditions.checkArgument(validityYears > 0, "validityYears (%s) <= 0", validityYears); String useStoreType = storeType; if (useStoreType == null) { useStoreType = KeyStore.getDefaultType(); Verify.verifyNotNull(useStoreType); } try { KeyStore ks = KeyStore.getInstance(useStoreType); ks.load(null, null); Pair<PrivateKey, X509Certificate> generated = generateKeyAndCertificate("RSA", "SHA1withRSA", validityYears, dn); ks.setKeyEntry(keyAlias, generated.getFirst(), keyPassword.toCharArray(), new Certificate[] { generated.getSecond() }); FileOutputStream fos = new FileOutputStream(storeFile); boolean threw = true; try { ks.store(fos, storePassword.toCharArray()); threw = false; } finally { Closeables.close(fos, threw); } } catch (KeytoolException e) { throw e; } catch (Exception e) { throw new KeytoolException("Failed to create keystore.", e); } return true; }
From source file:org.jclouds.examples.rackspace.cloudqueues.PublishSubscribe.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 w ww. j a va 2 s .com*/ public void close() throws IOException { Closeables.close(marconiApi, true); }
From source file:ch.ledcom.maven.sitespeed.analyzer.SiteSpeedAnalyzer.java
public Document analyze(URL url) throws IOException, JDOMException, InterruptedException { InputStream in = null;//from w w w. ja v a 2s. c om boolean threw = true; try { log.info("Starting analysis of [" + url.toExternalForm() + "]"); List<String> command = constructCommand(url); logCommand(command); ProcessBuilder pb = new ProcessBuilder(command); pb.redirectErrorStream(); Process p = pb.start(); // FIXME: we need to filter the InputStream as it seems we can get // content outside of the XML document (see sitespeed.io) in = p.getInputStream(); byte[] result = IOUtils.toByteArray(in); log.info("Result of analysis:" + ArrayUtils.toString(result)); Document doc = docBuilder.get().build(new ByteArrayInputStream(result)); log.info(XmlPrettyPrinter.prettyPrint(doc)); int status = p.waitFor(); if (status != 0) { throw new RuntimeException("PhantomJS returned with status [" + status + "]"); } threw = false; return doc; } finally { Closeables.close(in, threw); } }
From source file:com.android.tools.perflib.vmtrace.VmTraceParser.java
/** Parses the trace file header and returns the offset in the file where the header ends. */ @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE) long parseHeader(File f) throws IOException { long offset = 0; BufferedReader in = null;// w w w .ja v a2 s.c o m try { in = new BufferedReader(new InputStreamReader(new FileInputStream(f), Charsets.US_ASCII)); int mode = PARSE_VERSION; String line; while (true) { line = in.readLine(); if (line == null) { throw new IOException("Key section does not have an *end marker"); } // Calculate how much we have read from the file so far. The // extra byte is for the line ending not included by readLine(). offset += line.length() + 1; if (line.startsWith("*")) { if (line.equals(HEADER_SECTION_VERSION)) { mode = PARSE_VERSION; continue; } if (line.equals(HEADER_SECTION_THREADS)) { mode = PARSE_THREADS; continue; } if (line.equals(HEADER_SECTION_METHODS)) { mode = PARSE_METHODS; continue; } if (line.equals(HEADER_END)) { break; } } switch (mode) { case PARSE_VERSION: mTraceDataBuilder.setVersion(Integer.decode(line)); mode = PARSE_OPTIONS; break; case PARSE_THREADS: parseThread(line); break; case PARSE_METHODS: parseMethod(line); break; case PARSE_OPTIONS: parseOption(line); break; } } } finally { if (in != null) { try { Closeables.close(in, true /* swallowIOException */); } catch (IOException e) { // cannot happen } } } return offset; }
From source file:org.apache.jackrabbit.oak.plugins.blob.datastore.OakFileDataStore.java
@Override public void addMetadataRecord(InputStream input, String name) throws DataStoreException { try {//from ww w . ja v a 2 s . c o m File file = new File(getPath(), name); FileOutputStream os = new FileOutputStream(file); try { IOUtils.copyLarge(input, os); } finally { Closeables.close(os, true); Closeables.close(input, true); } } catch (IOException e) { LOG.error("Exception while adding root record with name {}, {}", new Object[] { name, e }); throw new DataStoreException("Could not add root record", e); } }
From source file:edu.rosehulman.mahout.classifier.naivebayes.NaiveBayesModel.java
public void serialize(Path output, Configuration conf) throws IOException { FileSystem fs = output.getFileSystem(conf); FSDataOutputStream out = fs.create(new Path(output, "naiveBayesModel.bin")); try {/*from w w w . ja va 2s .c o m*/ out.writeFloat(alphaI); VectorWritable.writeVector(out, weightsPerFeature); VectorWritable.writeVector(out, weightsPerLabel); VectorWritable.writeVector(out, perlabelThetaNormalizer); for (int row = 0; row < weightsPerLabelAndFeature.numRows(); row++) { VectorWritable.writeVector(out, weightsPerLabelAndFeature.viewRow(row)); } } finally { Closeables.close(out, false); } }
From source file:org.apache.mahout.cf.taste.example.kddcup.DataFileIterator.java
@Override public void close() { endOfData();//from ww w . java 2 s.c o m try { Closeables.close(lineIterator, true); } catch (IOException e) { log.error(e.getMessage(), e); } }
From source file:org.kitesdk.data.spi.filesystem.FileSystemMetadataProvider.java
@Override public DatasetDescriptor load(String name) { Preconditions.checkNotNull(name, "Dataset name cannot be null"); LOG.debug("Loading dataset metadata name: {}", name); Path metadataPath = pathForMetadata(name); checkExists(rootFileSystem, metadataPath); InputStream inputStream = null; Properties properties = new Properties(); DatasetDescriptor.Builder builder = new DatasetDescriptor.Builder(); Path descriptorPath = new Path(metadataPath, DESCRIPTOR_FILE_NAME); boolean threw = true; try {// w w w .j a v a 2 s . c om inputStream = rootFileSystem.open(descriptorPath); properties.load(inputStream); threw = false; } catch (IOException e) { throw new DatasetIOException( "Unable to load descriptor file:" + descriptorPath + " for dataset:" + name, e); } finally { try { Closeables.close(inputStream, threw); } catch (IOException e) { throw new DatasetIOException("Cannot close", e); } } if (properties.containsKey(FORMAT_FIELD_NAME)) { builder.format(Accessor.getDefault().newFormat(properties.getProperty(FORMAT_FIELD_NAME))); } if (properties.containsKey(PARTITION_EXPRESSION_FIELD_NAME)) { builder.partitionStrategy( Accessor.getDefault().fromExpression(properties.getProperty(PARTITION_EXPRESSION_FIELD_NAME))); } Path schemaPath = new Path(metadataPath, SCHEMA_FILE_NAME); try { builder.schemaUri(rootFileSystem.makeQualified(schemaPath).toUri()); } catch (IOException e) { throw new DatasetIOException("Unable to load schema file:" + schemaPath + " for dataset:" + name, e); } final Path location; if (properties.containsKey(LOCATION_FIELD_NAME)) { // the location should always be written by this library and validated // when the descriptor is first created. location = new Path(properties.getProperty(LOCATION_FIELD_NAME)); } else { // backwards-compatibility: older versions didn't write this property but // the data and metadata were always co-located. location = expectedPathForDataset(name); } builder.location(location); // custom properties for (String property : properties.stringPropertyNames()) { if (!RESERVED_PROPERTIES.contains(property)) { builder.property(property, properties.getProperty(property)); } } return builder.build(); }
From source file:org.apache.giraph.scripting.ScriptLoader.java
/** * Load a single deployed script/* www . j av a 2s. c o m*/ * * @param conf Configuration * @param deployedScript the deployed script */ public static void loadScript(Configuration conf, DeployedScript deployedScript) throws IOException { InputStream stream = openScriptInputStream(conf, deployedScript); switch (deployedScript.getLanguage()) { case JYTHON: loadJythonScript(stream); break; default: LOG.fatal("Don't know how to load script " + deployedScript); throw new IllegalStateException("Don't know how to load script " + deployedScript); } LOADED_SCRIPTS.add(deployedScript); Closeables.close(stream, true); }