List of usage examples for java.io BufferedReader BufferedReader
public BufferedReader(Reader in)
From source file:com.icesoft.applications.faces.address.XWrapperUtil.java
public static void main(String[] args) { if (log.isDebugEnabled()) { log.debug("Converting database..."); }/* ww w . j a v a2 s . c o m*/ //load the CSV file InputStream is = MatchAddressDB.class.getResourceAsStream(CSV_ADDRESS_DB); BufferedReader buff = new BufferedReader(new InputStreamReader(is)); XMLEncoder xEncode = null; XAddressDataWrapper xData; //open the XML encoder and attempt to write the xml file try { xEncode = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(XML_GZ_ADDRESS_DB))); } catch (FileNotFoundException ex) { log.error("Database could not be written.", ex); } //first line char[] line = getNextLine(buff); while (line != null) { //get three strings within quotes String addressValues[] = new String[3]; int stringValueStart = 0, stringValueEnd; for (int i = 0; i < 3; i++) { //opening quote while (line[stringValueStart++] != '\"') { } stringValueEnd = stringValueStart + 1; //closing quote while (line[stringValueEnd] != '\"') { stringValueEnd++; } //value addressValues[i] = new String(line, stringValueStart, stringValueEnd - stringValueStart); stringValueStart = stringValueEnd + 1; } //assign the data to the wrapper xData = new XAddressDataWrapper(); xData.setCity(addressValues[1]); xData.setState(addressValues[2]); xData.setZip(addressValues[0]); //read the next line (entry) in the CSV file line = getNextLine(buff); } //close the XML Encoder try { xEncode.close(); } catch (NullPointerException npe) { log.error("Could not close XML Encoder.", npe); return; } if (log.isDebugEnabled()) { log.debug("Closed XML Encoder."); } }
From source file:com.quix.aia.cn.imo.mapper.UrlForUserData.java
public static void main(String[] args) { // TODO Auto-generated method stub UserAuthResponds userAuth = new UserAuthResponds(); try {/*w ww . jav a 2s . c o m*/ GsonBuilder builder = new GsonBuilder(); DefaultHttpClient httpClient = new DefaultHttpClient(); String username = "", psw = "", co = ""; username = "NSNP306"; psw = "A111111A"; co = "0986"; HttpGet getRequest = new HttpGet("http://211.144.219.243/isp/rest/index.do?isAjax=true&account=" + username + "&co=" + co + "&password=" + psw + ""); getRequest.addHeader("accept", "application/json"); HttpResponse response = httpClient.execute(getRequest); if (response.getStatusLine().getStatusCode() != 200) { throw new RuntimeException( "Failed : HTTP error code : " + response.getStatusLine().getStatusCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); Gson googleJson = new Gson(); userAuth = googleJson.fromJson(output, UserAuthResponds.class); System.out.println("Success " + userAuth.getSuccess()); if (userAuth.getSuccess().equals("1")) { System.out.println("Login successfully Done"); } else { System.out.println("Login Failed "); } } httpClient.getConnectionManager().shutdown(); // googleJson = builder.create(); // Type listType = new TypeToken<List<UserAuthResponds>>() {}.getType(); } catch (ClientProtocolException e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } catch (IOException e) { log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); } }
From source file:org.jaqpot.core.service.client.jpdi.JPDIClientFactory.java
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException { CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create().build(); asyncClient.start();/*ww w . j av a 2s .c om*/ HttpGet request = new HttpGet("http://www.google.com"); request.addHeader("Accept", "text/html"); Future f = asyncClient.execute(request, new FutureCallback<HttpResponse>() { @Override public void completed(HttpResponse t) { System.out.println("completed"); try { String result = new BufferedReader(new InputStreamReader(t.getEntity().getContent())).lines() .collect(Collectors.joining("\n")); System.out.println(result); } catch (IOException ex) { Logger.getLogger(JPDIClientFactory.class.getName()).log(Level.SEVERE, null, ex); } catch (UnsupportedOperationException ex) { Logger.getLogger(JPDIClientFactory.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void failed(Exception excptn) { System.out.println("failed"); } @Override public void cancelled() { System.out.println("cancelled"); } }); f.get(); asyncClient.close(); }
From source file:com.asquareb.kaaval.MachineKey.java
/** * Main method to execute as a command line utility. Provides the option to * encrypt a string, decrypt a encrypted string or exit from the program *//*w w w .j ava 2 s .c o m*/ public static void main(String[] args) { String originalPassword = null; String encryptedPassword = null; try { final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter E - Encrypt,D - Decrypt,X - Exit :"); final String choice = cin.readLine(); final Random rand = new Random(); boolean phraseCorrect = false; String app = null; if (choice.equalsIgnoreCase("E")) { System.out.print("Enter the string to encrypt :"); originalPassword = cin.readLine(); System.out.println("Choose a phrase of min 8 chars in length "); System.out.println(" Also the password should include 2 Cap,"); System.out.println(" 2 small letters,2 numeric and 2 non alpha numeric chars"); while (!phraseCorrect) { System.out.print("Enter a phrase to encrypt :"); password = cin.readLine().toCharArray(); phraseCorrect = PasswordRules.verifyPassword(password); } System.out.print("Enter application code :"); app = cin.readLine(); app += (rand.nextInt(10000)); encryptedPassword = encrypt(originalPassword, app); System.out.println("Encrypted password :" + encryptedPassword); System.out.println("Key stored in :" + app); System.out.println("*** Provide the encrypted string to app team"); System.out.println("*** Store the key file in a secure durectory"); System.out.println("*** Inform the key file name and location to app team"); } else if (choice.equalsIgnoreCase("D")) { System.out.print("Enter the string to Decrypt :"); encryptedPassword = cin.readLine(); System.out.print("Enter the name of key file :"); app = cin.readLine(); final String decryptedPassword = decrypt(encryptedPassword, app); System.out.print("Decrypted string :" + decryptedPassword); } return; } catch (KaavalException e) { e.PrintProtectException(); } catch (Exception e) { e.printStackTrace(); } }
From source file:EchoClient.java
public static void main(String[] args) throws IOException { Socket echoSocket = null;/* www . j ava 2 s. c o m*/ PrintWriter out = null; BufferedReader in = null; try { echoSocket = new Socket("taranis", 7); out = new PrintWriter(echoSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader( echoSocket.getInputStream())); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis."); System.exit(1); } catch (IOException e) { System.err.println("Couldn't get I/O for " + "the connection to: taranis."); System.exit(1); } BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in)); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); System.out.println("echo: " + in.readLine()); } out.close(); in.close(); stdIn.close(); echoSocket.close(); }
From source file:net.morphbank.webclient.ProcessFiles.java
/** * @param args//w ww. ja va 2 s . co m * args[0] directory including terminal '/' * args[1] prefix of request files * args[2] number of digits in file index value * args[3] number of files * args[4] index of first file (default 0) * args[5] prefix of service * args[6] prefix of response files (default args[1] + "Resp") */ public static void main(String[] args) { ProcessFiles fileProcessor = new ProcessFiles(); // restTest.processRequest(URL, UPLOAD_FILE); String zeros = "0000000"; if (args.length < 4) { System.out.println("Too few parameters"); } else { try { // get parameters String reqDir = args[0]; String reqPrefix = args[1]; int numDigits = Integer.valueOf(args[2]); if (numDigits > zeros.length()) numDigits = zeros.length(); NumberFormat intFormat = new DecimalFormat(zeros.substring(0, numDigits)); int numFiles = Integer.valueOf(args[3]); int firstFile = 0; BufferedReader fileIn = new BufferedReader(new FileReader(FILE_IN_PATH)); String line = fileIn.readLine(); fileIn.close(); firstFile = Integer.valueOf(line); // firstFile = 189; // numFiles = 1; int lastFile = firstFile + numFiles - 1; String url = URL; String respPrefix = reqPrefix + "Resp"; if (args.length > 5) respPrefix = args[5]; if (args.length > 6) url = args[6]; // process files for (int i = firstFile; i <= lastFile; i++) { String xmlOutputFile = null; String requestFile = reqDir + reqPrefix + intFormat.format(i) + ".xml"; System.out.println("Processing request file " + requestFile); String responseFile = reqDir + respPrefix + intFormat.format(i) + ".xml"; System.out.println("Response file " + responseFile); // restTest.processRequest(URL, UPLOAD_FILE); fileProcessor.processRequest(url, requestFile, responseFile); Writer fileOut = new FileWriter(FILE_IN_PATH, false); fileOut.append(Integer.toString(i + 1)); fileOut.close(); } } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java
public static void main(String[] args) throws Exception { if (args.length != 4 && args.length != 5) { System.err.println(/* ww w . j a v a2 s . c o m*/ "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional)."); return; } File queryDir = new File(args[0]); String resourceUrl = args[1]; int warmUpRounds = Integer.parseInt(args[2]); int testRounds = Integer.parseInt(args[3]); File resultDir; if (args.length == 4) { resultDir = null; } else { resultDir = new File(args[4]); if (!resultDir.exists()) { if (!resultDir.mkdirs()) { throw new RuntimeException("Failed to create result directory: " + resultDir); } } } File[] queryFiles = queryDir.listFiles(); assert queryFiles != null; Arrays.sort(queryFiles); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost httpPost = new HttpPost(resourceUrl); httpPost.addHeader("content-type", "application/json"); for (File queryFile : queryFiles) { StringBuilder stringBuilder = new StringBuilder(); try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) { int length; while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) { stringBuilder.append(new String(CHAR_BUFFER, 0, length)); } } String query = stringBuilder.toString(); httpPost.setEntity(new StringEntity(query)); System.out.println( "--------------------------------------------------------------------------------"); System.out.println("Running query: " + query); System.out.println( "--------------------------------------------------------------------------------"); // Warm-up Rounds System.out.println("Run " + warmUpRounds + " times to warm up..."); for (int i = 0; i < warmUpRounds; i++) { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); System.out.print('*'); } System.out.println(); // Test Rounds System.out.println("Run " + testRounds + " times to get response time statistics..."); long[] responseTimes = new long[testRounds]; long totalResponseTime = 0L; for (int i = 0; i < testRounds; i++) { long startTime = System.currentTimeMillis(); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); httpResponse.close(); long responseTime = System.currentTimeMillis() - startTime; responseTimes[i] = responseTime; totalResponseTime += responseTime; System.out.print(responseTime + "ms "); } System.out.println(); // Store result. if (resultDir != null) { File resultFile = new File(resultDir, queryFile.getName() + ".result"); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); try (BufferedInputStream bufferedInputStream = new BufferedInputStream( httpResponse.getEntity().getContent()); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) { int length; while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) { bufferedWriter.write(new String(BYTE_BUFFER, 0, length)); } } httpResponse.close(); } // Process response times. double averageResponseTime = (double) totalResponseTime / testRounds; double temp = 0; for (long responseTime : responseTimes) { temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime); } double standardDeviation = Math.sqrt(temp / testRounds); System.out.println("Average response time: " + averageResponseTime + "ms"); System.out.println("Standard deviation: " + standardDeviation); } } }
From source file:org.hyperic.hq.hqapi1.tools.PasswordEncryptor.java
public static void main(String[] args) throws Exception { String password1 = String.valueOf(PasswordField.getPassword(System.in, "Enter password: ")); String password2 = String.valueOf(PasswordField.getPassword(System.in, "Re-Enter password: ")); String encryptionKey = "defaultkey"; if (password1.equals(password2)) { System.out.print("Encryption Key: "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); encryptionKey = in.readLine();/*from www .j ava 2 s. c o m*/ if (encryptionKey.length() < 8) { System.out.println("Encryption key too short. Please use at least 8 characters"); System.exit(-1); } } else { System.out.println("Passwords don't match"); System.exit(-1); } System.out.println("The encrypted password is " + encryptPassword(password1, encryptionKey)); }
From source file:DIA_Umpire_Quant.DIA_Umpire_LCMSIDGen.java
/** * @param args the command line arguments *///w w w.j a v a 2s .c o m public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire LCMSID geneartor (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be: java -jar -Xmx10G DIA_Umpire_LCMSIDGen.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_lcmsidgen.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; 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 "DecoyPrefix": { if (!"".equals(value)) { tandemPara.DecoyPrefix = value; } break; } case "PeptideFDR": { tandemPara.PepFDR = Float.parseFloat(value); break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //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()); } //process each DIA file to genearate untargeted identifications for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { long time = System.currentTimeMillis(); DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); FileList.add(DiaFile); 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 + "...."); DiaFile.ParsePepXML(tandemPara, null); DiaFile.BuildStructure(); if (!DiaFile.MS1FeatureMap.ReadPeakCluster()) { Logger.getRootLogger().info("Loading peak and structure failed, job is incomplete"); System.exit(1); } DiaFile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster(); //Generate mapping between index of precursor feature and pseudo MS/MS scan index DiaFile.GenerateClusterScanNomapping(); //Doing quantification DiaFile.AssignQuant(); DiaFile.ClearStructure(); DiaFile.IDsummary.ReduceMemoryUsage(); time = System.currentTimeMillis() - time; Logger.getRootLogger().info(mzXMLFile + " processed time:" + String.format("%d hour, %d min, %d sec", TimeUnit.MILLISECONDS.toHours(time), TimeUnit.MILLISECONDS.toMinutes(time) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(time)), TimeUnit.MILLISECONDS.toSeconds(time) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)))); } Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); } }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrSimpleIndexApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("i", null, true, "Input File"); options.addOption("u", null, true, "Solr URI"); options.addOption("n", null, true, "Batch size"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {/*from w ww.jav a 2 s. c om*/ CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("i")) { inputFile = cmd.getOptionValue("i"); } else { Usage("Specify Input File"); } if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } if (cmd.hasOption("n")) { batchQty = Integer.parseInt(cmd.getOptionValue("n")); } SolrServerWrapper solrServer = new SolrServerWrapper(solrURI); BufferedReader inpText = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFile))); XmlHelper xmlHlp = new XmlHelper(); String docText = XmlHelper.readNextXMLIndexEntry(inpText); for (int docNum = 1; docText != null; ++docNum, docText = XmlHelper.readNextXMLIndexEntry(inpText)) { // 1. Read document text Map<String, String> docFields = null; HashMap<String, Object> objDocFields = new HashMap<String, Object>(); try { docFields = xmlHlp.parseXMLIndexEntry(docText); } catch (SAXException e) { System.err.println("Parsing error, offending DOC:" + NL + docText); throw new Exception("Parsing error."); } for (Map.Entry<String, String> e : docFields.entrySet()) { //System.out.println(e.getKey() + " " + e.getValue()); objDocFields.put(e.getKey(), e.getValue()); } solrServer.indexDocument(objDocFields); if ((docNum - 1) % batchQty == 0) solrServer.indexCommit(); } solrServer.indexCommit(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }