List of usage examples for java.io BufferedReader readLine
public String readLine() throws IOException
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * /* ww w .j a v a 2 s . c o m*/ * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java
/** * @param args/*from www .ja v a2s . c o m*/ */ public static void main(String[] args) { // Setup parameters int verbosity = 1; String output_format = "xml", grammar_filename = null, filename_to_parse = null; // Parse command line arguments Options options = setupOptions(); CommandLine c_line = setupCommandLine(args, options); assert c_line != null; if (c_line.hasOption("verbosity")) { verbosity = Integer.parseInt(c_line.getOptionValue("verbosity")); } if (verbosity > 0) { showHeader(); } if (c_line.hasOption("version")) { System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec Chicoutimi"); System.err.println("This program comes with ABSOLUTELY NO WARRANTY."); System.err.println("This is a free software, and you are welcome to redistribute it"); System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n"); System.exit(ERR_OK); } if (c_line.hasOption("h")) { showUsage(options); System.exit(ERR_OK); } if (c_line.hasOption("f")) { output_format = c_line.getOptionValue("f"); } // Get grammar file @SuppressWarnings("unchecked") List<String> remaining_args = c_line.getArgList(); if (remaining_args.isEmpty()) { System.err.println("ERROR: no grammar file specified"); System.exit(ERR_ARGUMENTS); } grammar_filename = remaining_args.get(0); // Get file to parse, if any if (remaining_args.size() >= 2) { filename_to_parse = remaining_args.get(1); } // Read grammar file BnfParser parser = null; try { parser = new BnfParser(new File(grammar_filename)); } catch (InvalidGrammarException e) { System.err.println("ERROR: invalid grammar"); System.exit(ERR_GRAMMAR); } catch (IOException e) { System.err.println("ERROR reading grammar " + grammar_filename); System.exit(ERR_IO); } assert parser != null; // Read input file BufferedReader bis = null; if (filename_to_parse == null) { // Read from stdin bis = new BufferedReader(new InputStreamReader(System.in)); } else { // Read from file try { bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse)))); } catch (FileNotFoundException e) { System.err.println("ERROR: file not found " + filename_to_parse); System.exit(ERR_IO); } } assert bis != null; String str; StringBuilder input_file = new StringBuilder(); try { while ((str = bis.readLine()) != null) { input_file.append(str).append("\n"); } } catch (IOException e) { System.err.println("ERROR reading input"); System.exit(ERR_IO); } String file_contents = input_file.toString(); // Parse contents of file ParseNode p_node = null; try { p_node = parser.parse(file_contents); } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) { System.err.println("ERROR parsing input\n"); e.printStackTrace(); System.exit(ERR_PARSE); } if (p_node == null) { System.err.println("ERROR parsing input\n"); System.exit(ERR_PARSE); } assert p_node != null; // Output parse node to desired format PrintStream output = System.out; OutputFormatVisitor out_vis = null; if (output_format.compareToIgnoreCase("xml") == 0) { // Output to XML out_vis = new XmlVisitor(); } else if (output_format.compareToIgnoreCase("dot") == 0) { // Output to DOT out_vis = new GraphvizVisitor(); } else if (output_format.compareToIgnoreCase("txt") == 0) { // Output to indented plain text out_vis = new IndentedTextVisitor(); } else if (output_format.compareToIgnoreCase("json") == 0) { // Output to JSON } if (out_vis == null) { System.err.println("ERROR: unknown output format " + output_format); System.exit(ERR_ARGUMENTS); } assert out_vis != null; p_node.prefixAccept(out_vis); output.print(out_vis.toOutputString()); // Terminate without error System.exit(ERR_OK); }
From source file:net.sf.firemox.Magic.java
/** * @param args//from w ww. j a v a 2s . c o m * the command line arguments * @throws Exception */ public static void main(String[] args) throws Exception { Log.init(); Log.debug("MP v" + IdConst.VERSION + ", jre:" + System.getProperty("java.runtime.version") + ", jvm:" + System.getProperty("java.vm.version") + ",os:" + System.getProperty("os.name") + ", res:" + Toolkit.getDefaultToolkit().getScreenSize().width + "x" + Toolkit.getDefaultToolkit().getScreenSize().height + ", root:" + MToolKit.getRootDir()); System.setProperty("swing.aatext", "true"); System.setProperty(SubstanceLookAndFeel.WATERMARK_IMAGE_PROPERTY, MToolKit.getIconPath(Play.ZONE_NAME + "/hardwoodfloor.png")); final File substancelafFile = MToolKit.getFile(FILE_SUBSTANCE_PROPERTIES); if (substancelafFile == null) { Log.warn("Unable to locate '" + FILE_SUBSTANCE_PROPERTIES + "' file, you are using the command line with wrong configuration. See http://www.firemox.org/dev/project.html documentation"); } else { System.getProperties().load(new FileInputStream(substancelafFile)); } MToolKit.defaultFont = new Font("Arial", 0, 11); try { if (args.length > 0) { final String[] args2 = new String[args.length - 1]; System.arraycopy(args, 1, args2, 0, args.length - 1); if ("-rebuild".equals(args[0])) { XmlConfiguration.main(args2); } else if ("-oracle2xml".equals(args[0])) { Oracle2Xml.main(args2); } else if ("-batch".equals(args[0])) { if ("-server".equals(args[1])) { batchMode = BATCH_SERVER; } else if ("-client".equals(args[1])) { batchMode = BATCH_CLIENT; } } else { Log.error("Unknown options '" + Arrays.toString(args) + "'\nUsage : java -jar starter.jar <options>, where options are :\n" + "\t-rebuild -game <tbs name> [-x] [-d] [-v] [-h] [-f] [-n]\n" + "\t-oracle2xml -f <oracle file> -d <output directory> [-v] [-h]"); } System.exit(0); return; } if (batchMode == -1 && !"Mac OS X".equals(System.getProperty("os.name"))) { splash = new SplashScreen(MToolKit.getIconPath("splash.jpg"), null, 2000); } // language settings LanguageManager.initLanguageManager(Configuration.getString("language", "auto")); } catch (Throwable t) { Log.error("START-ERROR : \n\t" + t.getMessage()); System.exit(1); return; } Log.debug("MP Language : " + LanguageManager.getLanguage().getName()); speparateAvatar = Toolkit.getDefaultToolkit().getScreenSize().height > 768; // verify the java version, minimal is 1.5 if (new JavaVersion().compareTo(new JavaVersion(IdConst.MINIMAL_JRE)) == -1) { Log.error(LanguageManager.getString("wrongjava") + IdConst.MINIMAL_JRE); } // load look and feel settings lookAndFeelName = Configuration.getString("preferred", MUIManager.LF_SUBSTANCE_CLASSNAME); // try { // FileInputStream in= new FileInputStream("MAGIC.TTF"); // MToolKit.defaultFont= Font.createFont(Font.TRUETYPE_FONT, in); // in.close(); // MToolKit.defaultFont= MToolKit.defaultFont.deriveFont(Font.BOLD, 11); // } // catch (FileNotFoundException e) { // System.out.println("editorfont.ttf not found, using default."); // } // catch (Exception ex) { // ex.printStackTrace(); // } // Read available L&F final LinkedList<Pair<String, String>> lfList = new LinkedList<Pair<String, String>>(); try { BufferedReader buffReader = new BufferedReader( new InputStreamReader(MToolKit.getResourceAsStream(IdConst.FILE_THEME_SETTINGS))); String line; while ((line = buffReader.readLine()) != null) { line = line.trim(); if (!line.startsWith("#")) { final int index = line.indexOf(';'); if (index != -1) { lfList.add(new Pair<String, String>(line.substring(0, index), line.substring(index + 1))); } } } IOUtils.closeQuietly(buffReader); } catch (Throwable e) { // no place for resolve this problem Log.debug("Error reading L&F properties : " + e.getMessage()); } for (Pair<String, String> pair : lfList) { UIManager.installLookAndFeel(pair.key, pair.value); } // install L&F if (SkinLF.isSkinLF(lookAndFeelName)) { // is a SkinLF Look & Feel /* * Make sure we have a nice window decoration. */ SkinLF.installSkinLF(lookAndFeelName); } else { // is Metal Look & Feel if (!MToolKit.isAvailableLookAndFeel(lookAndFeelName)) { // preferred look&feel is not available JOptionPane.showMessageDialog(magicForm, LanguageManager.getString("preferredlfpb", lookAndFeelName), LanguageManager.getString("error"), JOptionPane.INFORMATION_MESSAGE); setDefaultUI(); } // Install the preferred LookAndFeel newLAF = MToolKit.geLookAndFeel(lookAndFeelName); frameDecorated = newLAF.getSupportsWindowDecorations(); /* * Make sure we have a nice window decoration. */ JFrame.setDefaultLookAndFeelDecorated(frameDecorated); JDialog.setDefaultLookAndFeelDecorated(frameDecorated); UIManager.setLookAndFeel(MToolKit.geLookAndFeel(lookAndFeelName)); } // Start main thread try { new Magic(); SwingUtilities.invokeLater(SkinLF.REFRESH_RUNNER); } catch (Throwable e) { Log.fatal("In main thread, occurred exception : ", e); ConnectionManager.closeConnexions(); return; } }
From source file:SheetStructure.java
public static void main(String[] args) { HttpURLConnection connection = null; StringBuilder response = new StringBuilder(); //We are using Jackson JSON parser to serialize and deserialize the JSON. See http://wiki.fasterxml.com/JacksonHome //Feel free to use which ever library you prefer. ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String accessToken = "";//Insert your access token here. try {/*from w w w .j ava 2 s . c o m*/ System.out.println("Starting HelloSmartsheet2: Betty's Bake Sale..."); //First Create a new sheet. String sheetName = "Betty's Bake Sale"; //We will be using POJOs to represent the REST request objects. We will convert these to and from JSON using Jackson JSON. //Their structure directly relates to the JSON that gets passed through the API. //Note that these POJOs are included as static inner classes to keep this to one file. Normally they would be broken out. Sheet newSheet = new Sheet(); newSheet.setName(sheetName); newSheet.setColumns(Arrays.asList(new Column("Baked Goods", "TEXT_NUMBER", null, true, null), new Column("Baker", "CONTACT_LIST", null, null, null), new Column("Price Per Item", "TEXT_NUMBER", null, null, null), new Column("Gluten Free?", "CHECKBOX", "FLAG", null, null), new Column("Status", "PICKLIST", null, null, Arrays.asList("Started", "Finished", "Delivered")))); connection = (HttpURLConnection) new URL(GET_SHEETS_URL).openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newSheet); Result<Sheet> newSheetResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Sheet>>() { }); newSheet = newSheetResult.getResult(); System.out.println("Sheet " + newSheet.getName() + " created, id: " + newSheet.getId()); //Now add a column: String columnName = "Delivery Date"; System.out.println("Adding column " + columnName + " to " + sheetName); Column newColumn = new Column(columnName, "DATE", 5); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), newColumn); Result<Column> newColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println( "Column " + newColumnResult.getResult().getTitle() + " added to " + newSheet.getName()); //Next, we will get the list of Columns from the API. We could figure this out based on what the server has returned in the result, but we'll just ask the API for it. System.out.println("Fetching " + newSheet.getName() + " sheet columns..."); connection = (HttpURLConnection) new URL(SHEET_COLUMNS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); List<Column> allColumns = mapper.readValue(connection.getInputStream(), new TypeReference<List<Column>>() { }); System.out.println("Fetched."); //Now we will be adding rows System.out.println("Inserting rows into " + newSheet.getName()); List<Row> rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Brownies"), new Cell(allColumns.get(1).id, "julieann@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Snickerdoodles"), new Cell(allColumns.get(1).id, "stevenelson@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-04")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Rice Krispy Treats"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Started")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Muffins"), new Cell(allColumns.get(1).id, "sandrassmart@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Finished")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Chocolate Chip Cookies"), new Cell(allColumns.get(1).id, "janedaniels@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Delivered"), new Cell(allColumns.get(5).id, "2013-09-05")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Ginger Snaps"), new Cell(allColumns.get(1).id, "nedbarnes@example.com"), new Cell(allColumns.get(2).id, "$.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Unknown", false)))); //Note that this one is strict=false. This is because "Unknown" was not one of the original options when the column was created. RowWrapper rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> newRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + newRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move a row to the top. System.out.println("Moving row 6 to the top."); RowWrapper moveToTop = new RowWrapper(); moveToTop.setToTop(true); connection = (HttpURLConnection) new URL( ROW_URL.replace(ID, "" + newRowsResult.getResult().get(5).getId())).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), moveToTop); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row 6 moved to top."); //Insert empty rows for spacing rows = new ArrayList<Row>(); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "")))); rows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Delivered")))); rowWrapper = new RowWrapper(); rowWrapper.setToBottom(true); rowWrapper.setRows(rows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> spacerRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + spacerRowsResult.getResult().size() + " rows to " + newSheet.getName()); //Move Delivered rows to be children of the last spacer row. System.out.println("Moving delivered rows to Delivered section..."); Long[] deliveredRowIds = new Long[] { newRowsResult.result.get(1).getId(), newRowsResult.result.get(4).getId() }; RowWrapper parentRowLocation = new RowWrapper(); parentRowLocation.setParentId(spacerRowsResult.getResult().get(1).getId()); for (Long deliveredId : deliveredRowIds) { System.out.println("Moving " + deliveredId + " to Delivered."); connection = (HttpURLConnection) new URL(ROW_URL.replace(ID, "" + deliveredId)).openConnection(); connection.setRequestMethod("PUT"); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), parentRowLocation); mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Row id " + deliveredId + " moved."); } System.out.println("Appending additional rows to items in progress..."); List<Row> siblingRows = new ArrayList<Row>(); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Scones"), new Cell(allColumns.get(1).id, "tomlively@example.com"), new Cell(allColumns.get(2).id, "$1.50"), new Cell(allColumns.get(3).id, Boolean.TRUE), new Cell(allColumns.get(4).id, "Finished")))); siblingRows.add(new Row(Arrays.asList(new Cell(allColumns.get(0).id, "Lemon Bars"), new Cell(allColumns.get(1).id, "rickthames@example.com"), new Cell(allColumns.get(2).id, "$1"), new Cell(allColumns.get(3).id, Boolean.FALSE), new Cell(allColumns.get(4).id, "Started")))); rowWrapper = new RowWrapper(); rowWrapper.setSiblingId(newRowsResult.getResult().get(3).getId()); rowWrapper.setRows(siblingRows); connection = (HttpURLConnection) new URL(SHEET_ROWS_URL.replace(ID, "" + newSheet.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); mapper.writeValue(connection.getOutputStream(), rowWrapper); Result<List<Row>> siblingRowsResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<List<Row>>>() { }); System.out.println("Added " + siblingRowsResult.getResult().size() + " rows to " + newSheet.getName()); System.out.println("Moving Status column to index 1..."); Column statusColumn = allColumns.get(4); Column moveColumn = new Column(); moveColumn.setIndex(1); moveColumn.setTitle(statusColumn.title); moveColumn.setSheetId(newSheet.getId()); moveColumn.setType(statusColumn.getType()); connection = (HttpURLConnection) new URL(COLUMN_URL.replace(ID, "" + statusColumn.getId())) .openConnection(); connection.addRequestProperty("Authorization", "Bearer " + accessToken); connection.addRequestProperty("Content-Type", "application/json"); connection.setDoOutput(true); connection.setRequestMethod("PUT"); mapper.writeValue(connection.getOutputStream(), moveColumn); Result<Column> movedColumnResult = mapper.readValue(connection.getInputStream(), new TypeReference<Result<Column>>() { }); System.out.println("Moved column " + movedColumnResult.getResult().getId()); System.out.println("Completed Hellosmartsheet2: Betty's Bake Sale."); } catch (IOException e) { InputStream is = ((HttpURLConnection) connection).getErrorStream(); if (is != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; try { response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); Result<?> result = mapper.readValue(response.toString(), Result.class); System.err.println(result.message); } catch (IOException e1) { e1.printStackTrace(); } } e.printStackTrace(); } catch (Exception e) { System.out.println("Something broke: " + e.getMessage()); e.printStackTrace(); } }
From source file:LamportBasicVersion.java
public static void main(String[] args) throws FileNotFoundException, IOException, InterruptedException { totalMessageCount = 0;/* www . j a v a 2s. c o m*/ //For parsing the file and storing the information String line; String configurationFile = "configuration.txt"; int lineCountInFile = 0; myProcessId = Integer.parseInt(args[0]); FileReader fileReader = new FileReader(configurationFile); BufferedReader bufferedReader = new BufferedReader(fileReader); while ((line = bufferedReader.readLine()) != null) { if ((!(line.startsWith("#"))) && (!(line.isEmpty()))) { lineCountInFile = lineCountInFile + 1; String[] splitLine = line.split(" "); switch (lineCountInFile) { case 1: numberOfProcesses = Integer.parseInt(splitLine[0]); interRequestDelay = Integer.parseInt(splitLine[1]); csExecutionTime = Integer.parseInt(splitLine[2]); maxNumberOfRequest = Integer.parseInt(splitLine[3]); machineNames = new String[Integer.parseInt(splitLine[0])]; portNumbers = new int[Integer.parseInt(splitLine[0])]; break; default: machineNames[lineCountInFile - 2] = splitLine[1]; portNumbers[lineCountInFile - 2] = Integer.parseInt(splitLine[2]); break; } } } conditionArray = new int[numberOfProcesses]; finishFlagArray = new int[numberOfProcesses]; //Initializing vector class VectorClass.initialize(numberOfProcesses); //Fill the arrays with zero false value for (int o = 0; o < numberOfProcesses; o++) { conditionArray[o] = 0; finishFlagArray[o] = 0; } // Write output to file filename = filename + Integer.toString(myProcessId) + ".out"; file = new File(filename); file.createNewFile(); writer = new FileWriter(file); // Write clocks to file filenameClock = filenameClock + Integer.toString(myProcessId) + ".out"; fileClock = new File(filenameClock); fileClock.createNewFile(); //writerClock = new FileWriter(fileClock); fw = new FileWriter(fileClock); bw = new BufferedWriter(fw); // // Expo mean insert csExecutionExpoDelay = new ExponentialDistribution(csExecutionTime); interRequestExpoDelay = new ExponentialDistribution(interRequestDelay); // System.out.println("********************************************************"); System.out.println("My process id : " + myProcessId); System.out.println("Number of processes : " + numberOfProcesses); System.out.println("Inter-request delay : " + interRequestDelay); System.out.println("Critical section execution time : " + csExecutionTime); System.out.println("Maximum number of request : " + maxNumberOfRequest); System.out.println( "My process name : " + machineNames[myProcessId] + " My port number : " + portNumbers[myProcessId]); for (int i = 0; i < numberOfProcesses; i++) { System.out.println("Process name : " + machineNames[i] + " Port number : " + portNumbers[i]); } System.out.println("********************************************************"); //For hosting server localhost SctpServerChannel sctpServerChannel = SctpServerChannel.open(); InetSocketAddress serverAddr = new InetSocketAddress(portNumbers[myProcessId]); sctpServerChannel.bind(serverAddr); System.out.println("********************************************************"); System.out.println("Local server hosted"); System.out.println("********************************************************"); //For creating neighbor SCTP channels Thread.sleep(30000); socketAddress = new SocketAddress[numberOfProcesses]; sctpChannel = new SctpChannel[numberOfProcesses]; System.out.println("********************************************************"); System.out.println("Neighbor channels created"); System.out.println("********************************************************"); //Thread spanned for generating critical section request new Thread(new LamportBasicVersion()).start(); //while loop to receive all the requests and other messages while (true) { try (SctpChannel sctpChannelFromClient = sctpServerChannel.accept()) { mutex.acquire(); byteBufferFromNeighbor.clear(); String receiveMessage; MessageInfo messageInfoFromNeighbor = sctpChannelFromClient.receive(byteBufferFromNeighbor, null, null); //System.out.println("Raw Message : " + messageInfoFromNeighbor); receiveMessage = byteToString(byteBufferFromNeighbor, messageInfoFromNeighbor); //write to file start writer.write("Received Message : " + receiveMessage); writer.write("\n"); writer.flush(); //write to file end System.out.println("Received Message : " + receiveMessage); if (receiveMessage.contains("Request")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // int requestMade = Integer.parseInt(parseMessage[3] + parseMessage[1]); queue.add(requestMade); //Send reply messages to that process for entering CS lamportClock++; //vector clock construction int[] vector = VectorClass.increment(myProcessId); String vectorClockConstruction = ""; for (int g = 0; g < vector.length; g++) { if (g == 0) { vectorClockConstruction = vectorClockConstruction + Integer.toString(vector[g]); } else { vectorClockConstruction = vectorClockConstruction + "," + Integer.toString(vector[g]); } } // for (int k = 0; k < numberOfProcesses; k++) { if (k == Integer.parseInt(parseMessage[1])) { try { byteBufferToNeighbor.clear(); initializeChannels(); sctpChannel[k].connect(socketAddress[k]); String sendMessage = "Reply from Process-" + myProcessId + "-" + Integer.toString(requestMade) + "-" + lamportClock + "-" + vectorClockConstruction; System.out.println("Message sent is : " + sendMessage); //write to file start writer.write("Message sent is : " + sendMessage); writer.write("\n"); writer.flush(); //write to file end MessageInfo messageInfoToNeighbor = MessageInfo.createOutgoing(null, 0); byteBufferToNeighbor.put(sendMessage.getBytes()); byteBufferToNeighbor.flip(); sctpChannel[k].send(byteBufferToNeighbor, messageInfoToNeighbor); totalMessageCount++; sctpChannel[k].close(); } catch (IOException ex) { Logger.getLogger(LamportBasicVersion.class.getName()).log(Level.SEVERE, null, ex); } } } } else if (receiveMessage.contains("Reply")) { conditionArray[myProcessId] = 1; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // conditionArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (conditionArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { L1ConditionFlag = 1; System.out.println("Inside L1"); blockingQueue.put("L1"); //Clearing condition array after receiving all REPLY for (int z = 0; z < numberOfProcesses; z++) { conditionArray[z] = 0; } if (L2ConditionFlag == 0 && outstandingRequest == 1) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); if (queueArray[0] == currentRequestBeingServed) { System.out.println("Inside L2"); L2ConditionFlag = 1; blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Release")) { int present = 0; int delete = 0; String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // if (queue.size() != 0) { Integer[] queueArray = new Integer[queue.size()]; queue.toArray(queueArray); Arrays.sort(queueArray); for (int a = 0; a < queueArray.length; a++) { if (queueArray[a] == Integer.parseInt(parseMessage[2])) { present = 1; delete = a; } } if (present == 1) { for (int s = 0; s <= delete; s++) { queue.remove(); } } } if (L2ConditionFlag == 0 && outstandingRequest == 1) { if (queue.size() != 0) { Integer[] queueArray1 = new Integer[queue.size()]; queue.toArray(queueArray1); Arrays.sort(queueArray1); if (currentRequestBeingServed == queueArray1[0]) { L2ConditionFlag = 1; System.out.println("Inside L2"); blockingQueue.put("L2"); } } } } else if (receiveMessage.contains("Finish")) { String[] parseMessage = receiveMessage.split("-"); lamportClock = Math.max(lamportClock, Integer.parseInt(parseMessage[3])) + 1; //vector clock update String[] stringNumericalTimestamp = parseMessage[4].split(","); int[] numericalTimestamp = new int[stringNumericalTimestamp.length]; for (int d = 0; d < stringNumericalTimestamp.length; d++) { numericalTimestamp[d] = Integer.parseInt(stringNumericalTimestamp[d]); } VectorClass.update(myProcessId, numericalTimestamp); // finishFlagArray[Integer.parseInt(parseMessage[1])] = 1; int count = 0; for (int v = 0; v < numberOfProcesses; v++) { if (finishFlagArray[v] == 1) { count = count + 1; } } if (count == numberOfProcesses) { break; } } //logic for other messages //Print the queue to check System.out.println("********************************************************"); for (Object item : queue) { System.out.print(item); System.out.print("\t"); } System.out.println("********************************************************"); } mutex.release(); } }
From source file:edu.nyu.tandon.tool.RawHits.java
@SuppressWarnings("unchecked") public static void main(final String[] arg) throws Exception { SimpleJSAP jsap = new SimpleJSAP(RawHits.class.getName(), "Loads indices relative to a collection, possibly loads the collection, and answers to queries.", new Parameter[] { new FlaggedOption("collection", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'c', "collection", "The collection of documents indexed by the given indices."), new FlaggedOption("objectCollection", new ObjectParser(DocumentCollection.class, MG4JClassParser.PACKAGE), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'o', "object-collection", "An object specification describing a document collection."), new FlaggedOption("titleList", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 't', "title-list", "A serialized big list of titles (will override collection titles if specified)."), new FlaggedOption("titleFile", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'T', "title-file", "A file of newline-separated, UTF-8 titles (will override collection titles if specified)."), new FlaggedOption("input", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, 'I', "input", "A file containing the input."), new Switch("noSizes", 'n', "no-sizes", "Disable loading document sizes (they are necessary for BM25 scoring)."), new Switch("http", 'h', "http", "Starts an HTTP query server."), new Switch("verbose", 'v', "verbose", "Print full exception stack traces."), new FlaggedOption("itemClass", MG4JClassParser.getParser(), JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'i', "item-class", "The class that will handle item display in the HTTP server."), new FlaggedOption("itemMimeType", JSAP.STRING_PARSER, "text/html", JSAP.NOT_REQUIRED, 'm', "item-mime-type", "A MIME type suggested to the class handling item display in the HTTP server."), new FlaggedOption("port", JSAP.INTEGER_PARSER, "4242", JSAP.NOT_REQUIRED, 'p', "port", "The port on localhost where the server will appear."), new UnflaggedOption("basenameWeight", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.REQUIRED, JSAP.GREEDY, "The indices that the servlet will use. Indices are specified using their basename, optionally followed by a colon and a double representing the weight used to score results from that index. Indices without a specified weight are weighted 1."), new Switch("noMplex", 'P', "noMplex", "Starts with multiplex disabled."), new FlaggedOption("results", JSAP.INTEGER_PARSER, "1000", JSAP.NOT_REQUIRED, 'r', "results", "The # of results to display"), new FlaggedOption("mode", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'M', "time", "The results display mode"), new FlaggedOption("divert", JSAP.STRING_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'd', "divert", "output file"), new FlaggedOption("dumpsize", JSAP.INTEGER_PARSER, JSAP.NO_DEFAULT, JSAP.NOT_REQUIRED, 'D', "dumpsize", "number of queries before dumping") });/*w ww . j ava 2 s . c o m*/ final JSAPResult jsapResult = jsap.parse(arg); if (jsap.messagePrinted()) return; final DocumentCollection documentCollection = (DocumentCollection) (jsapResult.userSpecified("collection") ? AbstractDocumentSequence.load(jsapResult.getString("collection")) : jsapResult.userSpecified("objectCollection") ? jsapResult.getObject("objectCollection") : null); final BigList<? extends CharSequence> titleList = (BigList<? extends CharSequence>) (jsapResult .userSpecified("titleList") ? BinIO.loadObject(jsapResult.getString("titleList")) : jsapResult.userSpecified("titleFile") ? new FileLinesBigList(jsapResult.getString("titleFile"), "UTF-8") : null); final String[] basenameWeight = jsapResult.getStringArray("basenameWeight"); final Object2ReferenceLinkedOpenHashMap<String, Index> indexMap = new Object2ReferenceLinkedOpenHashMap<String, Index>( Hash.DEFAULT_INITIAL_SIZE, .5f); final Reference2DoubleOpenHashMap<Index> index2Weight = new Reference2DoubleOpenHashMap<Index>(); final boolean verbose = jsapResult.getBoolean("verbose"); final boolean loadSizes = !jsapResult.getBoolean("noSizes"); RawHits.loadIndicesFromSpec(basenameWeight, loadSizes, documentCollection, indexMap, index2Weight); final long numberOfDocuments = indexMap.values().iterator().next().numberOfDocuments; if (titleList != null && titleList.size64() != numberOfDocuments) throw new IllegalArgumentException("The number of titles (" + titleList.size64() + " and the number of documents (" + numberOfDocuments + ") do not match"); final Object2ObjectOpenHashMap<String, TermProcessor> termProcessors = new Object2ObjectOpenHashMap<String, TermProcessor>( indexMap.size()); for (String alias : indexMap.keySet()) termProcessors.put(alias, indexMap.get(alias).termProcessor); final SimpleParser simpleParser = new SimpleParser(indexMap.keySet(), indexMap.firstKey(), termProcessors); final Reference2ReferenceMap<Index, Object> index2Parser = new Reference2ReferenceOpenHashMap<Index, Object>(); /* // Fetch parsers for payload-based fields. for( Index index: indexMap.values() ) if ( index.hasPayloads ) { if ( index.payload.getClass() == DatePayload.class ) index2Parser.put( index, DateFormat.getDateInstance( DateFormat.SHORT, Locale.UK ) ); } */ final HitsQueryEngine queryEngine = new HitsQueryEngine(simpleParser, new DocumentIteratorBuilderVisitor( indexMap, index2Parser, indexMap.get(indexMap.firstKey()), MAX_STEMMING), indexMap); queryEngine.setWeights(index2Weight); queryEngine.score(new Scorer[] { new BM25Scorer(), new VignaScorer() }, new double[] { 1, 1 }); queryEngine.multiplex = !jsapResult.userSpecified("moPlex") || jsapResult.getBoolean("noMplex"); queryEngine.intervalSelector = null; queryEngine.equalize(1000); RawHits query = new RawHits(queryEngine); // start docHits with at least 10K results query.interpretCommand("$score BM25Scorer"); // query.interpretCommand("$mode time"); if (jsapResult.userSpecified("divert")) query.interpretCommand("$divert " + jsapResult.getObject("divert")); query.displayMode = OutputType.DOCHHITS; query.maxOutput = jsapResult.getInt("results", 1000); String q; int n = 0; String lastQ = ""; try { final BufferedReader br = new BufferedReader( new InputStreamReader(new FileInputStream(jsapResult.getString("input")))); final ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>> results = new ObjectArrayList<DocumentScoreInfo<ObjectArrayList<Byte>>>(); for (;;) { q = br.readLine(); if (q == null) { System.err.println(); break; // CTRL-D } if (q.length() == 0) continue; if (q.charAt(0) == '$') { if (!query.interpretCommand(q)) break; continue; } queryCount++; long time = -System.nanoTime(); if (q.compareTo(lastQ) != 0) { try { n = queryEngine.process(q, 0, query.maxOutput, results); } catch (QueryParserException e) { if (verbose) e.getCause().printStackTrace(System.err); else System.err.println(e.getCause()); continue; } catch (Exception e) { if (verbose) e.printStackTrace(System.err); else System.err.println(e); continue; } lastQ = q; } time += System.nanoTime(); query.output(results, documentCollection, titleList, TextMarker.TEXT_BOLDFACE); } } finally { } }
From source file:DIA_Umpire_Quant.DIA_Umpire_ExtLibSearch.java
/** * @param args the command line arguments *//* w w w .j ava 2 s. c om*/ public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire targeted re-extraction analysis using external library (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_ExtLibSearch.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_extlibsearch.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String ExternalLibPath = ""; String ExternalLibDecoyTag = "DECOY"; float ExtProbThreshold = 0.99f; float RTWindow_Ext = -1f; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } case "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "ExternalLibPath": { ExternalLibPath = value; break; } case "ExtProbThreshold": { ExtProbThreshold = Float.parseFloat(value); break; } case "RTWindow_Ext": { RTWindow_Ext = Float.parseFloat(value); break; } case "ExternalLibDecoyTag": { ExternalLibDecoyTag = value; if (ExternalLibDecoyTag.endsWith("_")) { ExternalLibDecoyTag = ExternalLibDecoyTag.substring(0, ExternalLibDecoyTag.length() - 1); } break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.FastaPath = tandemPara.FastaPath; FileList.add(DiaFile); } } } //<editor-fold defaultstate="collapsed" desc="Targeted re-extraction using external library"> //External library search Logger.getRootLogger().info("Targeted extraction using external library"); //Read exteranl library FragmentLibManager ExlibManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, FilenameUtils.getBaseName(ExternalLibPath)); if (ExlibManager == null) { ExlibManager = new FragmentLibManager(FilenameUtils.getBaseName(ExternalLibPath)); //Import traML file ExlibManager.ImportFragLibByTraML(ExternalLibPath, ExternalLibDecoyTag); //Check if there are decoy spectra ExlibManager.CheckDecoys(); //ExlibManager.ImportFragLibBySPTXT(ExternalLibPath); ExlibManager.WriteFragmentLibSerialization(WorkFolder); } Logger.getRootLogger() .info("No. of peptide ions in external lib:" + ExlibManager.PeptideFragmentLib.size()); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } //Generate RT mapping RTMappingExtLib RTmap = new RTMappingExtLib(diafile.IDsummary, ExlibManager, diafile.GetParameter()); RTmap.GenerateModel(); RTmap.GenerateMappedPepIon(); diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.GenerateMassCalibrationRTMap(); //Perform targeted re-extraction diafile.TargetedExtractionQuant(false, ExlibManager, ExtProbThreshold, RTWindow_Ext); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); //Remove target IDs below the defined probability threshold diafile.IDsummary.RemoveLowProbMappedIon(ExtProbThreshold); diafile.ExportID(); diafile.ClearStructure(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); }
From source file:com.cloudera.flume.util.FlumeShell.java
/** * Args are optional - the first arg is the host:port for the master to * connect to/*ww w . j a v a2 s. c om*/ */ public static void main(String[] args) throws IOException, TTransportException { // Make sure the Java version is not older than 1.6 if (!CheckJavaVersion.isVersionOk()) { LOG.error("Exiting because of an old Java version or Java version in bad format"); System.exit(-1); } CommandLine cmd = null; Options options = new Options(); options.addOption("?", false, "Command line usage"); options.addOption("c", true, "Connect to master:adminport:reportport"); options.addOption("e", true, "Run a single command"); options.addOption("s", true, "Run a FlumeShell script"); options.addOption("q", false, "Run in quiet mode - only print command results"); try { CommandLineParser parser = new PosixParser(); cmd = parser.parse(options, args); } catch (ParseException e) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("FlumeShell", options, true); System.exit(-1); } if (cmd.hasOption('?')) { HelpFormatter fmt = new HelpFormatter(); fmt.printHelp("FlumeShell", options, true); System.exit(0); } boolean print = true; if (cmd.hasOption('q')) { print = false; } FlumeShell shell = new FlumeShell(print); if (cmd.hasOption("c")) { String[] addr = cmd.getOptionValue("c").split(":"); // determine the admin port int aPort = parseAdminPort(addr.length >= 2 ? addr[1] : null); // determine the report server port int rPort = parseReportPort(addr.length >= 3 ? addr[2] : null); shell.connect(addr[0], aPort, rPort); } if (cmd.hasOption("e")) { long ret = shell.executeLine(cmd.getOptionValue("e")); // return error code if negative, otherwise return 0. System.exit(ret < 0 ? (int) ret : 0); } if (cmd.hasOption("s")) { FileReader f = null; try { f = new FileReader(cmd.getOptionValue('s')); } catch (IOException e) { System.err.println("Failed to open script: " + cmd.getOptionValue('s')); System.err.println("Exception was: " + e.getMessage()); System.exit(1); } BufferedReader in = new BufferedReader(f); String str; while ((str = in.readLine()) != null) { shell.executeLine(str); } System.exit(0); } if (!cmd.hasOption('q')) { shell.printHello(); } shell.run(); }
From source file:IndexService.IndexServer_Old.java
public static void main(String[] args) throws IOException, HiveException { IndexServer_Old server = new IndexServer_Old(); server.start();//w ww . j a va 2s .c o m BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str; while (true) { try { str = br.readLine(); String[] strs = str.split(" "); if (strs[0].equals("setindexstatus")) { Path indexpath = new Path(strs[1]); server.db.setIndexStatus(indexpath.getParent().getParent().getName(), indexpath.getParent().getName(), indexpath.getName(), Integer.valueOf(strs[2])); } else if (str.equals("exit")) { server.close(); System.exit(0); break; } } catch (NumberFormatException e) { e.printStackTrace(); } catch (HiveException e) { e.printStackTrace(); } } }
From source file:ExecDemoLs.java
public static void main(String argv[]) throws IOException { final Process p; // Process tracks one external native process BufferedReader is; // reader for output of process String line;//w ww .j ava2 s . com p = Runtime.getRuntime().exec(PROGRAM); // Optional: start a thread to wait for the process to terminate. // Don't just wait in main line, but here set a "done" flag and // use that to control the main reading loop below. Thread waiter = new Thread() { public void run() { try { p.waitFor(); } catch (InterruptedException ex) { // OK, just quit. return; } System.out.println("Program terminated!"); done = true; } }; waiter.start(); // getInputStream gives an Input stream connected to // the process p's standard output (and vice versa). We use // that to construct a BufferedReader so we can readLine() it. is = new BufferedReader(new InputStreamReader(p.getInputStream())); while (!done && ((line = is.readLine()) != null)) System.out.println(line); return; }