List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:com.github.zhongl.io.IterableFile.java
public <T> Iterator<T> toIterator(final Function<ByteBuffer, T> function) { return new AbstractIterator<T>() { private ByteBuffer byteBuffer = (ByteBuffer) ByteBuffer.allocateDirect(BUFFER_SIZE) .position(BUFFER_SIZE);// w w w.jav a 2 s . co m private long position = 0; @Override protected synchronized T computeNext() { while (true) { try { int last = byteBuffer.position(); ByteBuffer duplicate = byteBuffer.duplicate(); T object = function.apply(duplicate); byteBuffer.position(duplicate.position()); position += byteBuffer.position() - last; return object; } catch (RuntimeException e) { if (isNotOutOfBound(e)) throw e; try { FileChannel channel = stream.getChannel(); if (position >= channel.size()) { DirectByteBufferCleaner.clean(byteBuffer); Closeables.closeQuietly(stream); return endOfData(); } byteBuffer.clear(); FileChannels.read(channel, position, byteBuffer); } catch (IOException ex) { throw new IllegalStateException(ex); } } } } }; }
From source file:zookeeper.example.discovery.ExampleServer.java
@Override public void close() throws IOException { Closeables.closeQuietly(serviceDiscovery); }
From source file:io.druid.server.initialization.PropertiesModule.java
@Override public void configure(Binder binder) { final Properties fileProps = new Properties(); Properties systemProps = System.getProperties(); Properties props = new Properties(fileProps); props.putAll(systemProps);/*from w w w .java 2s .c om*/ InputStream stream = ClassLoader.getSystemResourceAsStream(propertiesFile); try { if (stream == null) { File workingDirectoryFile = new File( systemProps.getProperty("druid.properties.file", propertiesFile)); if (workingDirectoryFile.exists()) { stream = new BufferedInputStream(new FileInputStream(workingDirectoryFile)); } } if (stream != null) { log.info("Loading properties from %s", propertiesFile); try { fileProps.load(new InputStreamReader(stream, Charsets.UTF_8)); } catch (IOException e) { throw Throwables.propagate(e); } } } catch (FileNotFoundException e) { log.wtf(e, "This can only happen if the .exists() call lied. That's f'd up."); } finally { Closeables.closeQuietly(stream); } binder.bind(Properties.class).toInstance(props); }
From source file:org.sonar.api.rules.XMLRuleParser.java
/** * Warning : the input stream is closed in this method *//*from w w w . jav a2s.com*/ public List<Rule> parse(InputStream input) { Reader reader = null; try { reader = new InputStreamReader(input, CharEncoding.UTF_8); return parse(reader); } catch (IOException e) { throw new SonarException("Fail to load the xml stream", e); } finally { Closeables.closeQuietly(reader); } }
From source file:com.netflix.recipes.rss.server.BaseNettyServer.java
public void close() { Closeables.closeQuietly(nettyServer); Closeables.closeQuietly(karyonServer); LoggingConfiguration.getInstance().stop(); }
From source file:org.fusesource.process.manager.GenerateControllerKinds.java
public void run() throws Exception { File baseDir = new File(System.getProperty("basedir", ".")); File srcDir = new File(baseDir, "src/main/resources"); assertTrue("source dir doesn't exist! " + srcDir, srcDir.exists()); assertTrue("source folder is not a directory " + srcDir, srcDir.isDirectory()); File classesDir = new File(baseDir, "target/classes"); File outFile = new File(classesDir, "org/fusesource/process/manager/controllerKinds"); outFile.getParentFile().mkdirs();/*from w w w . j a v a2 s . c o m*/ System.out.println("Generating controller kinds file: " + outFile); FileWriter writer = null; try { writer = new FileWriter(outFile); File[] list = srcDir.listFiles(); String postfix = ".json"; List<String> kinds = Lists.newArrayList(); assertNotNull("No JSON files found in source dir: " + srcDir, list); for (File file : list) { if (!file.isFile()) continue; String name = file.getName(); if (name.endsWith(postfix)) { String kind = name.substring(0, name.length() - postfix.length()); kinds.add(kind); writer.write(kind + "\n"); } } System.out.println("Found controller kinds: " + kinds); } finally { Closeables.closeQuietly(writer); } // lets try find the process tarball String groupId = System.getProperty("groupId", "org.fusesource.process"); String artifactId = "process-launcher"; String version = System.getProperty("version", "99-master-SNAPSHOT"); String classifier = "bin"; String extension = "tar.gz"; String name = groupId + "/" + artifactId + "/" + version; System.out.println("Loading bundle: " + name); File file = new File(baseDir + "/../process-launcher/target/" + artifactId + "-" + version + "-bin.tar.gz"); assertNotNull("Cannot find the file for " + name + " using " + file.getPath(), file); File newFile = new File(classesDir, "process-launcher.tar.gz"); Files.move(file, newFile); System.out.println("Moved process launch tarball to " + newFile); }
From source file:com.silverpeas.util.cryptage.CryptMD5.java
public static String hash(File file) throws UtilException { MessageDigest digest;/* w ww . ja va 2 s .c om*/ FileInputStream fileInputStream = null; try { digest = MessageDigest.getInstance("MD5"); fileInputStream = new FileInputStream(file); byte[] buffer = new byte[8]; int c = 0; while ((c = fileInputStream.read(buffer)) != -1) { digest.update(buffer, 0, c); } byte[] signature = digest.digest(); return getHexString(signature); } catch (NoSuchAlgorithmException e) { throw new UtilException("CryptMD5.hash()", SilverpeasException.ERROR, "root.EX_NO_MESSAGE", e); } catch (IOException e) { throw new UtilException("CryptMD5.hash()", SilverpeasException.ERROR, "root.EX_NO_MESSAGE", e); } finally { if (fileInputStream != null) { Closeables.closeQuietly(fileInputStream); } } }
From source file:org.sonar.plugins.erlang.cover.FixedOtpInputStream.java
@Override public OtpErlangObject read_compressed() throws OtpErlangDecodeException { final int tag = read1skip_version(); if (tag != OtpExternal.compressedTag) { throw new OtpErlangDecodeException( "Wrong tag encountered, expected " + OtpExternal.compressedTag + ", got " + tag); }//from w ww. j a va2s.c o m final int size = read4BE(); final byte[] buf = new byte[size]; final java.util.zip.InflaterInputStream is = new java.util.zip.InflaterInputStream(this, new Inflater(), size); try { final int dsize = is.read(buf, 0, size); if (dsize != size) { throw new OtpErlangDecodeException("Decompression gave " + dsize + " bytes, not " + size); } is.close(); } catch (final IOException e) { throw new OtpErlangDecodeException("Cannot read from input stream"); } final OtpInputStream ois = new OtpInputStream(buf, flags); OtpErlangObject ret = ois.read_any(); Closeables.closeQuietly(ois); return ret; }
From source file:org.elasticsearch.cloud.aws.node.Ec2CustomNodeAttributes.java
@Override public Map<String, String> buildAttributes() { if (!settings.getAsBoolean("cloud.node.auto_attributes", false)) { return null; }//from www .jav a 2 s. c o m Map<String, String> ec2Attributes = Maps.newHashMap(); URLConnection urlConnection; InputStream in = null; try { URL url = new URL(AwsEc2Service.EC2_METADATA_URL + "placement/availability-zone"); logger.debug("obtaining ec2 [placement/availability-zone] from ec2 meta-data url {}", url); urlConnection = url.openConnection(); urlConnection.setConnectTimeout(2000); in = urlConnection.getInputStream(); BufferedReader urlReader = new BufferedReader(new InputStreamReader(in)); String metadataResult = urlReader.readLine(); if (metadataResult == null || metadataResult.length() == 0) { logger.error("no ec2 metadata returned from {}", url); return null; } ec2Attributes.put("aws_availability_zone", metadataResult); } catch (IOException e) { logger.debug("failed to get metadata for [placement/availability-zone]: " + ExceptionsHelper.detailedMessage(e)); } finally { Closeables.closeQuietly(in); } return ec2Attributes; }
From source file:org.jclouds.tmrk.enterprisecloud.handlers.TerremarkEnterpriseCloudErrorHandler.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 ww. ja v a 2s. com message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; case 409: exception = new IllegalStateException(message, exception); case 500: if (message != null && message.indexOf("Unable to determine package for") != -1) { exception = new ResourceNotFoundException(message, exception); } } } finally { if (response.getPayload() != null) Closeables.closeQuietly(response.getPayload().getInput()); command.setException(exception); } }