List of usage examples for java.lang String split
public String[] split(String regex)
From source file:edu.harvard.med.screensaver.io.Spammer.java
@SuppressWarnings("static-access") public static void main(String[] args) throws Exception { CommandLineApplication app = new CommandLineApplication(args); String[] option = MAIL_RECIPIENT_LIST_OPTION; app.addCommandLineOption(OptionBuilder.withType(Integer.class).hasArg().isRequired() .withArgName(option[SHORT_OPTION_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); option = MAIL_CC_LIST_OPTION;// www . jav a 2s .c o m app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_REPLYTO_LIST_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_MESSAGE_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_FILE_ATTACHMENT; app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_SUBJECT_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_SERVER_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_USERNAME_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_USER_PASSWORD_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().isRequired().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_FROM_OPTION; app.addCommandLineOption(OptionBuilder.hasArg().withArgName(option[SHORT_OPTION_INDEX]) .withDescription(option[DESCRIPTION_INDEX]).withLongOpt(option[LONG_OPTION_INDEX]) .create(option[SHORT_OPTION_INDEX])); option = MAIL_USE_SMTPS; app.addCommandLineOption( OptionBuilder.withArgName(option[SHORT_OPTION_INDEX]).withDescription(option[DESCRIPTION_INDEX]) .withLongOpt(option[LONG_OPTION_INDEX]).create(option[SHORT_OPTION_INDEX])); app.processOptions(true, true); String message = app.getCommandLineOptionValue(MAIL_MESSAGE_OPTION[SHORT_OPTION_INDEX]); File attachedFile = null; if (app.isCommandLineFlagSet(MAIL_FILE_ATTACHMENT[SHORT_OPTION_INDEX])) { attachedFile = new File(app.getCommandLineOptionValue(MAIL_FILE_ATTACHMENT[SHORT_OPTION_INDEX])); if (!attachedFile.exists()) { log.error("Specified file does not exist: " + attachedFile.getCanonicalPath()); System.exit(1); } } String subject = app.getCommandLineOptionValue(MAIL_SUBJECT_OPTION[SHORT_OPTION_INDEX]); String recipientlist = app.getCommandLineOptionValue(MAIL_RECIPIENT_LIST_OPTION[SHORT_OPTION_INDEX]); String[] recipients = recipientlist.split(DELIMITER); String[] ccrecipients = null; if (app.isCommandLineFlagSet(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX])) { String cclist = app.getCommandLineOptionValue(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX]); ccrecipients = cclist.split(DELIMITER); } String replytos = null; if (app.isCommandLineFlagSet(MAIL_REPLYTO_LIST_OPTION[SHORT_OPTION_INDEX])) { replytos = app.getCommandLineOptionValue(MAIL_CC_LIST_OPTION[SHORT_OPTION_INDEX]); } String mailHost = app.getCommandLineOptionValue(MAIL_SERVER_OPTION[SHORT_OPTION_INDEX]); String username = app.getCommandLineOptionValue(MAIL_USERNAME_OPTION[SHORT_OPTION_INDEX]); String password = app.getCommandLineOptionValue(MAIL_USER_PASSWORD_OPTION[SHORT_OPTION_INDEX]); boolean useSmtps = app.isCommandLineFlagSet(MAIL_USE_SMTPS[SHORT_OPTION_INDEX]); String mailFrom = username; if (app.isCommandLineFlagSet(MAIL_FROM_OPTION[SHORT_OPTION_INDEX])) { mailFrom = app.getCommandLineOptionValue(MAIL_FROM_OPTION[SHORT_OPTION_INDEX]); } SmtpEmailService service = new SmtpEmailService(mailHost, username, replytos, password, useSmtps); service.send(subject, message, mailFrom, recipients, ccrecipients, attachedFile); }
From source file:edu.msu.cme.rdp.graph.sandbox.KmerStartsFromKnown.java
public static void main(String[] args) throws Exception { final KmerStartsWriter out; final boolean translQuery; final int wordSize; final int translTable; try {/*from www . j av a2 s . com*/ CommandLine cmdLine = new PosixParser().parse(options, args); args = cmdLine.getArgs(); if (args.length < 2) { throw new Exception("Unexpected number of arguments"); } if (cmdLine.hasOption("out")) { out = new KmerStartsWriter(cmdLine.getOptionValue("out")); } else { out = new KmerStartsWriter(System.out); } if (cmdLine.hasOption("transl-table")) { translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table")); } else { translTable = 11; } translQuery = cmdLine.hasOption("transl-kmer"); wordSize = Integer.valueOf(args[0]); } catch (Exception e) { new HelpFormatter().printHelp("KmerStartsFromKnown <word_size> [name=]<ref_file> ...", options); System.err.println(e.getMessage()); System.exit(1); throw new RuntimeException("Stupid jvm"); //While this will never get thrown it is required to make sure javac doesn't get confused about uninitialized variables } long startTime = System.currentTimeMillis(); /* * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else * { */ //} System.err.println("Starting kmer mapping at " + new Date()); System.err.println("* References: " + Arrays.asList(args)); System.err.println("* Kmer length: " + wordSize); for (int index = 1; index < args.length; index++) { String refName; String refFileName = args[index]; if (refFileName.contains("=")) { String[] lexemes = refFileName.split("="); refName = lexemes[0]; refFileName = lexemes[1]; } else { String tmpName = new File(refFileName).getName(); if (tmpName.contains(".")) { refName = tmpName.substring(0, tmpName.lastIndexOf(".")); } else { refName = tmpName; } } File refFile = new File(refFileName); if (SeqUtils.guessSequenceType(refFile) != SequenceType.Nucleotide) { throw new Exception("Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile) + " sequences but expected nucleotide sequences"); } SequenceReader seqReader = new SequenceReader(refFile); Sequence seq; while ((seq = seqReader.readNextSequence()) != null) { if (seq.getSeqName().startsWith("#")) { continue; } ModelPositionKmerGenerator kmers = new ModelPositionKmerGenerator(seq.getSeqString(), wordSize, SequenceType.Nucleotide); for (char[] charmer : kmers) { int pos = kmers.getModelPosition() - 1; if (translQuery) { if (pos % 3 != 0) { continue; } else { pos /= 3; } } String kmer = new String(charmer); out.write(new KmerStart(refName, seq.getSeqName(), seq.getSeqName(), kmer, 1, pos, translQuery, (translQuery ? ProteinUtils.getInstance().translateToProtein(kmer, true, translTable) : null))); } } seqReader.close(); } out.close(); }
From source file:com.xandrev.altafitcalendargenerator.Main.java
public static void main(String[] args) { CalendarPrinter printer = new CalendarPrinter(); XLSExtractor extractor = new XLSExtractor(); if (args != null && args.length > 0) { try {//from ww w .ja va 2 s .c o m Options opt = new Options(); opt.addOption("f", true, "Filepath of the XLS file"); opt.addOption("t", true, "Type name of activities"); opt.addOption("m", true, "Month index"); opt.addOption("o", true, "Output filename of the generated ICS"); BasicParser parser = new BasicParser(); CommandLine cliParser = parser.parse(opt, args); if (cliParser.hasOption("f")) { String fileName = cliParser.getOptionValue("f"); LOG.debug("File name to be imported: " + fileName); String activityNames = cliParser.getOptionValue("t"); LOG.debug("Activity type names: " + activityNames); ArrayList<String> nameList = new ArrayList<>(); String[] actNames = activityNames.split(","); if (actNames != null) { nameList.addAll(Arrays.asList(actNames)); } LOG.debug("Sucessfully activities parsed: " + nameList.size()); if (cliParser.hasOption("m")) { String monthIdx = cliParser.getOptionValue("m"); LOG.debug("Month index: " + monthIdx); int month = Integer.parseInt(monthIdx) - 1; if (cliParser.hasOption("o")) { String outputfilePath = cliParser.getOptionValue("o"); LOG.debug("Output file to be generated: " + monthIdx); LOG.debug("Starting to extract the spreadsheet"); HashMap<Integer, ArrayList<TimeTrack>> result = extractor.importExcelSheet(fileName); LOG.debug("Extracted the spreadsheet done"); LOG.debug("Starting the filter of the data"); HashMap<Date, String> cal = printer.getCalendaryByItem(result, nameList, month); LOG.debug("Finished the filter of the data"); LOG.debug("Creating the ics Calendar"); net.fortuna.ical4j.model.Calendar calendar = printer.createICSCalendar(cal); LOG.debug("Finished the ics Calendar"); LOG.debug("Printing the ICS file to: " + outputfilePath); printer.saveCalendar(calendar, outputfilePath); LOG.debug("Finished the ICS file to: " + outputfilePath); } } } } catch (ParseException ex) { LOG.error("Error parsing the argument list: ", ex); } } }
From source file:iac.cnr.it.TestSearcher.java
public static void main(String[] args) throws IOException, ParseException { /** Command line parser and options */ CommandLineParser parser = new PosixParser(); Options options = new Options(); options.addOption(OPT_INDEX, true, "Index path"); options.addOption(OPT_QUERY, true, "The query"); CommandLine cmd = null;/*from w w w .j av a 2 s. co m*/ try { cmd = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { logger.fatal("Error while parsing command line arguments"); System.exit(1); } /** Check for mandatory options */ if (!cmd.hasOption(OPT_INDEX) || !cmd.hasOption(OPT_QUERY)) { usage(); System.exit(0); } /** Read options */ File casePath = new File(cmd.getOptionValue(OPT_INDEX)); String query = cmd.getOptionValue(OPT_QUERY); /** Check correctness of the path containing an ISODAC case */ if (!casePath.exists() || !casePath.isDirectory()) { logger.fatal("The case directory \"" + casePath.getAbsolutePath() + "\" is not valid"); System.exit(1); } /** Check existance of the info.dat file */ File infoFile = new File(casePath, INFO_FILENAME); if (!infoFile.exists()) { logger.fatal("Can't find " + INFO_FILENAME + " within the case directory (" + casePath + ")"); System.exit(1); } /** Load the mapping image_uuid --> image_filename */ imagesMap = new HashMap<Integer, String>(); BufferedReader reader = new BufferedReader(new FileReader(infoFile)); while (reader.ready()) { String line = reader.readLine(); logger.info("Read the line: " + line); String currentID = line.split("\t")[0]; String currentImgFile = line.split("\t")[1]; imagesMap.put(Integer.parseInt(currentID), currentImgFile); logger.info("ID: " + currentID + " - IMG: " + currentImgFile + " added to the map"); } reader.close(); /** Load all the directories containing an index */ ArrayList<String> indexesDirs = new ArrayList<String>(); for (File f : casePath.listFiles()) { logger.info("Analyzing: " + f); if (f.isDirectory()) indexesDirs.add(f.getAbsolutePath()); } logger.info(indexesDirs.size() + " directories found!"); /** Set-up the searcher */ Searcher searcher = null; try { String[] array = indexesDirs.toArray(new String[indexesDirs.size()]); searcher = new Searcher(array); TopDocs results = searcher.search(query, Integer.MAX_VALUE); ScoreDoc[] hits = results.scoreDocs; int numTotalHits = results.totalHits; System.out.println(numTotalHits + " total matching documents"); for (int i = 0; i < numTotalHits; i++) { Document doc = searcher.doc(hits[i].doc); String path = doc.get(FIELD_PATH); String filename = doc.get(FIELD_FILENAME); String image_uuid = doc.get(FIELD_IMAGE_ID); if (path != null) { //System.out.println((i + 1) + ". " + path + File.separator + filename + " - score: " + hits[i].score); // System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + image_uuid); System.out.println((i + 1) + ". " + path + File.separator + filename + " - image_file: " + imagesMap.get(Integer.parseInt(image_uuid))); } else { System.out.println((i + 1) + ". " + "No path for this document"); } } } catch (Exception e) { System.err.println("An error occurred: " + e.getMessage()); e.printStackTrace(); } finally { if (searcher != null) searcher.close(); } }
From source file:com.athena.peacock.controller.common.util.DiffUtil.java
public static void main(String[] args) { List<String> original = null; List<String> revised = null; String a = "Line 1\nLine 2\nLine 3\nLine 4\nLine 5\nLine 6\nLine 7\nLine 8\nLine 9\nLine 10"; String b = "Line 1\nLine 3 with changes\nLine 4\nLine 5 with changes and\na new line\nLine 6\nnew line 6.1\nLine 7\nLine 8\nLine 9\nLine 10 with changes"; original = Arrays.asList(a.split("\n")); revised = Arrays.asList(b.split("\n")); Patch<String> patch = DiffUtils.diff(original, revised); for (Delta<String> delta : patch.getDeltas()) { System.out.println(delta); }/* www .java2 s . c o m*/ System.out.println(original); System.out.println(revised); }
From source file:com.trendmicro.hdfs.webdav.Main.java
public static void main(String[] args) { HDFSWebDAVServlet servlet = HDFSWebDAVServlet.getServlet(); Configuration conf = servlet.getConfiguration(); // Process command line Options options = new Options(); options.addOption("d", "debug", false, "Enable debug logging"); options.addOption("p", "port", true, "Port to bind to [default: 8080]"); options.addOption("b", "bind-address", true, "Address or hostname to bind to [default: 0.0.0.0]"); options.addOption("g", "ganglia", true, "Send Ganglia metrics to host:port [default: none]"); CommandLine cmd = null;// w w w .java 2 s.c o m try { cmd = new PosixParser().parse(options, args); } catch (ParseException e) { printUsageAndExit(options, -1); } if (cmd.hasOption('d')) { Logger rootLogger = Logger.getLogger("com.trendmicro"); rootLogger.setLevel(Level.DEBUG); } if (cmd.hasOption('b')) { conf.set("hadoop.webdav.bind.address", cmd.getOptionValue('b')); } if (cmd.hasOption('p')) { conf.setInt("hadoop.webdav.port", Integer.valueOf(cmd.getOptionValue('p'))); } String gangliaHost = null; int gangliaPort = 8649; if (cmd.hasOption('g')) { String val = cmd.getOptionValue('g'); if (val.indexOf(':') != -1) { String[] split = val.split(":"); gangliaHost = split[0]; gangliaPort = Integer.valueOf(split[1]); } else { gangliaHost = val; } } InetSocketAddress addr = getAddress(conf); // Log in the server principal from keytab UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) try { SecurityUtil.login(conf, "hadoop.webdav.server.kerberos.keytab", "hadoop.webdav.server.kerberos.principal", addr.getHostName()); } catch (IOException e) { LOG.fatal("Could not log in", e); System.err.println("Could not log in"); System.exit(-1); } // Set up embedded Jetty Server server = new Server(); server.setSendServerVersion(false); server.setSendDateHeader(false); server.setStopAtShutdown(true); // Set up connector Connector connector = new SelectChannelConnector(); connector.setPort(addr.getPort()); connector.setHost(addr.getHostName()); server.addConnector(connector); LOG.info("Listening on " + addr); // Set up context Context context = new Context(server, "/", Context.SESSIONS); // WebDAV servlet ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setInitParameter("authenticate-header", "Basic realm=\"Hadoop WebDAV Server\""); context.addServlet(servletHolder, "/*"); // metrics instrumentation filter context.addFilter(new FilterHolder(new DefaultWebappMetricsFilter()), "/*", 0); // auth filter context.addFilter(new FilterHolder(new AuthFilter(conf)), "/*", 0); server.setHandler(context); // Set up Ganglia metrics reporting if (gangliaHost != null) { GangliaReporter.enable(1, TimeUnit.MINUTES, gangliaHost, gangliaPort); } // Start and join the server thread try { server.start(); server.join(); } catch (Exception e) { LOG.fatal("Failed to start Jetty", e); System.err.println("Failed to start Jetty"); System.exit(-1); } }
From source file:net.iridiant.hdfs.webdav.Main.java
public static void main(String[] args) { HDFSWebDAVServlet servlet = HDFSWebDAVServlet.getServlet(); Configuration conf = servlet.getConfiguration(); // Process command line Options options = new Options(); options.addOption("d", "debug", false, "Enable debug logging"); options.addOption("p", "port", true, "Port to bind to [default: 8080]"); options.addOption("b", "bind-address", true, "Address or hostname to bind to [default: 0.0.0.0]"); options.addOption("g", "ganglia", true, "Send Ganglia metrics to host:port [default: none]"); CommandLine cmd = null;//from ww w .j ava2s .c om try { cmd = new PosixParser().parse(options, args); } catch (ParseException e) { printUsageAndExit(options, -1); } if (cmd.hasOption('d')) { Logger rootLogger = Logger.getLogger("net.iridiant"); rootLogger.setLevel(Level.DEBUG); } if (cmd.hasOption('b')) { conf.set("hadoop.webdav.bind.address", cmd.getOptionValue('b')); } if (cmd.hasOption('p')) { conf.setInt("hadoop.webdav.port", Integer.valueOf(cmd.getOptionValue('p'))); } String gangliaHost = null; int gangliaPort = 8649; if (cmd.hasOption('g')) { String val = cmd.getOptionValue('g'); if (val.indexOf(':') != -1) { String[] split = val.split(":"); gangliaHost = split[0]; gangliaPort = Integer.valueOf(split[1]); } else { gangliaHost = val; } } InetSocketAddress addr = getAddress(conf); // Log in the server principal from keytab UserGroupInformation.setConfiguration(conf); if (UserGroupInformation.isSecurityEnabled()) try { SecurityUtil.login(conf, "hadoop.webdav.server.kerberos.keytab", "hadoop.webdav.server.kerberos.principal", addr.getHostName()); } catch (IOException e) { LOG.fatal("Could not log in", e); System.err.println("Could not log in"); System.exit(-1); } // Set up embedded Jetty Server server = new Server(); server.setSendServerVersion(false); server.setSendDateHeader(false); server.setStopAtShutdown(true); // Set up connector Connector connector = new SelectChannelConnector(); connector.setPort(addr.getPort()); connector.setHost(addr.getHostName()); server.addConnector(connector); LOG.info("Listening on " + addr); // Set up context Context context = new Context(server, "/", Context.SESSIONS); // WebDAV servlet ServletHolder servletHolder = new ServletHolder(servlet); servletHolder.setInitParameter("authenticate-header", "Basic realm=\"Hadoop WebDAV Server\""); context.addServlet(servletHolder, "/*"); // metrics instrumentation filter context.addFilter(new FilterHolder(new DefaultWebappMetricsFilter()), "/*", 0); // auth filter context.addFilter(new FilterHolder(new AuthFilter(conf)), "/*", 0); server.setHandler(context); // Set up Ganglia metrics reporting if (gangliaHost != null) { GangliaReporter.enable(1, TimeUnit.MINUTES, gangliaHost, gangliaPort); } // Start and join the server thread try { server.start(); server.join(); } catch (Exception e) { LOG.fatal("Failed to start Jetty", e); System.err.println("Failed to start Jetty"); System.exit(-1); } }
From source file:com.cedarsoft.serialization.SplittingPerformanceRunner.java
public static void main(String[] args) throws Exception { final String uri = "http://www.cedarsoft.com/some/slashes/1.0.0"; run("String.plit", new Callable<String>() { @Override/*from w w w . j a va 2s .c om*/ public String call() throws Exception { String[] parts = uri.split("/"); return parts[parts.length - 1]; } }); run("Splitter", new Callable<String>() { @Override public String call() throws Exception { Splitter splitter = Splitter.on("/"); Iterable<String> parts = splitter.split(uri); Iterator<String> iterator = parts.iterator(); while (true) { String current = iterator.next(); if (!iterator.hasNext()) { return current; } } } }); run("static Splitter", new Callable<String>() { @Override public String call() throws Exception { Iterable<String> parts = SPLITTER.split(uri); Iterator<String> iterator = parts.iterator(); while (true) { String current = iterator.next(); if (!iterator.hasNext()) { return current; } } } }); run("indexOf", new Callable<String>() { @Override public String call() throws Exception { int index = uri.lastIndexOf("/"); return uri.substring(index + 1); } }); }
From source file:jk.kamoru.test.IMAPMail.java
public static void main(String[] args) { /* if (args.length < 3) {//from w w w . j a v a2 s . com System.err.println( "Usage: IMAPMail <imap server hostname> <username> <password> [TLS]"); System.exit(1); } */ String server = "imap.handysoft.co.kr"; String username = "namjk24@handysoft.co.kr"; String password = "22222"; String proto = (args.length > 3) ? args[3] : null; IMAPClient imap; if (proto != null) { System.out.println("Using secure protocol: " + proto); imap = new IMAPSClient(proto, true); // implicit // enable the next line to only check if the server certificate has expired (does not check chain): // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager()); // OR enable the next line if the server uses a self-signed certificate (no checks) // ((IMAPSClient) imap).setTrustManager(TrustManagerUtils.getAcceptAllTrustManager()); } else { imap = new IMAPClient(); } System.out.println("Connecting to server " + server + " on " + imap.getDefaultPort()); // We want to timeout if a response takes longer than 60 seconds imap.setDefaultTimeout(60000); File imap_log_file = new File("IMAMP-UNSEEN"); try { System.out.println(imap_log_file.getAbsolutePath()); PrintStream ps = new PrintStream(imap_log_file); // suppress login details imap.addProtocolCommandListener(new PrintCommandListener(ps, true)); } catch (FileNotFoundException e1) { imap.addProtocolCommandListener(new PrintCommandListener(System.out, true)); } try { imap.connect(server); } catch (IOException e) { throw new RuntimeException("Could not connect to server.", e); } try { if (!imap.login(username, password)) { System.err.println("Could not login to server. Check password."); imap.disconnect(); System.exit(3); } imap.setSoTimeout(6000); // imap.capability(); // imap.select("inbox"); // imap.examine("inbox"); imap.status("inbox", new String[] { "UNSEEN" }); // imap.logout(); imap.disconnect(); List<String> imap_log = FileUtils.readLines(imap_log_file); for (int i = 0; i < imap_log.size(); i++) { System.out.println(i + ":" + imap_log.get(i)); } String unseenText = imap_log.get(4); unseenText = unseenText.substring(unseenText.indexOf('(') + 1, unseenText.indexOf(')')); int unseenCount = Integer.parseInt(unseenText.split(" ")[1]); System.out.println(unseenCount); //imap_log.indexOf("UNSEEN ") } catch (IOException e) { System.out.println(imap.getReplyString()); e.printStackTrace(); System.exit(10); return; } }
From source file:mlbench.pagerank.PagerankMerge.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) throws IOException, InterruptedException { try {//from w ww . j av a 2s. co m parseArgs(args); HashMap<String, String> conf = new HashMap<String, String>(); initConf(conf); MPI_D.Init(args, MPI_D.Mode.Common, conf); JobConf jobConf = new JobConf(confPath); if (MPI_D.COMM_BIPARTITE_O != null) { // O communicator int rank = MPI_D.Comm_rank(MPI_D.COMM_BIPARTITE_O); int size = MPI_D.Comm_size(MPI_D.COMM_BIPARTITE_O); if (rank == 0) { LOG.info(PagerankMerge.class.getSimpleName() + " O start."); } FileSplit[] inputs = DataMPIUtil.HDFSDataLocalLocator.getTaskInputs(MPI_D.COMM_BIPARTITE_O, jobConf, inDir, rank); for (int i = 0; i < inputs.length; i++) { FileSplit fsplit = inputs[i]; LineRecordReader kvrr = new LineRecordReader(jobConf, fsplit); LongWritable key = kvrr.createKey(); Text value = kvrr.createValue(); { while (kvrr.next(key, value)) { String line_text = value.toString(); final String[] line = line_text.split("\t"); if (line.length >= 2) { MPI_D.Send(new IntWritable(Integer.parseInt(line[0])), new Text(line[1])); } } } } } else if (MPI_D.COMM_BIPARTITE_A != null) { // A communicator int rank = MPI_D.Comm_rank(MPI_D.COMM_BIPARTITE_A); if (rank == 0) { LOG.info(PagerankMerge.class.getSimpleName() + " A start."); } HadoopWriter<IntWritable, Text> outrw = HadoopIOUtil.getNewWriter(jobConf, outDir, IntWritable.class, Text.class, TextOutputFormat.class, null, rank, MPI_D.COMM_BIPARTITE_A); IntWritable oldKey = null; double next_rank = 0; double previous_rank = 0; double diff = 0; int local_diffs = 0; random_coeff = (1 - mixing_c) / (double) number_nodes; converge_threshold = ((double) 1.0 / (double) number_nodes) / 10; Object[] keyValue = MPI_D.Recv(); while (keyValue != null) { IntWritable key = (IntWritable) keyValue[0]; Text value = (Text) keyValue[1]; if (oldKey == null) { oldKey = key; } if (!key.equals(oldKey)) { next_rank = next_rank * mixing_c + random_coeff; outrw.write(oldKey, new Text("v" + next_rank)); diff = Math.abs(previous_rank - next_rank); if (diff > converge_threshold) { local_diffs += 1; } oldKey = key; next_rank = 0; previous_rank = 0; } String cur_value_str = value.toString(); if (cur_value_str.charAt(0) == 's') { previous_rank = Double.parseDouble(cur_value_str.substring(1)); } else { next_rank += Double.parseDouble(cur_value_str.substring(1)); } keyValue = MPI_D.Recv(); } if (previous_rank != 0) { next_rank = next_rank * mixing_c + random_coeff; outrw.write(oldKey, new Text("v" + next_rank)); diff = Math.abs(previous_rank - next_rank); if (diff > converge_threshold) local_diffs += 1; } outrw.close(); reduceDiffs(local_diffs, rank); } MPI_D.Finalize(); } catch (MPI_D_Exception e) { e.printStackTrace(); } }