List of usage examples for com.google.common.io Closeables closeQuietly
public static void closeQuietly(@Nullable Reader reader)
From source file:com.google.eclipse.mechanic.core.keybinding.KeyBindingsManualFormatter.java
private void dumpBindingsToFile(BindingType bindingType, Map<KbaChangeSetQualifier, KbaChangeSet> kbaChangeSet, IPath outputLocation, String description) throws FileNotFoundException, IOException { String output = getBindingsPrintout(bindingType, kbaChangeSet, description); File file = outputLocation.toFile(); PrintStream stream = null;// ww w . j av a 2s. c o m try { stream = new PrintStream(new FileOutputStream(file)); stream.print(output); } finally { Closeables.closeQuietly(stream); } }
From source file:edu.isi.karma.cleaning.features.RecordClassifier2.java
public OnlineLogisticRegression train(HashMap<String, Vector<String>> traindata) throws Exception { String csvTrainFile = "./target/tmp/csvtrain.csv"; Data2Features.Traindata2CSV(traindata, csvTrainFile, rf); lmp = new LogisticModelParameters(); lmp.setTargetVariable("label"); lmp.setMaxTargetCategories(rf.labels.size()); lmp.setNumFeatures(rf.getFeatureNames().size()); List<String> typeList = Lists.newArrayList(); typeList.add("numeric"); List<String> predictorList = Lists.newArrayList(); for (String attr : rf.getFeatureNames()) { if (attr.compareTo("lable") != 0) { predictorList.add(attr);//from w w w . j a v a 2 s . c om } } lmp.setTypeMap(predictorList, typeList); // lmp.setUseBias(!getBooleanArgument(cmdLine, noBias)); // lmp.setTypeMap(predictorList, typeList); lmp.setLambda(1e-4); lmp.setLearningRate(50); int passes = 100; CsvRecordFactory csv = lmp.getCsvRecordFactory(); OnlineLogisticRegression lr = lmp.createRegression(); for (int pass = 0; pass < passes; pass++) { BufferedReader in = new BufferedReader(new FileReader(new File(csvTrainFile))); ; try { // read variable names csv.firstLine(in.readLine()); String line = in.readLine(); while (line != null) { // for each new line, get target and predictors RandomAccessSparseVector input = new RandomAccessSparseVector(lmp.getNumFeatures()); int targetValue = csv.processLine(line, input); String label = csv.getTargetCategories().get(lr.classifyFull(input).maxValueIndex()); // now update model lr.train(targetValue, input); line = in.readLine(); } } finally { Closeables.closeQuietly(in); } } labels = csv.getTargetCategories(); return lr; }
From source file:co.cask.tigon.flow.DeployClient.java
private static void expandJar(File jarPath, File unpackDir) throws Exception { JarFile jar = new JarFile(jarPath); Enumeration enumEntries = jar.entries(); while (enumEntries.hasMoreElements()) { JarEntry file = (JarEntry) enumEntries.nextElement(); File f = new File(unpackDir + File.separator + file.getName()); if (file.isDirectory()) { f.mkdirs();//from w ww. ja va2 s . co m continue; } else { f.getParentFile().mkdirs(); } InputStream is = jar.getInputStream(file); try { ByteStreams.copy(is, Files.newOutputStreamSupplier(f)); } finally { Closeables.closeQuietly(is); } } }
From source file:net.sourceforge.docfetcher.model.parse.ChmParser.java
/** * Converts all <tt>ChmEntry</tt>s under <tt>entry</tt> to strings and * puts them into the given <tt>StringBuilder</tt>. * /*w w w . j a v a 2s.c o m*/ * @param renderText * Whether the textual contents of the <tt>ChmEntry</tt>s * should be extracted in a readable format (true) or as raw * strings (false). */ private void append(@NotNull StringBuilder sb, @NotNull ChmEntry entry, boolean renderText) throws IOException { if (entry.hasAttribute(ChmEntry.Attribute.DIRECTORY)) { for (ChmEntry child : entry.entries(ChmEntry.Attribute.ALL)) append(sb, child, renderText); } else { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(entry.getInputStream(), "utf8" // Just guessing... //$NON-NLS-1$ )); StringBuilder entryBuffer = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) entryBuffer.append(line).append("\n\n"); //$NON-NLS-1$ /* * The current version of chm4j doesn't allow differentiating * between binary files (such as images) and HTML files. Therefore * we scan the text for HTML tags to select the HTML files. */ if (isHTML(entryBuffer)) { Source source = new Source(entryBuffer); source.setLogger(null); if (renderText) sb.append(source.getRenderer().setIncludeHyperlinkURLs(false).toString()); else sb.append(source.getTextExtractor().toString()); } } catch (RuntimeException e) { // The HTML lib can do this to us; do nothing } finally { Closeables.closeQuietly(reader); } } }
From source file:org.sonatype.nexus.mime.DefaultMimeSupport.java
@Override public Set<String> detectMimeTypesFromContent(final ContentLocator content) throws IOException { Set<String> magicMimeTypes = new HashSet<String>(); BufferedInputStream bis = null; try {/*from w w w . j a va2 s . c o m*/ magicMimeTypes.addAll(toStringSet( getTouchingMimeUtil2().getMimeTypes(bis = new BufferedInputStream(content.getContent())))); } finally { Closeables.closeQuietly(bis); } return magicMimeTypes; }
From source file:de.blizzy.documentr.system.SystemSettingsStore.java
@Override public void start() { running = true;//from w ww. jav a 2 s . co m try { User adminUser = userStore.getUser("admin"); //$NON-NLS-1$ ILockedRepository repo = globalRepositoryManager.createProjectCentralRepository(REPOSITORY_NAME, false, adminUser); Closeables.closeQuietly(repo); // repository has just been created, store settings for the first time Map<String, String> settingsToStore; synchronized (settings) { settingsToStore = Maps.newHashMap(settings); } storeSettings(settingsToStore, adminUser); } catch (IllegalStateException e) { // okay } catch (IOException e) { throw new RuntimeException(e); } catch (GitAPIException e) { throw new RuntimeException(e); } }
From source file:oculus.aperture.parchment.ParchmentModule.java
@Override protected void configure() { logger.info("Loading Parchment Module..."); MapBinder<String, ResourceDefinition> resourceBinder = MapBinder.newMapBinder(binder(), String.class, ResourceDefinition.class); // Provides the image service bindings. resourceBinder.addBinding("/parchment/{confidence}/{currency}") .toInstance(new ResourceDefinition(ParchmentResource.class).setVariable("currency", new Variable(Variable.TYPE_URI_PATH, "", false, false))); // Provides the CSS bindings resourceBinder.addBinding("/parchment.css").toInstance(new ResourceDefinition(ParchmentCSSResource.class)); // Prep CSS/* ww w . j a va2 s .c om*/ InputStream inp = ParchmentModule.class.getResourceAsStream("parchment.css"); String css = null; try { css = CharStreams.toString(new BufferedReader(new InputStreamReader(inp, Charset.forName("UTF-8")))); } catch (IOException e) { logger.error("Failure Loading Parchment Module", e); } finally { Closeables.closeQuietly(inp); } // bind result in guice. Names.bindProperties(this.binder(), ImmutableMap.of("aperture.parchment.css", css != null ? css : "{}")); }
From source file:co.cask.cdap.data.stream.service.upload.AvroStreamBodyConsumer.java
@Override public void handleError(Throwable cause) { LOG.warn("Failed to handle upload to stream {}", contentWriterFactory.getStream(), cause); Closeables.closeQuietly(bufferInput); try {/*from w w w. j av a 2s .com*/ writerThread.join(); } catch (InterruptedException e) { // Just log LOG.warn("Join on writer thread interrupted", e); } }
From source file:zookeeper.example.cache.PathCacheExample.java
private static void processCommands(CuratorFramework client, PathChildrenCache cache) throws Exception { // More scaffolding that does a simple command line processor printHelp();//from w w w .j av a 2 s. co m List<ExampleServer> servers = Lists.newArrayList(); try { addListener(cache); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); boolean done = false; while (!done) { System.out.print("> "); String command = in.readLine().trim(); String[] parts = command.split("\\s"); if (parts.length == 0) { continue; } String operation = parts[0]; String args[] = Arrays.copyOfRange(parts, 1, parts.length); if (operation.equalsIgnoreCase("help") || operation.equalsIgnoreCase("?")) { printHelp(); } else if (operation.equalsIgnoreCase("q") || operation.equalsIgnoreCase("quit")) { done = true; } else if (operation.equals("set")) { setValue(client, command, args); } else if (operation.equals("remove")) { remove(client, command, args); } else if (operation.equals("list")) { list(cache); } Thread.sleep(1000); // just to allow the console output to catch up } } finally { for (ExampleServer server : servers) { Closeables.closeQuietly(server); } } }
From source file:com.netflix.curator.framework.recipes.locks.ChildReaper.java
@Override public void close() throws IOException { if (state.compareAndSet(State.STARTED, State.CLOSED)) { Closeables.closeQuietly(reaper); task.cancel(true);// ww w.ja v a 2s . co m } }