List of usage examples for java.io PrintWriter close
public void close()
From source file:EchoClient.java
public static void main(String[] args) throws IOException { Socket kkSocket = null;/*from w w w . jav a2 s. com*/ PrintWriter out = null; BufferedReader in = null; try { kkSocket = new Socket("taranis", 4444); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.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 fromServer; String fromUser; while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer); if (fromServer.equals("Bye.")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } } out.close(); in.close(); stdIn.close(); kkSocket.close(); }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step7aLearningDataProducer.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws IOException { String inputDir = args[0];//w w w . jav a2 s . c o m File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); // for generating ConvArgStrict use this String prefix = "no-eq_DescendingScoreArgumentPairListSorter"; // for oversampling using graph transitivity properties use this // String prefix = "generated_no-eq_AscendingScoreArgumentPairListSorter"; Iterator<File> iterator = files.iterator(); while (iterator.hasNext()) { File file = iterator.next(); if (!file.getName().startsWith(prefix)) { iterator.remove(); } } int totalGoldPairsCounter = 0; Map<String, Integer> goldDataDistribution = new HashMap<>(); DescriptiveStatistics statsPerTopic = new DescriptiveStatistics(); int totalPairsWithReasonSameAsGold = 0; DescriptiveStatistics ds = new DescriptiveStatistics(); for (File file : files) { List<AnnotatedArgumentPair> argumentPairs = (List<AnnotatedArgumentPair>) XStreamTools.getXStream() .fromXML(file); int pairsPerTopicCounter = 0; String name = file.getName().replaceAll(prefix, "").replaceAll("\\.xml", ""); PrintWriter pw = new PrintWriter(new File(outputDir, name + ".csv"), "utf-8"); pw.println("#id\tlabel\ta1\ta2"); for (AnnotatedArgumentPair argumentPair : argumentPairs) { String goldLabel = argumentPair.getGoldLabel(); if (!goldDataDistribution.containsKey(goldLabel)) { goldDataDistribution.put(goldLabel, 0); } goldDataDistribution.put(goldLabel, goldDataDistribution.get(goldLabel) + 1); pw.printf(Locale.ENGLISH, "%s\t%s\t%s\t%s%n", argumentPair.getId(), goldLabel, multipleParagraphsToSingleLine(argumentPair.getArg1().getText()), multipleParagraphsToSingleLine(argumentPair.getArg2().getText())); pairsPerTopicCounter++; int sameInOnePair = 0; // get gold reason statistics for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { String label = assignment.getValue(); if (goldLabel.equals(label)) { sameInOnePair++; } } ds.addValue(sameInOnePair); totalPairsWithReasonSameAsGold += sameInOnePair; } totalGoldPairsCounter += pairsPerTopicCounter; statsPerTopic.addValue(pairsPerTopicCounter); pw.close(); } System.out.println("Total reasons matching gold " + totalPairsWithReasonSameAsGold); System.out.println(ds); System.out.println("Total gold pairs: " + totalGoldPairsCounter); System.out.println(statsPerTopic); int totalPairs = 0; for (Integer pairs : goldDataDistribution.values()) { totalPairs += pairs; } System.out.println("Total pairs: " + totalPairs); System.out.println(goldDataDistribution); }
From source file:Trace.java
public static void main(String[] args) throws java.io.IOException, TransformerException, TransformerConfigurationException, java.util.TooManyListenersException, org.xml.sax.SAXException { String fileName = "foo"; if (args.length > 0) fileName = args[0];//from w w w . j a v a 2 s . com // Set up a PrintTraceListener object to print to a file. java.io.FileWriter fw = new java.io.FileWriter("events.log"); java.io.PrintWriter pw = new java.io.PrintWriter(fw, true); PrintTraceListener ptl = new PrintTraceListener(pw); // Print information as each node is 'executed' in the stylesheet. ptl.m_traceElements = true; // Print information after each result-tree generation event. ptl.m_traceGeneration = true; // Print information after each selection event. ptl.m_traceSelection = true; // Print information whenever a template is invoked. ptl.m_traceTemplates = true; // Print information whenever an extension call is made. ptl.m_traceExtension = true; // Set up the transformation TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(new StreamSource(fileName + ".xsl")); // Cast the Transformer object to TransformerImpl. if (transformer instanceof TransformerImpl) { TransformerImpl transformerImpl = (TransformerImpl) transformer; // Register the TraceListener with a TraceManager associated // with the TransformerImpl. TraceManager trMgr = transformerImpl.getTraceManager(); trMgr.addTraceListener(ptl); // Perform the transformation --printing information to // the events log during the process. transformer.transform(new StreamSource(fileName + ".xml"), new StreamResult(new java.io.FileWriter(fileName + ".out"))); } // Close the PrintWriter and FileWriter. pw.close(); fw.close(); System.out.println("**The output is in " + fileName + ".out; the log is in events.log ****"); }
From source file:ArrayFile.java
public static void main(String[] args) throws Exception { PrintWriter out = new PrintWriter(new FileWriter("arrayfile.txt")); CaBioApplicationService appService = (CaBioApplicationService) ApplicationServiceProvider .getApplicationServiceFromUrl("http://cabioapi-qa.nci.nih.gov/cabio42"); ArrayAnnotationService am = new ArrayAnnotationServiceImpl(appService); String arrayName = "HG-U133_Plus_2"; Collection<ArrayReporter> reps = am.getReportersForPlatform(arrayName); out.println("Name\tSymbol\tHUGO Symbol\tUnigene Id\t" + "Sequence Type\tSequence Source\tTarget Id\t" + "Target Description\tCytoband\tChromosome\tStart\tEnd"); int c = 0;// w w w.ja v a2 s . c o m for (ArrayReporter rep : reps) { ExpressionArrayReporter er = (ExpressionArrayReporter) rep; out.println(resolve(er, "name") + "\t" + resolve(er, "gene.symbol") + "\t" + resolve(er, "gene.hugoSymbol") + "\t" + resolve(er, "gene.clusterId") + "\t" + resolve(er, "sequenceType") + "\t" + resolve(er, "sequenceSource") + "\t" + resolve(er, "targetId") + "\t" + resolve(er, "targetDescription") + "\t" + resolve(er, "cytogeneticLocationCollection[0].startCytoband.name") + "\t" + resolve(er, "physicalLocationCollection[0].chromosome.number") + "\t" + resolve(er, "physicalLocationCollection[0].chromosomalStartPosition") + "\t" + resolve(er, "physicalLocationCollection[0].chromosomalEndPosition")); if (c++ > 500) break; } out.close(); }
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 {/*from w w w . j av a2 s .c o m*/ 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:eval.dataset.ParseWikiLog.java
public static void main(String[] ss) throws FileNotFoundException, ParserConfigurationException, IOException { FileInputStream fin = new FileInputStream("data/enwiki-20151201-pages-logging.xml.gz"); GzipCompressorInputStream gzIn = new GzipCompressorInputStream(fin); InputStreamReader reader = new InputStreamReader(gzIn); BufferedReader br = new BufferedReader(reader); PrintWriter pw = new PrintWriter(new FileWriter("data/user_page.txt")); pw.println(/*www. j av a2 s . c o m*/ "#list of user names and pages that they have edited, deleted or created. These info are mined from logitems of enwiki-20150304-pages-logging.xml.gz"); TreeMap<String, Set<String>> userPageList = new TreeMap(); TreeSet<String> pageList = new TreeSet(); int counterEntry = 0; String currentUser = null; String currentPage = null; try { for (String line = br.readLine(); line != null; line = br.readLine()) { if (line.trim().equals("</logitem>")) { counterEntry++; if (currentUser != null && currentPage != null) { updateMap(userPageList, currentUser, currentPage); pw.println(currentUser + "\t" + currentPage); pageList.add(currentPage); } currentUser = null; currentPage = null; } else if (line.trim().startsWith("<username>")) { currentUser = line.trim().split(">")[1].split("<")[0].replace(" ", "_"); } else if (line.trim().startsWith("<logtitle>")) { String content = line.trim().split(">")[1].split("<")[0]; if (content.split(":").length == 1) { currentPage = content.replace(" ", "_"); } } } } catch (IOException ex) { Logger.getLogger(ParseWikiLog.class.getName()).log(Level.SEVERE, null, ex); } pw.println("#analysed " + counterEntry + " entries of wikipesia log file"); pw.println("#gathered a list of unique user of size " + userPageList.size()); pw.println("#gathered a list of pages of size " + pageList.size()); pw.close(); gzIn.close(); PrintWriter pwUser = new PrintWriter(new FileWriter("data/user_list_page_edited.txt")); pwUser.println( "#list of unique users and pages that they have edited, extracted from logitems of enwiki-20150304-pages-logging.xml.gz"); for (String user : userPageList.keySet()) { pwUser.print(user); Set<String> getList = userPageList.get(user); for (String page : getList) { pwUser.print("\t" + page); } pwUser.println(); } pwUser.close(); PrintWriter pwPage = new PrintWriter(new FileWriter("data/all_pages.txt")); pwPage.println("#list of the unique pages that are extracted from enwiki-20150304-pages-logging.xml.gz"); for (String page : pageList) { pwPage.println(page); } pwPage.close(); System.out.println("#analysed " + counterEntry + " entries of wikipesia log file"); System.out.println("#gathered a list of unique user of size " + userPageList.size()); System.out.println("#gathered a list of pages of size " + pageList.size()); }
From source file:com.annuletconsulting.homecommand.server.HomeCommand.java
/** * This class will accept commands from a node in each room. For it to react to events on the server * computer, it must be also running as a node. However the server can cause all nodes to react * to an event happening on any node, such as an email or text arriving. A call on a node device * could pause all music devices, for example. * /*from w ww.j ava2 s . com*/ * @param args */ public static void main(String[] args) { try { socket = Integer.parseInt(HomeComandProperties.getInstance().getServerPort()); nonJavaUserModulesPath = HomeComandProperties.getInstance().getNonJavaUserDir(); } catch (Exception exception) { System.out.println("Error loading from properties file."); exception.printStackTrace(); } try { sharedKey = HomeComandProperties.getInstance().getSharedKey(); if (sharedKey == null) System.out.println("shared_key is null, commands without valid signatures will be processed."); } catch (Exception exception) { System.out.println("shared_key not found in properties file."); exception.printStackTrace(); } try { if (args.length > 0) { String arg0 = args[0]; if (arg0.equals("help") || arg0.equals("?") || arg0.equals("usage") || arg0.equals("-help") || arg0.equals("-?")) { System.out.println( "The defaults can be changed by editing the HomeCommand.properties file, or you can override them temporarily using command line options."); System.out.println("\nHome Command Server command line overrride usage:"); System.out.println( "hcserver [server_port] [java_user_module_directory] [non_java_user_module_directory]"); //TODO make hcserver.sh System.out.println("\nDefaults:"); System.out.println("server_port: " + socket); System.out.println("java_user_module_directory: " + userModulesPath); System.out.println("non_java_user_module_directory: " + nonJavaUserModulesPath); System.out.println("\n2013 | Annulet, LLC"); } socket = Integer.parseInt(arg0); } if (args.length > 1) userModulesPath = args[1]; if (args.length > 2) nonJavaUserModulesPath = args[2]; System.out.println("Config loaded, initializing modules."); modules.add(new HueLightModule()); System.out.println("HueLightModule initialized."); modules.add(new QuestionModule()); System.out.println("QuestionModule initialized."); modules.add(new MathModule()); System.out.println("MathModule initialized."); modules.add(new MusicModule()); System.out.println("MusicModule initialized."); modules.add(new NonCopyrightInfringingGenericSpaceExplorationTVShowModule()); System.out.println("NonCopyrightInfringingGenericSpaceExplorationTVShowModule initialized."); modules.add(new HelpModule()); System.out.println("HelpModule initialized."); modules.add(new SetUpModule()); System.out.println("SetUpModule initialized."); modules.addAll(NonJavaUserModuleLoader.loadModulesAt(nonJavaUserModulesPath)); System.out.println("NonJavaUserModuleLoader initialized."); ServerSocket serverSocket = new ServerSocket(socket); System.out.println("Listening..."); while (!end) { Socket socket = serverSocket.accept(); InputStreamReader isr = new InputStreamReader(socket.getInputStream()); PrintWriter output = new PrintWriter(socket.getOutputStream(), true); int character; StringBuffer inputStrBuffer = new StringBuffer(); while ((character = isr.read()) != 13) { inputStrBuffer.append((char) character); } System.out.println(inputStrBuffer.toString()); String[] cmd; // = inputStrBuffer.toString().split(" "); String result = "YOUR REQUEST WAS NOT VALID JSON"; if (inputStrBuffer.substring(0, 1).equals("{")) { nodeType = extractElement(inputStrBuffer.toString(), "node_type"); if (sharedKey != null) { if (validateSignature(extractElement(inputStrBuffer.toString(), "time_stamp"), extractElement(inputStrBuffer.toString(), "signature"))) { if ("Y".equalsIgnoreCase(extractElement(inputStrBuffer.toString(), "cmd_encoded"))) cmd = decryptCommand(extractElement(inputStrBuffer.toString(), "command")); else cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } else result = "YOUR SIGNATURE DID NOT MATCH, CHECK SHARED KEY"; } else { cmd = extractElement(inputStrBuffer.toString(), "command").split(" "); result = getResult(cmd); } } System.out.println(result); output.print(result); output.print((char) 13); output.close(); isr.close(); socket.close(); } serverSocket.close(); System.out.println("Shutting down."); } catch (Exception exception) { exception.printStackTrace(); } }
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 ww.java 2 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:microbiosima.Microbiosima.java
/** * @param args//from w w w . j av a 2s .co m * the command line arguments * @throws java.io.FileNotFoundException * @throws java.io.UnsupportedEncodingException */ public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException { //Init with default values int populationSize = 500; int microSize = 1000; int numberOfSpecies = 150; int numberOfGeneration = 10000; int numberOfObservation = 100; int numberOfReplication = 1; double pctEnv = 0; double pctPool = 0; Options options = new Options(); Option help = new Option("h", "help", false, "print this message"); Option version = new Option("v", "version", false, "print the version information and exit"); options.addOption(help); options.addOption(version); options.addOption(Option.builder("o").longOpt("obs").hasArg().argName("OBS") .desc("Number generation for observation [default: 100]").build()); options.addOption(Option.builder("r").longOpt("rep").hasArg().argName("REP") .desc("Number of replication [default: 1]").build()); Builder C = Option.builder("c").longOpt("config").numberOfArgs(4).argName("Pop Micro Spec Gen") .desc("Four Parameters in the following orders: " + "(1) population size, (2) microbe size, (3) number of species, (4) number of generation" + " [default: 500 1000 150 10000]"); options.addOption(C.build()); HelpFormatter formatter = new HelpFormatter(); String syntax = "microbiosima pctEnv pctPool"; String header = "\nSimulates the evolutionary and ecological dynamics of microbiomes within a population of hosts.\n\n" + "required arguments:\n" + " pctEnv Percentage of environmental acquisition\n" + " pctPool Percentage of pooled environmental component\n" + "\noptional arguments:\n"; String footer = "\n"; formatter.setWidth(80); CommandLineParser parser = new DefaultParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); String[] pct_config = cmd.getArgs(); if (cmd.hasOption("h") || args.length == 0) { formatter.printHelp(syntax, header, options, footer, true); System.exit(0); } if (cmd.hasOption("v")) { System.out.println("Microbiosima " + VERSION); System.exit(0); } if (pct_config.length != 2) { System.out.println("ERROR! Required exactly two argumennts for pct_env and pct_pool. It got " + pct_config.length + ": " + Arrays.toString(pct_config)); formatter.printHelp(syntax, header, options, footer, true); System.exit(3); } else { pctEnv = Double.parseDouble(pct_config[0]); pctPool = Double.parseDouble(pct_config[1]); if (pctEnv < 0 || pctEnv > 1) { System.out.println( "ERROR: pctEnv (Percentage of environmental acquisition) must be between 0 and 1 (pctEnv=" + pctEnv + ")! EXIT"); System.exit(3); } if (pctPool < 0 || pctPool > 1) { System.out.println( "ERROR: pctPool (Percentage of pooled environmental component must) must be between 0 and 1 (pctPool=" + pctPool + ")! EXIT"); System.exit(3); } } if (cmd.hasOption("config")) { String[] configs = cmd.getOptionValues("config"); populationSize = Integer.parseInt(configs[0]); microSize = Integer.parseInt(configs[1]); numberOfSpecies = Integer.parseInt(configs[2]); numberOfGeneration = Integer.parseInt(configs[3]); } if (cmd.hasOption("obs")) { numberOfObservation = Integer.parseInt(cmd.getOptionValue("obs")); } if (cmd.hasOption("rep")) { numberOfReplication = Integer.parseInt(cmd.getOptionValue("rep")); } } catch (ParseException e) { e.printStackTrace(); System.exit(3); } StringBuilder sb = new StringBuilder(); sb.append("Configuration Summary:").append("\n\tPopulation size: ").append(populationSize) .append("\n\tMicrobe size: ").append(microSize).append("\n\tNumber of species: ") .append(numberOfSpecies).append("\n\tNumber of generation: ").append(numberOfGeneration) .append("\n\tNumber generation for observation: ").append(numberOfObservation) .append("\n\tNumber of replication: ").append(numberOfReplication).append("\n"); System.out.println(sb.toString()); // System.exit(3); // LogNormalDistribution lgd=new LogNormalDistribution(0,1); // environment=lgd.sample(150); // double environment_sum=0; // for (int i=0;i<No;i++){ // environment_sum+=environment[i]; // } // for (int i=0;i<No;i++){ // environment[i]/=environment_sum; // } double[] environment = new double[numberOfSpecies]; for (int i = 0; i < numberOfSpecies; i++) { environment[i] = 1 / (double) numberOfSpecies; } for (int rep = 0; rep < numberOfReplication; rep++) { String prefix = "" + (rep + 1) + "_"; String sufix = "_E" + pctEnv + "_P" + pctPool + ".txt"; System.out.println("Output 5 result files in the format of: " + prefix + "[****]" + sufix); try { PrintWriter file1 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "gamma_diversity" + sufix))); PrintWriter file2 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "alpha_diversity" + sufix))); PrintWriter file3 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "beta_diversity" + sufix))); PrintWriter file4 = new PrintWriter(new BufferedWriter(new FileWriter(prefix + "sum" + sufix))); PrintWriter file5 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "inter_generation_distance" + sufix))); PrintWriter file6 = new PrintWriter( new BufferedWriter(new FileWriter(prefix + "environment_population_distance" + sufix))); Population population = new Population(microSize, environment, populationSize, pctEnv, pctPool, 0, 0); while (population.getNumberOfGeneration() < numberOfGeneration) { population.sumSpecies(); if (population.getNumberOfGeneration() % numberOfObservation == 0) { file1.println(population.gammaDiversity(true)); file2.println(population.alphaDiversity(true)); file3.print(population.betaDiversity(true)); file3.print("\t"); file3.println(population.BrayCurtis(true)); file4.println(population.printOut()); file5.println(population.interGenerationDistance()); file6.println(population.environmentPopulationDistance()); } population.getNextGen(); } file1.close(); file2.close(); file3.close(); file4.close(); file5.close(); file6.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:POP3Mail.java
public static void main(String[] args) { try {/* w ww . j a va 2s .c om*/ LogManager.getLogManager().readConfiguration(new FileInputStream("logging.properties")); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String server = null; String username = null; String password = null; if (new File("mail.properties").exists()) { Properties properties = new Properties(); try { properties.load(new FileInputStream(new File("mail.properties"))); server = properties.getProperty("server"); username = properties.getProperty("username"); password = properties.getProperty("password"); ArrayList<String> list = new ArrayList<String>( Arrays.asList(new String[] { server, username, password })); list.addAll(Arrays.asList(args)); args = list.toArray(new String[list.size()]); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (args.length < 3) { System.err .println("Usage: POP3Mail <pop3 server hostname> <username> <password> [TLS [true=implicit]]"); System.exit(1); } server = args[0]; username = args[1]; password = args[2]; String proto = null; int messageid = -1; boolean implicit = false; for (int i = 3; i < args.length; ++i) { if (args[i].equals("-m")) { i += 1; messageid = Integer.parseInt(args[i]); } } // String proto = args.length > 3 ? args[3] : null; // boolean implicit = args.length > 4 ? Boolean.parseBoolean(args[4]) // : false; POP3Client pop3; if (proto != null) { System.out.println("Using secure protocol: " + proto); pop3 = new POP3SClient(proto, implicit); } else { pop3 = new POP3Client(); } pop3.setDefaultPort(110); System.out.println("Connecting to server " + server + " on " + pop3.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds pop3.setDefaultTimeout(60000); // suppress login details pop3.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true)); try { pop3.connect(server); } catch (IOException e) { System.err.println("Could not connect to server."); e.printStackTrace(); System.exit(1); } try { if (!pop3.login(username, password)) { System.err.println("Could not login to server. Check password."); pop3.disconnect(); System.exit(1); } PrintWriter printWriter = new PrintWriter(new FileWriter("messages.csv"), true); POP3MessageInfo[] messages = null; POP3MessageInfo[] identifiers = null; if (messageid == -1) { messages = pop3.listMessages(); identifiers = pop3.listUniqueIdentifiers(); } else { messages = new POP3MessageInfo[] { pop3.listMessage(messageid) }; } if (messages == null) { System.err.println("Could not retrieve message list."); pop3.disconnect(); return; } else if (messages.length == 0) { System.out.println("No messages"); pop3.logout(); pop3.disconnect(); return; } new File("../json").mkdirs(); int count = 0; for (POP3MessageInfo msginfo : messages) { if (msginfo.number != identifiers[count].number) { throw new RuntimeException(); } msginfo.identifier = identifiers[count].identifier; BufferedReader reader = (BufferedReader) pop3.retrieveMessageTop(msginfo.number, 0); ++count; if (count % 100 == 0) { logger.finest(String.format("%d %s", msginfo.number, msginfo.identifier)); } System.out.println(String.format("%d %s", msginfo.number, msginfo.identifier)); if (reader == null) { System.err.println("Could not retrieve message header."); pop3.disconnect(); System.exit(1); } if (printMessageInfo(reader, msginfo.number, printWriter)) { } } printWriter.close(); pop3.logout(); pop3.disconnect(); } catch (IOException e) { e.printStackTrace(); return; } }