List of usage examples for java.io IOException getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:Main.java
/** Index all text files under a directory. */ public static void main(String[] args) { String usage = "java IndexFiles" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = "index"; String docsPath = null;//from ww w .java2 s . co m boolean create = true; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { indexPath = args[i + 1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i + 1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.err.println("Usage: " + usage); System.exit(1); } final File docDir = new File(docsPath); if (!docDir.exists() || !docDir.canRead()) { System.out.println("Document directory '" + docDir.getAbsolutePath() + "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(new File(indexPath)); // :Post-Release-Update-Version.LUCENE_XY: Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_4_10_0); IndexWriterConfig iwc = new IndexWriterConfig(Version.LUCENE_4_10_0, analyzer); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // // iwc.setRAMBufferSizeMB(256.0); IndexWriter writer = new IndexWriter(dir, iwc); indexDocs(writer, docDir); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:at.co.malli.relpm.RelPM.java
/** * @param args the command line arguments *//*from ww w. j ava 2s . c om*/ public static void main(String[] args) { //<editor-fold defaultstate="collapsed" desc=" Create config & log directory "> String userHome = System.getProperty("user.home"); File relPm = new File(userHome + "/.RelPM"); if (!relPm.exists()) { boolean worked = relPm.mkdir(); if (!worked) { ExceptionDisplayer.showErrorMessage(new Exception("Could not create directory " + relPm.getAbsolutePath() + " to store user-settings and logs")); System.exit(-1); } } File userConfig = new File(relPm.getAbsolutePath() + "/RelPM-userconfig.xml"); //should be created... if (!userConfig.exists()) { try { URL resource = RelPM.class.getResource("/at/co/malli/relpm/RelPM-defaults.xml"); FileUtils.copyURLToFile(resource, userConfig); } catch (IOException ex) { ExceptionDisplayer.showErrorMessage(new Exception("Could not copy default config. Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage())); System.exit(-1); } } if (!userConfig.canWrite() || !userConfig.canRead()) { ExceptionDisplayer.showErrorMessage(new Exception( "Can not read or write " + userConfig.getAbsolutePath() + "to store user-settings")); System.exit(-1); } if (System.getProperty("os.name").toLowerCase().contains("win")) { Path relPmPath = Paths.get(relPm.toURI()); try { Files.setAttribute(relPmPath, "dos:hidden", true); } catch (IOException ex) { ExceptionDisplayer.showErrorMessage(new Exception("Could not set " + relPm.getAbsolutePath() + " hidden. " + "Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage())); System.exit(-1); } } //</editor-fold> logger.trace("Environment setup sucessfull"); //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code "> try { String wantedLookAndFeel = SettingsProvider.getInstance().getString("gui.lookAndFeel"); UIManager.LookAndFeelInfo[] installed = UIManager.getInstalledLookAndFeels(); boolean found = false; for (UIManager.LookAndFeelInfo info : installed) { if (info.getClassName().equals(wantedLookAndFeel)) found = true; } if (found) UIManager.setLookAndFeel(wantedLookAndFeel); else UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } catch (InstantiationException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } catch (IllegalAccessException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { logger.error(ex.getMessage()); ExceptionDisplayer.showErrorMessage(ex); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc=" Add GUI start to awt EventQue "> java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainGUI().setVisible(true); } }); //</editor-fold> }
From source file:com.dreamerpartner.codereview.lucene.IndexHelper.java
public static void main(String[] args) { long beginTime = System.currentTimeMillis(); try {// w w w. ja v a 2s .c o m List<Document> docs = new ArrayList<Document>(); List<Field[]> list = getTestData(); for (Field[] fields : list) { Document doc = new Document(); for (Field field : fields) { doc.add(field); } docs.add(doc); } adds("test", docs); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } finally { long endTime = System.currentTimeMillis(); logger.debug("main " + (endTime - beginTime) + " milliseconds."); } }
From source file:acmi.l2.clientmod.l2_version_switcher.Main.java
public static void main(String[] args) { if (args.length != 3 && args.length != 4) { System.out.println("USAGE: l2_version_switcher.jar host game version <--splash> <filter>"); System.out.println("EXAMPLE: l2_version_switcher.jar " + L2.NCWEST_HOST + " " + L2.NCWEST_GAME + " 1 \"system\\*\""); System.out.println(/*from w ww. ja v a2s.co m*/ " l2_version_switcher.jar " + L2.PLAYNC_TEST_HOST + " " + L2.PLAYNC_TEST_GAME + " 48"); System.exit(0); } List<String> argsList = new ArrayList<>(Arrays.asList(args)); String host = argsList.get(0); String game = argsList.get(1); int version = Integer.parseInt(argsList.get(2)); Helper helper = new Helper(host, game, version); boolean available = false; try { available = helper.isAvailable(); } catch (IOException e) { System.err.print(e.getClass().getSimpleName()); if (e.getMessage() != null) { System.err.print(": " + e.getMessage()); } System.err.println(); } System.out.println(String.format("Version %d available: %b", version, available)); if (!available) { System.exit(0); } List<FileInfo> fileInfoList = null; try { fileInfoList = helper.getFileInfoList(); } catch (IOException e) { System.err.println("Couldn\'t get file info map"); System.exit(1); } boolean splash = argsList.remove("--splash"); if (splash) { Optional<FileInfo> splashObj = fileInfoList.stream() .filter(fi -> fi.getPath().contains("sp_32b_01.bmp")).findAny(); if (splashObj.isPresent()) { try (InputStream is = new FilterInputStream( Util.getUnzipStream(helper.getDownloadStream(splashObj.get().getPath()))) { @Override public int read() throws IOException { int b = super.read(); if (b >= 0) b ^= 0x36; return b; } @Override public int read(byte[] b, int off, int len) throws IOException { int r = super.read(b, off, len); if (r >= 0) { for (int i = 0; i < r; i++) b[off + i] ^= 0x36; } return r; } }) { new DataInputStream(is).readFully(new byte[28]); BufferedImage bi = ImageIO.read(is); JFrame frame = new JFrame("Lineage 2 [" + version + "] " + splashObj.get().getPath()); frame.setContentPane(new JComponent() { { setPreferredSize(new Dimension(bi.getWidth(), bi.getHeight())); } @Override protected void paintComponent(Graphics g) { g.drawImage(bi, 0, 0, null); } }); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println("Splash not found"); } return; } String filter = argsList.size() > 3 ? separatorsToSystem(argsList.get(3)) : null; File l2Folder = new File(System.getProperty("user.dir")); List<FileInfo> toUpdate = fileInfoList.parallelStream().filter(fi -> { String filePath = separatorsToSystem(fi.getPath()); if (filter != null && !wildcardMatch(filePath, filter, IOCase.INSENSITIVE)) return false; File file = new File(l2Folder, filePath); try { if (file.exists() && file.length() == fi.getSize() && Util.hashEquals(file, fi.getHash())) { System.out.println(filePath + ": OK"); return false; } } catch (IOException e) { System.out.println(filePath + ": couldn't check hash: " + e); return true; } System.out.println(filePath + ": need update"); return true; }).collect(Collectors.toList()); List<String> errors = Collections.synchronizedList(new ArrayList<>()); ExecutorService executor = Executors.newFixedThreadPool(16); CompletableFuture[] tasks = toUpdate.stream().map(fi -> CompletableFuture.runAsync(() -> { String filePath = separatorsToSystem(fi.getPath()); File file = new File(l2Folder, filePath); File folder = file.getParentFile(); if (!folder.exists()) { if (!folder.mkdirs()) { errors.add(filePath + ": couldn't create parent dir"); return; } } try (InputStream input = Util .getUnzipStream(new BufferedInputStream(helper.getDownloadStream(fi.getPath()))); OutputStream output = new BufferedOutputStream(new FileOutputStream(file))) { byte[] buffer = new byte[Math.min(fi.getSize(), 1 << 24)]; int pos = 0; int r; while ((r = input.read(buffer, pos, buffer.length - pos)) >= 0) { pos += r; if (pos == buffer.length) { output.write(buffer, 0, pos); pos = 0; } } if (pos != 0) { output.write(buffer, 0, pos); } System.out.println(filePath + ": OK"); } catch (IOException e) { String msg = filePath + ": FAIL: " + e.getClass().getSimpleName(); if (e.getMessage() != null) { msg += ": " + e.getMessage(); } errors.add(msg); } }, executor)).toArray(CompletableFuture[]::new); CompletableFuture.allOf(tasks).thenRun(() -> { for (String err : errors) System.err.println(err); executor.shutdown(); }); }
From source file:de.micromata.genome.tpsb.executor.GroovyShellExecutor.java
public static void main(String[] args) { String methodName = null;// w ww . j av a 2s .c o m if (args.length > 0 && StringUtils.isNotBlank(args[0])) { methodName = args[0]; } GroovyShellExecutor exec = new GroovyShellExecutor(); //System.out.println("GroovyShellExecutor start"); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String line; StringBuffer code = new StringBuffer(); try { while ((line = in.readLine()) != null) { if (line.equals("--EOF--") == true) { break; } code.append(line); code.append("\n"); //System.out.flush(); } } catch (IOException ex) { throw new RuntimeException("Failure reading std in: " + ex.toString(), ex); } try { exec.executeCode(code.toString(), methodName); } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework warn("GroovyShellExecutor failed with exception: " + ex.getClass().getName() + ": " + ex.getMessage() + "\n" + ExceptionUtils.getStackTrace(ex)); } System.out.println("--EOP--"); System.out.flush(); }
From source file:lucene.IndexFiles.java
/** Index all text files under a directory. */ public static void main(String[] args) { String usage = "java org.apache.lucene.demo.IndexFiles" + " [-index INDEX_PATH] [-docs DOCS_PATH] [-update]\n\n" + "This indexes the documents in DOCS_PATH, creating a Lucene index" + "in INDEX_PATH that can be searched with SearchFiles"; String indexPath = "E:/index26"; // is DFR/*from w ww . java 2s. c om*/ //2 is normal //3 is ib with h3 //4 is ib with h2 with porter stemmer //5 is ib with h2 with s stemmer //6 is ib with h2 without stemmer //7 is without stemmer without <p //8 is basic with all tags //9 is ib with h2 and stopwords without stemmer //10 like without ib, lower tags //11 like 10 with lower tags p, br and hr //12 like 11 with tags closed //13 is closed tags with punctuation replace and whitespace tokenizer with hyphen cared for //14 std tokenizer with hyphen taken cared for with stemmer //15 like 14 without stemming //16 like 15 with LMD //17 like 11 with LMD //18 with count of lower and upper delimiters of split //19 like 18 with (?i) to ignore case in all and valipas > 9 //20 with (?i) in all //21 is fresh 19 //22 is legalspans with LMD //23 is fresh 19 without 0 pass //24 is legalspans with InB2 //25 is 23 //26 is 25 with s stemmer and 0 //27 is legalspans demo of 50 passages //28 is modified legal span and fast //29 is 28 with s-stemming //30 is 28 with porter stemming String docsPath = "E:/documents/text"; boolean create = true; for (int i = 0; i < args.length; i++) { if ("-index".equals(args[i])) { indexPath = args[i + 1]; i++; } else if ("-docs".equals(args[i])) { docsPath = args[i + 1]; i++; } else if ("-update".equals(args[i])) { create = false; } } if (docsPath == null) { System.err.println("Usage: " + usage); System.exit(1); } final Path docDir = Paths.get(docsPath); if (!Files.isReadable(docDir)) { System.out.println("Document directory dhfndk '" + docDir.toAbsolutePath() + "' does not exist or is not readable, please check the path"); System.exit(1); } Date start = new Date(); try { System.out.println("Indexing to directory '" + indexPath + "'..."); Directory dir = FSDirectory.open(Paths.get(indexPath)); //Analyzer analyzer = new StandardAnalyzer(); //IndexWriterConfig iwc = new IndexWriterConfig(analyzer); StandardAnalyzer analyzer = new StandardAnalyzer(); //Directory dir = new RAMDirectory(); IndexWriterConfig iwc = new IndexWriterConfig(analyzer); /*IBSimilarity similarity = new IBSimilarity( new DistributionLL(),//1 //new DistributionSPL(),//2 new LambdaDF(),//1 //new LambdaTTF(), //2 new NormalizationH2());*/ /*DFRSimilarity similarity = new DFRSimilarity( ///////INB2 Similarity new BasicModelIn(), new AfterEffectL(), new NormalizationH1());*/ LMDirichletSimilarity similarity = new LMDirichletSimilarity();//////// LMD Model iwc.setSimilarity(similarity); IndexWriter writer = new IndexWriter(dir, iwc); if (create) { // Create a new index in the directory, removing any // previously indexed documents: iwc.setOpenMode(OpenMode.CREATE); } else { // Add new documents to an existing index: iwc.setOpenMode(OpenMode.CREATE_OR_APPEND); } System.out.println("Test 1"); // Optional: for better indexing performance, if you // are indexing many documents, increase the RAM // buffer. But if you do this, increase the max heap // size to the JVM (eg add -Xmx512m or -Xmx1g): // // iwc.setRAMBufferSizeMB(256.0); //IndexWriter writer = new IndexWriter(dir, iwc); System.out.println("Test 2"); indexDocs(writer, docDir); System.out.println("Test 3"); // NOTE: if you want to maximize search performance, // you can optionally call forceMerge here. This can be // a terribly costly operation, so generally it's only // worth it when your index is relatively static (ie // you're done adding documents to it): // // writer.forceMerge(1); writer.close(); Date end = new Date(); System.out.println(end.getTime() - start.getTime() + " total milliseconds"); } catch (IOException e) { System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage()); } }
From source file:vmwareConDiag.Starter.java
/** * Main method to test if connection to a vCenter can established. It loads also a config.properties with * user credentials for vCenter to establish the connection using the ViJavaConnectionTest. * After established connection some "about information" from the vCenter are received and the connection * will be closed.// w ww .j a v a2 s . co m * * @param args - No args evaluated */ public static void main(String[] args) { // Init vCenter credentials String host = EMPTY_STRING; String user = EMPTY_STRING; String pass = EMPTY_STRING; Boolean metrics = true; // Used for read in config.properties Properties properties = new Properties(); // vCenter service instance used if a vCenter connection could be established ServiceInstance serviceInstance; // Load config.properties from current directory try { properties.load(new FileInputStream(CONFIG_PROPERTIES)); host = properties.getProperty(PROP_HOST); user = properties.getProperty(PROP_USER); pass = properties.getProperty(PROP_PASS); metrics = Boolean.valueOf(properties.getProperty(PROP_QUERY_METRICS, "true")); doMetrics = metrics; } catch (IOException e) { logger.error("Couldn't read configuration property ['{}']. Error message: '{}'", CONFIG_PROPERTIES, e.getMessage()); logger.debug("Stack trace: '{}'", CONFIG_PROPERTIES, e.getMessage(), e.getStackTrace()); // No vCenter credentials --> Error exit System.exit(1); } // Could read config.properties. System.out.println("Reading virtual machines and ESX hosts from " + host + " with " + user + "/pass(SHA-256) " + DigestUtils.sha256Hex(pass) + "\n"); // Initialize connection with vCenter credentials ViJavaConnectTest viJavaConnectTest = new ViJavaConnectTest(host, user, pass); // Try to establish the connection to vCenter try { System.out.print("Try to connect VMware vCenter " + host + " ... "); // Establish connection serviceInstance = viJavaConnectTest.connect(); // Give some information to test if connection and credentials work System.out.println("SUCCESS\n"); System.out.println("VMware API Type: " + serviceInstance.getAboutInfo().apiType); System.out.println("VMware API Version: " + serviceInstance.getAboutInfo().apiVersion + " build " + serviceInstance.getAboutInfo().build); System.out.println("VMware operating system: " + serviceInstance.getAboutInfo().getOsType() + "\n"); // Give some information about VMware systems System.out.println("Collect Host Systems"); System.out.println("-----------------------"); iterateVmwareHostSystems(serviceInstance); System.out.println("\nCollect Virtual Machines"); System.out.println("------------------------"); iterateVmwareVirtualMachines(serviceInstance); } catch (MalformedURLException e) { logger.error("Malformed URL exception occurred. Error message: '{}'", e.getMessage()); logger.debug("Stack trace: '{}'", e.getStackTrace()); // Connection not possible --> Error exit System.exit(1); } catch (RemoteException e) { logger.error("Remote exception {} occurred. Error message: '{}'", e.getClass().getName(), e.getMessage()); logger.debug("Stack trace: '{}'", e.getStackTrace()); // Connection not possible --> Error exit System.exit(1); } // Disconnect vCenter connection viJavaConnectTest.disconnect(); }
From source file:Main.java
public static String convertStreamToString(InputStream is) { if (is != null) { StringBuilder sb = new StringBuilder(); String line;/*from www . jav a2 s. c o m*/ try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } catch (IOException e) { Log.e(e.getClass().getName() + " convertStreamToString", e.getMessage(), e); } finally { try { is.close(); } catch (IOException e) { Log.e(e.getClass().getName() + " convertStreamToString", e.getMessage(), e); } } return sb.toString(); } else { return ""; } }
From source file:org.tomahawk.libtomahawk.utils.parser.XspfParser.java
public static Playlist parse(String url) { String xspfString = null;//w ww . ja v a 2 s . co m try { Response response = NetworkUtils.httpRequest(null, url, null, null, null, null, true); xspfString = response.body().string(); } catch (IOException e) { Log.e(TAG, "parse: " + e.getClass() + ": " + e.getLocalizedMessage()); } return parseXspf(xspfString); }
From source file:org.runbuddy.libtomahawk.utils.parser.XspfParser.java
public static Playlist parse(File file) { String xspfString = null;/* w ww . j a va 2s . com*/ try { xspfString = FileUtils.readFileToString(file, Charset.forName("UTF-8")); } catch (IOException e) { Log.e(TAG, "parse: " + e.getClass() + ": " + e.getLocalizedMessage()); } return parseXspf(xspfString); }