List of usage examples for java.io PrintWriter flush
public void flush()
From source file:com.ifeng.sorter.NginxApp.java
public static void main(String[] args) { String input = "src/test/resources/data/nginx_report.txt"; PrintWriter pw = null; Map<String, List<LogBean>> resultMap = new HashMap<String, List<LogBean>>(); List<String> ips = new ArrayList<String>(); try {/* ww w .j a v a 2s. c om*/ List<String> lines = FileUtils.readLines(new File(input)); List<LogBean> items = new ArrayList<LogBean>(); for (String line : lines) { String[] values = line.split("\t"); if (values != null && values.length == 3) {// ip total seria try { String ip = values[0].trim(); String total = values[1].trim(); String seria = values[2].trim(); LogBean bean = new LogBean(ip, Integer.parseInt(total), seria); items.add(bean); } catch (NumberFormatException e) { e.printStackTrace(); } } } Collections.sort(items); for (LogBean bean : items) { String key = bean.getIp(); if (resultMap.containsKey(key)) { resultMap.get(key).add(bean); } else { List<LogBean> keyList = new ArrayList<LogBean>(); keyList.add(bean); resultMap.put(key, keyList); ips.add(key); } } pw = new PrintWriter("src/test/resources/output/result.txt", "UTF-8"); for (String ip : ips) { List<LogBean> list = resultMap.get(ip); for (LogBean bean : list) { pw.append(bean.toString()); pw.println(); } } } catch (IOException e) { e.printStackTrace(); } finally { pw.flush(); pw.close(); } }
From source file:at.tuwien.ifs.somtoolbox.apps.helper.VectorSimilarityWriter.java
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, SOMToolboxException { JSAPResult config = OptionFactory.parseResults(args, OptionFactory.OPTIONS_INPUT_SIMILARITY_COMPUTER); String inputVectorDistanceMatrix = config.getString("inputVectorDistanceMatrix"); String inputVectorFileName = config.getString("inputVectorFile"); int numNeighbours = config.getInt("numberNeighbours"); String outputFormat = config.getString("outputFormat"); InputVectorDistanceMatrix matrix = null; InputData data = new SOMLibSparseInputData(inputVectorFileName); if (StringUtils.isNotBlank(inputVectorDistanceMatrix)) { matrix = InputVectorDistanceMatrix.initFromFile(inputVectorDistanceMatrix); } else {/*from w w w. j a v a2 s.co m*/ String metricName = config.getString("metric"); DistanceMetric metric = AbstractMetric.instantiate(metricName); matrix = new LeightWeightMemoryInputVectorDistanceMatrix(data, metric); } String outputFileName = config.getString("output"); PrintWriter w = FileUtils.openFileForWriting("Similarity File", outputFileName); if (outputFormat.equals("SAT-DB")) { // find feature type String type = ""; if (inputVectorFileName.endsWith(".rh") || inputVectorFileName.endsWith(".rp") || inputVectorFileName.endsWith(".ssd")) { type = "_" + inputVectorFileName.substring(inputVectorFileName.lastIndexOf(".") + 1); } w.println("INSERT INTO `sat_track_similarity_ifs" + type + "` (`TRACKID`, `SIMILARITYCOUNT`, `SIMILARITYIDS`) VALUES "); } int numVectors = matrix.numVectors(); // numVectors = 10; // for testing StdErrProgressWriter progress = new StdErrProgressWriter(numVectors, "Writing similarities for vector ", 1); for (int i = 0; i < numVectors; i++) { int[] nearest = matrix.getNNearest(i, numNeighbours); if (outputFormat.equals("SAT-DB")) { w.print(" (" + i + " , NULL, '"); for (int j = 0; j < nearest.length; j++) { String label = data.getLabel(nearest[j]); w.print(label.replace(".mp3", "")); // strip ending if (j + 1 < nearest.length) { w.print(","); } else { w.print("')"); } } if (i + 1 < numVectors) { w.print(","); } } else { w.print(data.getLabel(i) + ","); for (int j = 0; j < nearest.length; j++) { w.print(data.getLabel(nearest[j])); if (j + 1 < nearest.length) { w.print(","); } } } w.println(); w.flush(); progress.progress(); } if (outputFormat.equals("SAT-DB")) { w.print(";"); } w.flush(); w.close(); }
From source file:com.basho.contact.ContactConsole.java
public static void main(String[] args) throws IOException { CommandLine commandLine = processArgs(args); ConsoleReader reader = new ConsoleReader(); reader.setBellEnabled(false);/* w w w . j av a 2s . c om*/ reader.setExpandEvents(false); // TODO: look into this // TODO: Pasting in text with tabs prints out a ton of completions //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords)); String line; PrintWriter out = new PrintWriter(System.out); DefaultConnectionProvider connections = new DefaultConnectionProvider(); RuntimeContext ctx = new RuntimeContext(connections, System.out, System.err); if (!commandLine.hasOption("nosignals")) { ConsoleSignalHander.install("INT", ctx); } ContactWalker walker = new ContactWalker(ctx); ContactAdminWalker adminWalker = new ContactAdminWalker(ctx); List<ContactBaseListener> walkers = new ArrayList<ContactBaseListener>(); walkers.add(walker); walkers.add(adminWalker); boolean nextLinePrompt = false; ANSIBuffer buf = new ANSIBuffer(); buf.setAnsiEnabled(!commandLine.hasOption("nocolor")); buf.blue("Welcome to Riak Contact\n"); buf.blue("(c) 2013 Dave Parfitt\n"); System.out.println(buf.toString()); if (!commandLine.hasOption("noconfig")) { String config = null; try { config = readConfig(); } catch (Exception e) { e.printStackTrace(); } if (config != null && !config.trim().isEmpty()) { processInput(config, walkers, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); } } if (commandLine.hasOption("infile")) { String filename = commandLine.getOptionValue("infile"); readInputFile(filename, walkers, ctx); ctx.getActionListener().term(); System.exit(0); } StringBuffer lines = new StringBuffer(); ANSIBuffer ansiprompt = new ANSIBuffer(); ansiprompt.setAnsiEnabled(true); ansiprompt.green("> "); String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor")); boolean inHereDoc = false; while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) { out.flush(); String chunks[] = line.split(" "); String consoleCommandCheck = chunks[0].toLowerCase().trim(); if (consoleOnlyCommands.containsKey(consoleCommandCheck)) { consoleOnlyCommands.get(consoleCommandCheck).run(line, reader); continue; } if (line.contains("~%~") && !line.contains("\\~%~")) { inHereDoc = !inHereDoc; } if (!line.trim().endsWith(";")) { nextLinePrompt = true; lines.append(line); lines.append("\n"); } else if (line.trim().endsWith(";") && !inHereDoc) { lines.append(line); String input = lines.toString(); nextLinePrompt = false; processInput(input, walkers, ctx); processOutput(ctx, out, !commandLine.hasOption("nocolor")); lines = new StringBuffer(); } else if (inHereDoc) { lines.append(line); lines.append("\n"); } } ctx.getActionListener().term(); }
From source file:com.medicaid.mmis.util.DataLoader.java
/** * The main function, imports the files given as arguments. * // w ww . j a v a 2s . co m * @param args the file names * @throws IOException for read/write errors * @throws PortalServiceException for any other errors */ public static void main(String[] args) throws IOException, PortalServiceException { if (args.length != 2) { System.out.println("2 file path arguments are required."); return; } PropertyConfigurator.configure("log4j.properties"); logger = Logger.getLogger(DataLoader.class); LookupServiceBean lookupBean = new LookupServiceBean(); EntityManagerFactory emf = Persistence.createEntityManagerFactory("cms-data-load"); EntityManager em = emf.createEntityManager(); lookupBean.setEm(em); DataLoader loader = new DataLoader(); loader.setLookup(lookupBean); SequenceGeneratorBean sequence = new SequenceGeneratorBean(); sequence.setEm(em); ProviderEnrollmentServiceBean enrollmentBean = new ProviderEnrollmentServiceBean(); enrollmentBean.setEm(em); enrollmentBean.setSequence(sequence); enrollmentBean.setLookupService(lookupBean); loader.setEnrollmentService(enrollmentBean); long processId = sequence.getNextValue("PROCESS_ID"); System.out.println("Started process id " + processId); BufferedReader br = null; PrintWriter accepted = null; PrintWriter rejected = null; try { System.out.println("Processing file 1..."); File success = new File("accepted_1_" + processId + ".txt"); File failure = new File("rejected_1_" + processId + ".txt"); success.createNewFile(); failure.createNewFile(); accepted = new PrintWriter(success); rejected = new PrintWriter(failure); br = new BufferedReader(new FileReader(args[0])); String line = null; int total = 0; int errors = 0; while ((line = br.readLine()) != null) { total++; try { em.getTransaction().begin(); loader.readProviderFile(new ByteArrayInputStream(line.getBytes())); em.getTransaction().commit(); accepted.println(line); logger.info("Commit row " + total); } catch (PortalServiceException e) { rejected.println(line); em.getTransaction().rollback(); errors++; logger.error("Rollback row " + total + " :" + e.getMessage()); } } accepted.flush(); accepted.close(); rejected.flush(); rejected.close(); br.close(); System.out.println("Total records read: " + total); System.out.println("Total rejected: " + errors); System.out.println("Processing file 2..."); success = new File("accepted_2_" + processId + ".txt"); failure = new File("rejected_2_" + processId + ".txt"); success.createNewFile(); failure.createNewFile(); accepted = new PrintWriter(success); rejected = new PrintWriter(failure); br = new BufferedReader(new FileReader(args[1])); line = null; total = 0; errors = 0; while ((line = br.readLine()) != null) { total++; try { em.getTransaction().begin(); Map<String, OwnershipInformation> owners = loader .readWS000EXT2OWNBEN(new ByteArrayInputStream(line.getBytes())); for (Map.Entry<String, OwnershipInformation> entry : owners.entrySet()) { enrollmentBean.addBeneficialOwners(entry.getKey(), entry.getValue()); } em.getTransaction().commit(); accepted.println(line); logger.info("Commit row " + total); } catch (PortalServiceException e) { rejected.println(line); em.getTransaction().rollback(); errors++; logger.error("Rollback row " + total + " :" + e.getMessage()); } } accepted.flush(); rejected.flush(); System.out.println("Total records read: " + total); System.out.println("Total rejected: " + errors); } finally { if (br != null) { br.close(); } if (accepted != null) { accepted.close(); } if (rejected != null) { rejected.close(); } } }
From source file:com.galois.fiveui.HeadlessRunner.java
/** * @param args list of headless run description filenames * @throws IOException//from www .ja v a2 s. co m * @throws URISyntaxException * @throws ParseException */ @SuppressWarnings("static-access") public static void main(final String[] args) throws IOException, URISyntaxException, ParseException { // Setup command line options Options options = new Options(); Option help = new Option("h", "print this help message"); Option output = OptionBuilder.withArgName("outfile").hasArg().withDescription("write output to file") .create("o"); Option report = OptionBuilder.withArgName("report directory").hasArg() .withDescription("write HTML reports to given directory").create("r"); options.addOption(output); options.addOption(report); options.addOption("v", false, "verbose output"); options.addOption("vv", false, "VERY verbose output"); options.addOption(help); // Parse command line options CommandLineParser parser = new GnuParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println("Command line option parsing failed. Reason: " + e.getMessage()); System.exit(1); } // Display help if requested if (cmd.hasOption("h")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("headless <input file 1> [<input file 2> ...]", options); System.exit(1); } // Set logging levels BasicConfigurator.configure(); Logger fiveuiLogger = Logger.getLogger("com.galois.fiveui"); Logger rootLogger = Logger.getRootLogger(); if (cmd.hasOption("v")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.ERROR); } else if (cmd.hasOption("vv")) { fiveuiLogger.setLevel(Level.DEBUG); rootLogger.setLevel(Level.DEBUG); } else { fiveuiLogger.setLevel(Level.ERROR); rootLogger.setLevel(Level.ERROR); } // Setup output file if requested PrintWriter outStream = null; if (cmd.hasOption("o")) { String outfile = cmd.getOptionValue("o"); try { outStream = new PrintWriter(new BufferedWriter(new FileWriter(outfile))); } catch (IOException e) { System.err.println("Could not open outfile for writing: " + cmd.getOptionValue("outfile")); System.exit(1); } } else { outStream = new PrintWriter(new BufferedWriter(new PrintWriter(System.out))); } // Setup HTML reports directory before the major work happens in case we // have to throw an exception. PrintWriter summaryFile = null; PrintWriter byURLFile = null; PrintWriter byRuleFile = null; if (cmd.hasOption("r")) { String repDir = cmd.getOptionValue("r"); try { File file = new File(repDir); if (!file.exists()) { file.mkdir(); logger.info("report directory created: " + repDir); } else { logger.info("report directory already exists!"); } summaryFile = new PrintWriter(new FileWriter(repDir + File.separator + "summary.html")); byURLFile = new PrintWriter(new FileWriter(repDir + File.separator + "byURL.html")); byRuleFile = new PrintWriter(new FileWriter(repDir + File.separator + "byRule.html")); } catch (IOException e) { System.err.println("could not open report directory / files for writing"); System.exit(1); } } // Major work: process input files ImmutableList<Result> results = null; for (String in : cmd.getArgs()) { HeadlessRunDescription descr = HeadlessRunDescription.parse(in); logger.debug("invoking headless run..."); BatchRunner runner = new BatchRunner(); results = runner.runHeadless(descr); logger.debug("runHeadless returned " + results.size() + " results"); // write results to the output stream as we go for (Result result : results) { outStream.println(result.toString()); } outStream.flush(); } outStream.close(); // Write report files if requested if (cmd.hasOption("r") && results != null) { Reporter kermit = new Reporter(results); summaryFile.write(kermit.getSummary()); summaryFile.close(); byURLFile.write(kermit.getByURL()); byURLFile.close(); byRuleFile.write(kermit.getByRule()); byRuleFile.close(); } }
From source file:whitebox.stats.Kriging.java
public static void main(String[] args) { try {/*from w w w . java 2 s. co m*/ //ChartPanel(createChart(createDataset())); Kriging k = new Kriging(); k.readPointFile("/Users/johnlindsay/Documents/Data/Krigging Test Data/test.shp", "Z"); k.ConsiderNugget = false; k.LagSize = 50; k.NumberOfLags = 100; k.Anisotropic = true; k.Tolerance = Math.PI / 4; k.BandWidth = 5000; PrintWriter pw = new PrintWriter("/Users/johnlindsay/Documents/Data/Krigging Test Data/test.txt"); for (int i = 0; i < 13; i++) { k.Angle = Math.PI / 12.0 * i; Variogram var = k.getSemivariogram(SemivariogramType.SPHERICAL, 1, k.NumberOfLags, true, true); pw.println(k.Angle + "," + var.Range + "," + var.Sill + "," + var.Nugget); pw.flush(); System.out.println((i + 1) + " of 12"); } System.out.println("Done!"); } catch (Exception e) { } // k.ConsiderNugget = false; // k.Points = k.ReadPointFile( // "G:\\Optimized Sensory Network\\PALS\\20120607\\test.shp","Z"); // k.LagSize = 2000; // k.Anisotropic = false; // Variogram var = k.SemiVariogram(SemiVariogramType.Spherical, 0.27, 50,false, true); // // //var.Range = 4160.672768; // //var.Sill = 1835.571948; // // k.resolution = 914; // k.BMinX = 588450 + k.resolution/2; // k.BMaxX = 601246 - k.resolution/2; // k.BMinY = 5474650 + k.resolution/2; // k.BMaxY = 5545942 - k.resolution/2; // // List<KrigingPoint> outPnts = k.calcInterpolationPoints() ; // outPnts = k.InterpolatePoints(var, outPnts, 5); // k.BuildRaster("G:\\Optimized Sensory Network\\PALS\\20120607\\Pnts60.dep", outPnts,false); // k.BuildRaster("G:\\Optimized Sensory Network\\PALS\\20120607\\PntsVar60.dep", outPnts,true); // // k.DrawSemiVariogram(k.bins, var); //k.calcBinSurface(SemiVariogramType.Spherical, 1, 99,false); //k.DrawSemiVariogramSurface(k.LagSize*(k.NumberOfLags), false); // k.LagSize = 2500; // k.Anisotropic = false; //// k.Angle = Math.PI*3/4; //// k.Tolerance = Math.PI/4; //// k.BandWidth = 3*k.LagSize; // for (int i = 0; i < 50; i++) { // k.Points = k.ReadPointFile("G:\\Optimized Sensory Network\\PALS\\Pals Shapefiles\\PALS_TA_20120607_HiAlt_v100.shp","h"); // k.Points = k.RandomizePoints(k.Points, 200); // Variogram var = k.SemiVariogram(SemiVariogramType.Spherical, 1, 25,false); // k.resolution = 900; // List<KrigingPoint> pnts = k.calcInterpolationPoints(); // pnts = k.InterpolatePoints(var, pnts, 5); // k.BuildRaster("G:\\Optimized Sensory Network\\PALS\\Pals Shapefiles\\PALS_TA_20120607_HiAlt_v100"+ i +".dep", pnts); // } //k.DrawSemiVariogram(k.bins, var); //k.calcBinSurface(SemiVariogramType.Spherical, 0.27, 25,false); //k.DrawSemiVariogramSurface(k.LagSize*(k.NumberOfLags),false); //k.Points = k.ReadPointFile("G:\\Papers\\AGU 2013\\Sample\\Sample.shp","V"); //k.Points = k.ReadPointFile("G:\\Papers\\AGU 2013\\WakerLake\\WakerLake.shp","V"); // String s= new String(); // PrintWriter pw = null ; // try { // pw = new PrintWriter("G:\\test.txt"); // } catch (FileNotFoundException ex) { // Logger.getLogger(Kriging.class.getName()).log(Level.SEVERE, null, ex); // } // // for (int i = 0; i < 500; i++) { // Kriging k = new Kriging(); // k.ConsiderNugget = false; // k.LagSize = 50; // k.Anisotropic = true; // k.Angle = Math.PI*3/4; // k.Tolerance = Math.PI/4; // k.BandWidth = 3*k.LagSize; // k.Points = k.ReadPointFile("G:\\Optimized Sensory Network\\PALS\\AGU\\SV_Test.shp","v"); // k.Points = k.RandomizePoints(k.Points, 500); // Variogram var = k.SemiVariogram(SemiVariogramType.Exponential, 0.27, 99,true); // s = var.Range + " , " + var.Sill; // // // pw.println(s); // pw.flush(); // k = null; // } // pw.close();; //k.resolution = 2.5; //k.DrawSemiVariogram(k.bins, var); //List<point> pnts = k.calcInterpolationPoints(); // var.Range = 50; // var.Sill = 104843.2; // var.Type = SemiVariogramType.Exponential; // // //pnts = k.InterpolatePoints(var, pnts,10); //k.BuildRaster("G:\\Papers\\AGU 2013\\WakerLake\\WakerLakeOut15.dep", pnts); //k.calcBinSurface(SemiVariogramType.Exponential, 0.27, 99,false); //k.DrawSemiVariogramSurface(k.LagSize*(k.NumberOfLags),true); //Kriging.point p = k.point(65, 137, 0); // List<Kriging.point> pnts = new ArrayList(); // pnts.add(p); }
From source file:com.bluemarsh.jswat.console.Main.java
/** * Kicks off the application.// w w w .j a va 2 s. c o m * * @param args the command line arguments. */ public static void main(String[] args) { // // An attempt was made early on to use the Console class in java.io, // but that is not designed to handle asynchronous output from // multiple threads, so we just use the usual System.out for output // and System.in for input. Note that automatic flushing is used to // ensure output is shown in a timely fashion. // // // Where console mode seems to work: // - bash // - emacs // // Where console mode does not seem to work: // - NetBeans: output from event listeners is never shown and the // cursor sometimes lags behind the output // // Turn on flushing so printing the prompt will flush // all buffered output generated from other threads. PrintWriter output = new PrintWriter(System.out, true); // Make sure we have the JPDA classes. try { Bootstrap.virtualMachineManager(); } catch (NoClassDefFoundError ncdfe) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_NoJPDA")); System.exit(1); } // Ensure we can create the user directory by requesting the // platform service. Simply asking for it has the desired effect. PlatformProvider.getPlatformService(); // Define the logging configuration. LogManager manager = LogManager.getLogManager(); InputStream is = Main.class.getResourceAsStream("logging.properties"); try { manager.readConfiguration(is); } catch (IOException ioe) { ioe.printStackTrace(); System.exit(1); } // Print out some useful debugging information. logSystemDetails(); // Add a shutdown hook to make sure we exit cleanly. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { // Save the command aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.saveSettings(); // Save the runtimes to persistent storage. RuntimeManager rm = RuntimeProvider.getRuntimeManager(); rm.saveRuntimes(); // Save the sessions to persistent storage and have them // close down in preparation to exit. SessionManager sm = SessionProvider.getSessionManager(); sm.saveSessions(true); } })); // Initialize the command parser and load the aliases. CommandParser parser = CommandProvider.getCommandParser(); parser.loadSettings(); parser.setOutput(output); // Create an OutputAdapter to display debuggee output. OutputAdapter adapter = new OutputAdapter(output); SessionManager sessionMgr = SessionProvider.getSessionManager(); sessionMgr.addSessionManagerListener(adapter); // Create a SessionWatcher to monitor the session status. SessionWatcher swatcher = new SessionWatcher(); sessionMgr.addSessionManagerListener(swatcher); // Create a BreakpointWatcher to monitor the breakpoints. BreakpointWatcher bwatcher = new BreakpointWatcher(); sessionMgr.addSessionManagerListener(bwatcher); // Add the watchers and adapters to the open sessions. Iterator<Session> iter = sessionMgr.iterateSessions(); while (iter.hasNext()) { Session s = iter.next(); s.addSessionListener(adapter); s.addSessionListener(swatcher); } // Find and run the RC file. try { runStartupFile(parser, output); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); } // Process command line arguments. try { processArguments(args); } catch (ParseException pe) { // Report the problem and keep going. System.err.println("Option parsing failed: " + pe.getMessage()); logger.log(Level.SEVERE, null, pe); } // Display a helpful greeting. output.println(NbBundle.getMessage(Main.class, "MSG_Main_Welcome")); if (jdbEmulationMode) { output.println(NbBundle.getMessage(Main.class, "MSG_Main_Jdb_Emulation")); } // Enter the main loop of processing user input. BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); while (true) { // Keep the prompt format identical to jdb for compatibility // with emacs and other possible wrappers. output.print("> "); output.flush(); try { String command = input.readLine(); // A null value indicates end of stream. if (command != null) { performCommand(output, parser, command); } // Sleep briefly to give the event processing threads, // and the automatic output flushing, a chance to catch // up before printing the input prompt again. Thread.sleep(250); } catch (InterruptedException ie) { logger.log(Level.WARNING, null, ie); } catch (IOException ioe) { logger.log(Level.SEVERE, null, ioe); output.println(NbBundle.getMessage(Main.class, "ERR_Main_IOError", ioe)); } catch (Exception x) { // Don't ever let an internal bug (e.g. in the command parser) // hork the console, as it really irritates people. logger.log(Level.SEVERE, null, x); output.println(NbBundle.getMessage(Main.class, "ERR_Main_Exception", x)); } } }
From source file:DataCrawler.OpenAIRE.XMLGenerator.java
public static void main(String[] args) { String text = ""; try {//www . j a va2 s . c om if (args.length < 4) { System.out.println("<command> template_file csv_file output_dir log_file [start_id]"); } // InputStream fis = new FileInputStream("E:/Downloads/result-r-00000"); InputStream fis = new FileInputStream(args[1]); BufferedReader br = new BufferedReader(new InputStreamReader(fis, Charset.forName("UTF-8"))); // String content = new String(Files.readAllBytes(Paths.get("publications_template.xml"))); String content = new String(Files.readAllBytes(Paths.get(args[0]))); Document doc = Jsoup.parse(content, "UTF-8", Parser.xmlParser()); // String outputDirectory = "G:/"; String outputDirectory = args[2]; // PrintWriter logWriter = new PrintWriter(new FileOutputStream("publication.log",false)); PrintWriter logWriter = new PrintWriter(new FileOutputStream(args[3], false)); Element objectId = null, title = null, publisher = null, dateofacceptance = null, bestlicense = null, resulttype = null, originalId = null, originalId2 = null; boolean start = true; // String startID = "dedup_wf_001::207a098867b64f3b5af505fa3aeecd24"; String startID = ""; if (args.length >= 5) { start = false; startID = args[4]; } String previousText = ""; while ((text = br.readLine()) != null) { /* For publications: 0. dri:objIdentifier context 9. title context 12. publisher context 18. dateofacceptance 19. bestlicense @classname 21. resulttype @classname 26. originalId context (Notice that the prefix is null and will use space to separate two different "originalId") */ if (!previousText.isEmpty()) { text = previousText + text; start = true; previousText = ""; } String[] items = text.split("!"); for (int i = 0; i < items.length; ++i) { items[i] = StringUtils.strip(items[i], "#"); } if (objectId == null) objectId = doc.getElementsByTag("dri:objIdentifier").first(); objectId.text(items[0]); if (!start && items[0].equals(startID)) { start = true; } if (title == null) title = doc.getElementsByTag("title").first(); title.text(items[9]); if (publisher == null) publisher = doc.getElementsByTag("publisher").first(); if (items.length < 12) { previousText = text; continue; } publisher.text(items[12]); if (dateofacceptance == null) dateofacceptance = doc.getElementsByTag("dateofacceptance").first(); dateofacceptance.text(items[18]); if (bestlicense == null) bestlicense = doc.getElementsByTag("bestlicense").first(); bestlicense.attr("classname", items[19]); if (resulttype == null) resulttype = doc.getElementsByTag("resulttype").first(); resulttype.attr("classname", items[21]); if (originalId == null || originalId2 == null) { Elements elements = doc.getElementsByTag("originalId"); String[] context = items[26].split(" "); if (elements.size() > 0) { if (elements.size() >= 1) { originalId = elements.get(0); if (context.length >= 1) { int indexOfnull = context[0].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[0].trim().length() >= (indexOfnull + 5)) value = context[0].trim().substring(indexOfnull + 5); } else { value = context[0].trim(); } originalId.text(value); } } if (elements.size() >= 2) { originalId2 = elements.get(1); if (context.length >= 2) { int indexOfnull = context[1].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[1].trim().length() >= (indexOfnull + 5)) value = context[1].trim().substring(indexOfnull + 5); } else { value = context[1].trim(); } originalId2.text(value); } } } } else { String[] context = items[26].split(" "); if (context.length >= 1) { int indexOfnull = context[0].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[0].trim().length() >= (indexOfnull + 5)) value = context[0].trim().substring(indexOfnull + 5); } else { value = context[0].trim(); } originalId.text(value); } if (context.length >= 2) { int indexOfnull = context[1].trim().indexOf("null"); String value = ""; if (indexOfnull != -1) { if (context[1].trim().length() >= (indexOfnull + 5)) value = context[1].trim().substring(indexOfnull + 5); } else { value = context[1].trim(); } originalId2.text(value); } } if (start) { String filePath = outputDirectory + items[0].replace(":", "#") + ".xml"; PrintWriter writer = new PrintWriter(new FileOutputStream(filePath, false)); logWriter.write(filePath + " > Start" + System.lineSeparator()); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + System.lineSeparator()); writer.write(doc.getElementsByTag("response").first().toString()); writer.close(); logWriter.write(filePath + " > OK" + System.lineSeparator()); logWriter.flush(); } } logWriter.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:client.QueryLastFm.java
License:asdf
public static void main(String[] args) throws Exception { // isAlreadyInserted("asdfs","jas,jnjkah"); // FileWriter fw = new FileWriter(".\\tracks.csv"); OutputStream track_os = new FileOutputStream(".\\tracks.csv"); PrintWriter out = new PrintWriter(new OutputStreamWriter(track_os, "UTF-8")); OutputStream track_id_os = new FileOutputStream(".\\track_id_sim_track_id.csv"); PrintWriter track_id_out = new PrintWriter(new OutputStreamWriter(track_id_os, "UTF-8")); track_id_out.print(""); ByteArrayInputStream input;// w ww . j a va 2s .co m Document doc = null; CloseableHttpClient httpclient = HttpClients.createDefault(); String trackName = ""; String artistName = ""; String sourceMbid = ""; out.print("ID");// first row first column out.print(","); out.print("TrackName");// first row second column out.print(","); out.println("Artist");// first row third column track_id_out.print("source");// first row second column track_id_out.print(","); track_id_out.println("target");// first row third column // track_id_out.print(","); // track_id_out.println("type");// first row third column // out.flush(); // out.close(); // fw.close(); // os.close(); try { URI uri = new URIBuilder().setScheme("http").setHost("ws.audioscrobbler.com").setPath("/2.0/") .setParameter("method", "track.getsimilar").setParameter("artist", "cher") .setParameter("track", "believe").setParameter("limit", "100") .setParameter("api_key", "88858618961414f8bec919bddd057044").build(); // new URIBuilder(). HttpGet request = new HttpGet(uri); // request. // This is useful for last.fm logging and preventing them from blocking this client request.setHeader(HttpHeaders.USER_AGENT, "nileshmore@gatech.edu - ClassAssignment at GeorgiaTech Non-commercial use"); HttpGet httpGet = new HttpGet( "http://ws.audioscrobbler.com/2.0/?method=track.getsimilar&artist=cher&track=believe&limit=4&api_key=88858618961414f8bec919bddd057044"); CloseableHttpResponse response = httpclient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); // The underlying HTTP connection is still held by the response object // to allow the response content to be streamed directly from the network socket. // In order to ensure correct deallocation of system resources // the user MUST call CloseableHttpResponse#close() from a finally clause. // Please note that if response content is not fully consumed the underlying // connection cannot be safely re-used and will be shut down and discarded // by the connection manager. try { if (statusCode == 200) { HttpEntity entity1 = response.getEntity(); BufferedReader br = new BufferedReader( new InputStreamReader((response.getEntity().getContent()))); Document document = builder.parse((response.getEntity().getContent())); Element root = document.getDocumentElement(); root.normalize(); // Need to focus and resolve this part NodeList nodes; nodes = root.getChildNodes(); nodes = root.getElementsByTagName("track"); if (nodes.getLength() == 0) { // System.out.println("empty"); return; } Node trackNode; for (int k = 0; k < nodes.getLength(); k++) // can access all tracks now { trackNode = nodes.item(k); NodeList trackAttributes = trackNode.getChildNodes(); // check if mbid is present in track attributes // System.out.println("Length " + (trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)); if ((trackAttributes.item(5).getNodeName().compareToIgnoreCase("mbid") == 0)) { if (((Element) trackAttributes.item(5)).hasChildNodes()) ;// System.out.println("Go aHead"); else continue; } else continue; for (int n = 0; n < trackAttributes.getLength(); n++) { Node attribute = trackAttributes.item(n); if ((attribute.getNodeName().compareToIgnoreCase("name")) == 0) { // System.out.println(((Element)attribute).getFirstChild().getNodeValue()); trackName = ((Element) attribute).getFirstChild().getNodeValue(); // make string encoding as UTF-8 ************ } if ((attribute.getNodeName().compareToIgnoreCase("mbid")) == 0) { // System.out.println(n + " " + ((Element)attribute).getFirstChild().getNodeValue()); sourceMbid = attribute.getFirstChild().getNodeValue(); } if ((attribute.getNodeName().compareToIgnoreCase("artist")) == 0) { NodeList ArtistNodeList = attribute.getChildNodes(); for (int j = 0; j < ArtistNodeList.getLength(); j++) { Node Artistnode = ArtistNodeList.item(j); if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) { // System.out.println(((Element)Artistnode).getFirstChild().getNodeValue()); artistName = ((Element) Artistnode).getFirstChild().getNodeValue(); } } } } out.print(sourceMbid); out.print(","); out.print(trackName); out.print(","); out.println(artistName); // out.print(","); findSimilarTracks(track_id_out, sourceMbid, trackName, artistName); } track_id_out.flush(); out.flush(); out.close(); track_id_out.close(); track_os.close(); // fw.close(); Element trac = (Element) nodes.item(0); // trac.normalize(); nodes = trac.getChildNodes(); // System.out.println(nodes.getLength()); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); // System.out.println(node.getNodeName()); if ((node.getNodeName().compareToIgnoreCase("name")) == 0) { // System.out.println(((Element)node).getFirstChild().getNodeValue()); } if ((node.getNodeName().compareToIgnoreCase("mbid")) == 0) { // System.out.println(((Element)node).getFirstChild().getNodeValue()); } if ((node.getNodeName().compareToIgnoreCase("artist")) == 0) { // System.out.println("Well"); NodeList ArtistNodeList = node.getChildNodes(); for (int j = 0; j < ArtistNodeList.getLength(); j++) { Node Artistnode = ArtistNodeList.item(j); if ((Artistnode.getNodeName().compareToIgnoreCase("name")) == 0) { /* System.out.println(((Element)Artistnode).getFirstChild().getNodeValue());*/ } /*System.out.println(Artistnode.getNodeName());*/ } } } /*if(node instanceof Element){ //a child element to process Element child = (Element) node; String attribute = child.getAttribute("width"); }*/ // System.out.println(root.getAttribute("status")); NodeList tracks = root.getElementsByTagName("track"); Element track = (Element) tracks.item(0); // System.out.println(track.getTagName()); track.getChildNodes(); } else { System.out.println("failed with status" + response.getStatusLine()); } // input = (ByteArrayInputStream)entity1.getContent(); // do something useful with the response body // and ensure it is fully consumed } finally { response.close(); } } finally { System.out.println("Exited succesfully."); httpclient.close(); } }
From source file:Main.java
public static String getStackTrace(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); t.printStackTrace(pw);//from w w w . ja v a2 s .c om pw.flush(); sw.flush(); return sw.toString(); }