List of usage examples for org.apache.commons.io IOUtils closeQuietly
public static void closeQuietly(OutputStream output)
OutputStream
. From source file:leader.LeaderSelectorExample.java
public static void main(String[] args) throws Exception { // all of the useful sample code is in ExampleClient.java System.out.println("Create " + CLIENT_QTY + " clients, have each negotiate for leadership and then wait a random number of seconds before letting another leader election occur."); System.out.println(// ww w . j a v a 2s. c o m "Notice that leader election is fair: all clients will become leader and will do so the same number of times."); List<CuratorFramework> clients = Lists.newArrayList(); List<ExampleClient> examples = Lists.newArrayList(); TestingServer server = new TestingServer(); try { for (int i = 0; i < CLIENT_QTY; ++i) { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); clients.add(client); ExampleClient example = new ExampleClient(client, PATH, "Client #" + i); examples.add(example); client.start(); example.start(); } System.out.println("Press enter/return to quit\n"); new BufferedReader(new InputStreamReader(System.in)).readLine(); } finally { System.out.println("Shutting down..."); for (ExampleClient exampleClient : examples) { IOUtils.closeQuietly(exampleClient); } for (CuratorFramework client : clients) { IOUtils.closeQuietly(client); } IOUtils.closeQuietly(server); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.common.dao.ExtractDataSetForCommonDBUnit.java
public static void main(final String[] args) throws Exception { Connection jdbcConnection = null; FileOutputStream fileOutputStream = null; try {//from w w w. j a va 2s .com // database connection Class.forName("org.postgresql.Driver"); jdbcConnection = DriverManager.getConnection(DBURL, DBUser, DBPass); final IDatabaseConnection connection = new DatabaseConnection(jdbcConnection); ITableFilter filter = new DatabaseSequenceFilter(connection); DatabaseConfig config = connection.getConfig(); config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new PostgresqlDataTypeFactory()); QueryDataSet ds = new QueryDataSet(connection, true); ds.addTable("log"); String outputPath = DB_DUMP_FOLDER + DB_DUMP_FILE; //noinspection IOResourceOpenedButNotSafelyClosed fileOutputStream = new FileOutputStream(outputPath); FlatXmlDataSet.write(ds, fileOutputStream); } finally { if (jdbcConnection != null) { jdbcConnection.close(); } IOUtils.closeQuietly(fileOutputStream); } }
From source file:locking.LockingExample.java
public static void main(String[] args) throws Exception { // all of the useful sample code is in ExampleClientThatLocks.java // FakeLimitedResource simulates some external resource that can only be access by one process at a time final FakeLimitedResource resource = new FakeLimitedResource(); ExecutorService service = Executors.newFixedThreadPool(QTY); final TestingServer server = new TestingServer(); try {// w ww.j a va 2s . c o m for (int i = 0; i < QTY; ++i) { final int index = i; Callable<Void> task = new Callable<Void>() { @Override public Void call() throws Exception { CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); try { client.start(); ExampleClientThatLocks example = new ExampleClientThatLocks(client, PATH, resource, "Client " + index); for (int j = 0; j < REPETITIONS; ++j) { example.doWork(10, TimeUnit.SECONDS); } } catch (Throwable e) { e.printStackTrace(); } finally { IOUtils.closeQuietly(client); } return null; } }; service.submit(task); } service.shutdown(); service.awaitTermination(10, TimeUnit.MINUTES); } finally { IOUtils.closeQuietly(server); } }
From source file:discovery.DiscoveryExample.java
public static void main(String[] args) throws Exception { // This method is scaffolding to get the example up and running TestingServer server = new TestingServer(); CuratorFramework client = null;/*from ww w . j a v a 2s . com*/ ServiceDiscovery<InstanceDetails> serviceDiscovery = null; Map<String, ServiceProvider<InstanceDetails>> providers = Maps.newHashMap(); try { client = CuratorFrameworkFactory.newClient(server.getConnectString(), new ExponentialBackoffRetry(1000, 3)); client.start(); JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>( InstanceDetails.class); serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH) .serializer(serializer).build(); serviceDiscovery.start(); processCommands(serviceDiscovery, providers, client); } finally { for (ServiceProvider<InstanceDetails> cache : providers.values()) { IOUtils.closeQuietly(cache); } IOUtils.closeQuietly(serviceDiscovery); IOUtils.closeQuietly(client); IOUtils.closeQuietly(server); } }
From source file:com.msopentech.odatajclient.engine.performance.PerfTestReporter.java
public static void main(final String[] args) throws Exception { // 1. check input directory final File reportdir = new File(args[0] + File.separator + "target" + File.separator + "surefire-reports"); if (!reportdir.isDirectory()) { throw new IllegalArgumentException("Expected directory, got " + args[0]); }/* w ww. ja v a2s . c o m*/ // 2. read test data from surefire output final File[] xmlReports = reportdir.listFiles(new FilenameFilter() { @Override public boolean accept(final File dir, final String name) { return name.endsWith("-output.txt"); } }); final Map<String, Map<String, Double>> testData = new TreeMap<String, Map<String, Double>>(); for (File xmlReport : xmlReports) { final BufferedReader reportReader = new BufferedReader(new FileReader(xmlReport)); try { while (reportReader.ready()) { String line = reportReader.readLine(); final String[] parts = line.substring(0, line.indexOf(':')).split("\\."); final String testClass = parts[0]; if (!testData.containsKey(testClass)) { testData.put(testClass, new TreeMap<String, Double>()); } line = reportReader.readLine(); testData.get(testClass).put(parts[1], Double.valueOf(line.substring(line.indexOf(':') + 2, line.indexOf('[')))); } } finally { IOUtils.closeQuietly(reportReader); } } // 3. build XSLX output (from template) final HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(args[0] + File.separator + "src" + File.separator + "test" + File.separator + "resources" + File.separator + XLS)); for (Map.Entry<String, Map<String, Double>> entry : testData.entrySet()) { final Sheet sheet = workbook.getSheet(entry.getKey()); int rows = 0; for (Map.Entry<String, Double> subentry : entry.getValue().entrySet()) { final Row row = sheet.createRow(rows++); Cell cell = row.createCell(0); cell.setCellValue(subentry.getKey()); cell = row.createCell(1); cell.setCellValue(subentry.getValue()); } } final FileOutputStream out = new FileOutputStream( args[0] + File.separator + "target" + File.separator + XLS); try { workbook.write(out); } finally { IOUtils.closeQuietly(out); } }
From source file:com.textocat.textokit.postagger.opennlp.OpenNLPPosTaggerTrainerCLI.java
public static void main(String[] args) throws Exception { OpenNLPPosTaggerTrainerCLI cli = new OpenNLPPosTaggerTrainerCLI(); new JCommander(cli, args); ///* www . jav a2s. c om*/ OpenNLPPosTaggerTrainer trainer = new OpenNLPPosTaggerTrainer(); trainer.setLanguageCode(cli.languageCode); trainer.setModelOutFile(cli.modelOutFile); // train params { FileInputStream fis = FileUtils.openInputStream(cli.trainParamsFile); TrainingParameters trainParams; try { trainParams = new TrainingParameters(fis); } finally { IOUtils.closeQuietly(fis); } trainer.setTrainingParameters(trainParams); } // feature extractors { FileInputStream fis = FileUtils.openInputStream(cli.extractorParams); Properties props = new Properties(); try { props.load(fis); } finally { IOUtils.closeQuietly(fis); } MorphDictionary morphDict = getMorphDictionaryAPI().getCachedInstance().getResource(); trainer.setTaggerFactory(new POSTaggerFactory(DefaultFeatureExtractors.from(props, morphDict))); } // input sentence stream { ExternalResourceDescription morphDictDesc = getMorphDictionaryAPI() .getResourceDescriptionForCachedInstance(); TypeSystemDescription tsd = createTypeSystemDescription( "com.textocat.textokit.commons.Commons-TypeSystem", TokenizerAPI.TYPESYSTEM_TOKENIZER, SentenceSplitterAPI.TYPESYSTEM_SENTENCES, PosTaggerAPI.TYPESYSTEM_POSTAGGER); CollectionReaderDescription colReaderDesc = CollectionReaderFactory.createReaderDescription( XmiCollectionReader.class, tsd, XmiCollectionReader.PARAM_INPUTDIR, cli.trainingXmiDir); AnalysisEngineDescription posTrimmerDesc = PosTrimmingAnnotator .createDescription(cli.gramCategories.toArray(new String[cli.gramCategories.size()])); bindExternalResource(posTrimmerDesc, PosTrimmingAnnotator.RESOURCE_GRAM_MODEL, morphDictDesc); AnalysisEngineDescription tagAssemblerDesc = TagAssembler.createDescription(); bindExternalResource(tagAssemblerDesc, GramModelBasedTagMapper.RESOURCE_GRAM_MODEL, morphDictDesc); AnalysisEngineDescription aeDesc = createEngineDescription(posTrimmerDesc, tagAssemblerDesc); Iterator<Sentence> sentIter = AnnotationIteratorOverCollection.createIterator(Sentence.class, colReaderDesc, aeDesc); SpanStreamOverCollection<Sentence> sentStream = new SpanStreamOverCollection<Sentence>(sentIter); trainer.setSentenceStream(sentStream); } trainer.train(); }
From source file:com.mmounirou.spotirss.SpotiRss.java
/** * @param args//from w w w . j a v a 2 s. c o m * @throws IOException * @throws ClassNotFoundException * @throws IllegalAccessException * @throws InstantiationException * @throws SpotifyClientException * @throws ChartRssException * @throws SpotifyException */ public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException, SpotifyClientException { if (args.length == 0) { System.err.println("usage : java -jar spotiboard.jar <charts-folder>"); return; } Properties connProperties = new Properties(); InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties"); try { connProperties.load(inStream); } finally { IOUtils.closeQuietly(inStream); } String host = connProperties.getProperty("host"); int port = Integer.parseInt(connProperties.getProperty("port")); String user = connProperties.getProperty("user"); final SpotifyClient spotifyClient = new SpotifyClient(host, port, user); final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient); final File outputDir = new File(args[0]); outputDir.mkdirs(); TrackCache cache = new TrackCache(); try { for (String strProvider : PROVIDERS) { String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "." + StringUtils.capitalize(strProvider); final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader() .loadClass(providerClassName).newInstance(); Iterable<String> chartsRss = getCharts(strProvider); final File resultDir = new File(outputDir, strProvider); resultDir.mkdir(); final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache); Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() { @Override @Nullable public String apply(@Nullable String chartRss) { try { long begin = System.currentTimeMillis(); ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter); Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs()); String strTitle = bilboardChartRss.getTitle(); File resultFile = new File(resultDir, strTitle); List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet()) .transform(Functions.toStringFunction())); lines.addAll(trackHrefs.values()); FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines); Playlist playlist = playlistsByTitle.get(strTitle); if (playlist != null) { playlist.getTracks().clear(); playlist.getTracks().addAll(trackHrefs.values()); spotifyClient.patch(playlist); LOGGER.info(String.format("%s chart exported patched", strTitle)); } LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle, resultFile.getAbsolutePath(), (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin))); } catch (Exception e) { LOGGER.error(String.format("fail to export %s charts", chartRss), e); } return ""; } }); // consume iterables Iterables.size(results); } } finally { cache.close(); } }
From source file:com.turn.ttorrent.client.main.TorrentMain.java
/** * Torrent creator.//www.j a v a 2 s .c o m * * <p> * You can use the {@code main()} function of this class to create * torrent files. See usage for details. * </p> */ public static void main(String[] args) throws Exception { // BasicConfigurator.configure(new ConsoleAppender(new PatternLayout("%-5p: %m%n"))); OptionParser parser = new OptionParser(); OptionSpec<Void> helpOption = parser.accepts("help").forHelp(); OptionSpec<File> inputOption = parser.accepts("input").withRequiredArg().ofType(File.class).required() .describedAs("The input file or directory for the torrent."); OptionSpec<File> outputOption = parser.accepts("output").withRequiredArg().ofType(File.class).required() .describedAs("The output torrent file."); OptionSpec<URI> announceOption = parser.accepts("announce").withRequiredArg().ofType(URI.class).required() .describedAs("The announce URL for the torrent."); parser.nonOptions().ofType(File.class).describedAs("Files to include in the torrent."); OptionSet options = parser.parse(args); List<?> otherArgs = options.nonOptionArguments(); // Display help and exit if requested if (options.has(helpOption)) { System.out.println("Usage: Torrent [<options>] <torrent-file>"); parser.printHelpOn(System.err); System.exit(0); } List<File> files = new ArrayList<File>(); for (Object o : otherArgs) files.add((File) o); Collections.sort(files); TorrentCreator creator = new TorrentCreator(options.valueOf(inputOption)); if (!files.isEmpty()) creator.setFiles(files); creator.setAnnounceList(options.valuesOf(announceOption)); Torrent torrent = creator.create(); File file = options.valueOf(outputOption); OutputStream fos = FileUtils.openOutputStream(file); try { torrent.save(fos); } finally { IOUtils.closeQuietly(fos); } }
From source file:com.doculibre.constellio.utils.resources.WriteResourceBundleUtils.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { File binDir = ClasspathUtils.getClassesDir(); File projectDir = binDir.getParentFile(); File sourceDir = new File(projectDir, "source"); String defaultLanguage;// w w w .j a va 2 s . c om String otherLanguage; if (args.length > 0) { defaultLanguage = args[0]; otherLanguage = args[1]; } else { defaultLanguage = Locale.ENGLISH.getLanguage(); otherLanguage = Locale.FRENCH.getLanguage(); } List<File> propertiesFiles = (List<File>) FileUtils.listFiles(sourceDir, new String[] { "properties" }, true); for (File propertiesFile : propertiesFiles) { File propertiesDir = propertiesFile.getParentFile(); String propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesFile.getName(), "_"); propertiesNameWoutSuffix = StringUtils.substringBefore(propertiesNameWoutSuffix, ".properties"); String noLanguageFileName = propertiesNameWoutSuffix + ".properties"; String defaultLanguageFileName = propertiesNameWoutSuffix + "_" + defaultLanguage + ".properties"; String otherLanguageFileName = propertiesNameWoutSuffix + "_" + otherLanguage + ".properties"; File noLanguageFile = new File(propertiesDir, noLanguageFileName); File defaultLanguageFile = new File(propertiesDir, defaultLanguageFileName); File otherLanguageFile = new File(propertiesDir, otherLanguageFileName); if (defaultLanguageFile.exists() && otherLanguageFile.exists() && !noLanguageFile.exists()) { System.out.println(defaultLanguageFile.getPath() + " > " + noLanguageFileName); System.out.println(defaultLanguageFile.getPath() + " > empty file"); defaultLanguageFile.renameTo(noLanguageFile); FileWriter defaultLanguageEmptyFileWriter = new FileWriter(defaultLanguageFile); defaultLanguageEmptyFileWriter.write(""); IOUtils.closeQuietly(defaultLanguageEmptyFileWriter); } } }
From source file:edu.harvard.med.iccbl.dev.HibernateConsole.java
public static void main(String[] args) { BufferedReader br = null;/*from w ww. ja v a 2s . com*/ try { CommandLineApplication app = new CommandLineApplication(args); app.processOptions(true, false); br = new BufferedReader(new InputStreamReader(System.in)); EntityManagerFactory emf = (EntityManagerFactory) app.getSpringBean("entityManagerFactory"); EntityManager em = emf.createEntityManager(); do { System.out.println("Enter HQL query (blank to quit): "); String input = br.readLine(); if (input.length() == 0) { System.out.println("Goodbye!"); System.exit(0); } try { List list = ((Session) em.getDelegate()).createQuery(input).list(); // note: this uses the Hibernate Session object, to allow HQL (and JPQL) // List list = em.createQuery(input).getResultList(); // note: this JPA method supports JPQL System.out.println("Result:"); for (Iterator iter = list.iterator(); iter.hasNext();) { Object item = iter.next(); // format output from multi-item selects ("select a, b, c, ... from ...") if (item instanceof Object[]) { List<Object> fields = Arrays.asList((Object[]) item); System.out.println(StringUtils.makeListString(fields, ", ")); } // format output from single-item selected ("select a from ..." or "from ...") else { System.out.println("[" + item.getClass().getName() + "]: " + item); } } System.out.println("(" + list.size() + " rows)\n"); } catch (Exception e) { System.out.println("Hibernate Error: " + e.getMessage()); log.error("Hibernate error", e); } System.out.println(); } while (true); } catch (Exception e) { System.err.println("Fatal Error: " + e.getMessage()); e.printStackTrace(); } finally { IOUtils.closeQuietly(br); } }