Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

In this page you can find the example usage for java.lang String substring.

Prototype

public String substring(int beginIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:com.marklogic.client.tutorial.util.Bootstrapper.java

/**
 * Command-line invocation.//from   w  w w.  j  a v  a2  s .c o  m
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args)
        throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Command-line invocation.//from   w  w w.  j  a  va  2  s .c om
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args) throws ClientProtocolException, IOException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    // TODO: catch invalid argument exceptions and provide feedback
    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}

From source file:org.sbs.util.BinaryDateDwonLoader.java

/**
 * @param args/*from   w  w  w .ja  v  a  2 s.c o  m*/
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    String img = "http://apollo.s.dpool.sina.com.cn/nd/dataent/moviepic/pics/157/moviepic_8d48be1e004c5b05464a7a427d6722e4.jpg";
    BinaryDateDwonLoader dateDwonLoader = BinaryDateDwonLoader.getInstance();
    PageFetchResult result = dateDwonLoader.fetchHeader(img);
    try {
        OutputStream outputStream = new FileOutputStream(
                new File("d:\\" + img.substring(img.lastIndexOf('/') + 1)));
        result.getEntity().writeTo(outputStream);
        outputStream.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:VerboseGC.java

public static void main(String[] args) {
    if (args.length < 1) {
        usage();//  w  ww  .  ja v a2  s  . com
    }

    String hostname = "";
    int port = -1;
    long interval = 5000; // default is 5 second interval
    long mins = 5;
    for (int argIndex = 0; argIndex < args.length; argIndex++) {
        String arg = args[argIndex];
        if (args[argIndex].startsWith("-")) {
            if (arg.equals("-h") || arg.equals("-help") || arg.equals("-?")) {
                usage();
            } else if (arg.startsWith("-interval=")) {
                try {
                    interval = Integer.parseInt(arg.substring(10)) * 1000;
                } catch (NumberFormatException ex) {
                    usage();
                }
            } else if (arg.startsWith("-duration=")) {
                try {
                    mins = Integer.parseInt(arg.substring(10));
                } catch (NumberFormatException ex) {
                    usage();
                }
            } else {
                // Unknown switch
                System.err.println("Unrecognized option: " + arg);
                usage();
            }
        } else {
            String[] arg2 = arg.split(":");
            if (arg2.length != 2) {
                usage();
            }
            hostname = arg2[0];
            try {
                port = Integer.parseInt(arg2[1]);
            } catch (NumberFormatException x) {
                usage();
            }
            if (port < 0) {
                usage();
            }
        }
    }

    // get full thread dump and perform deadlock detection
    VerboseGC vgc = new VerboseGC(hostname, port);
    long samples = (mins * 60 * 1000) / interval;
    vgc.dump(interval, samples);

}

From source file:com.seanmadden.net.fast.SerialInterface.java

public static void main(String[] args) {
    SerialInterface inter = new SerialInterface(new JSONObject());
    inter.open();//from   w  w w .  java 2s  .  co m

    System.out.println("Welcome.  Commands with 'help'");
    String cmd = "";
    Scanner scan = new Scanner(System.in);
    do {
        System.out.print("> ");
        cmd = scan.nextLine();
        if (cmd.toLowerCase().equals("help")) {
            System.out.println("Commands:");
            System.out.println("help : prints this message");
            System.out.println("send <message> : sends <message> to interpretype.");
            System.out.println("quit : exits this program");
        } else if (cmd.toLowerCase().startsWith("send")) {
            String message = cmd.substring(cmd.toLowerCase().indexOf(' ') + 1);
            inter.sendDataToPort(message);
        }
    } while (!cmd.toLowerCase().equals("quit"));

    inter.close();
}

From source file:ListAlgorithms.java

public static void main(String[] args) {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Provider[] providers = Security.getProviders();
    Set<String> ciphers = new HashSet<String>();
    Set<String> keyAgreements = new HashSet<String>();
    Set<String> macs = new HashSet<String>();
    Set<String> messageDigests = new HashSet<String>();
    Set<String> signatures = new HashSet<String>();
    Set<String> keyFactory = new HashSet<String>();
    Set<String> keyPairGenerator = new HashSet<String>();
    Set<String> keyGenerator = new HashSet<String>();

    for (int i = 0; i != providers.length; i++) {
        Iterator it = providers[i].keySet().iterator();

        while (it.hasNext()) {
            String entry = (String) it.next();

            if (entry.startsWith("Alg.Alias.")) {
                entry = entry.substring("Alg.Alias.".length());
            }//from  ww  w .  j  a  v a2  s  .  com

            if (entry.startsWith("Cipher.")) {
                ciphers.add(entry.substring("Cipher.".length()));
            } else if (entry.startsWith("KeyAgreement.")) {
                keyAgreements.add(entry.substring("KeyAgreement.".length()));
            } else if (entry.startsWith("Mac.")) {
                macs.add(entry.substring("Mac.".length()));
            } else if (entry.startsWith("MessageDigest.")) {
                messageDigests.add(entry.substring("MessageDigest.".length()));
            } else if (entry.startsWith("Signature.")) {

                signatures.add(entry.substring("Signature.".length()));

            } else if (entry.startsWith("KeyPairGenerator.")) {
                keyPairGenerator.add(entry.substring("KeyPairGenerator.".length()));
            } else if (entry.startsWith("KeyFactory.")) {
                keyFactory.add(entry.substring("KeyFactory.".length()));
            } else if (entry.startsWith("KeyGenerator.")) {
                keyGenerator.add(entry.substring("KeyGenerator.".length()));

            } else {
                System.out.println(entry);
            }
        }
    }

    printSet("KeyGenerator", keyGenerator);
    printSet("KeyFactory", keyFactory);
    printSet("KeyPairGenerator", keyPairGenerator);
    printSet("Ciphers", ciphers);
    printSet("KeyAgreeents", keyAgreements);
    printSet("Macs", macs);
    printSet("MessageDigests", messageDigests);
    printSet("Signatures", signatures);
}

From source file:ZipImploder.java

/**
 * Main command line entry point./* w  ww.jav  a 2 s.c  o m*/
 * 
 * @param args
 */
public static void main(final String[] args) {
    if (args.length == 0) {
        printHelp();
        System.exit(0);
    }
    String zipName = null;
    String jarName = null;
    String manName = null;
    String sourceDir = null;
    String leadDir = null;
    boolean jarActive = false, manActive = false, zipActive = false, sourceDirActive = false,
            leadDirActive = false;
    boolean verbose = false;
    boolean noDirs = false;
    // process arguments
    for (int i = 0; i < args.length; i++) {
        String arg = args[i];
        if (arg.charAt(0) == '-') { // switch
            arg = arg.substring(1);
            if (arg.equalsIgnoreCase("jar")) {
                jarActive = true;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("manifest")) {
                jarActive = false;
                manActive = true;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("zip")) {
                zipActive = true;
                manActive = false;
                jarActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("dir")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = true;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("lead")) {
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = true;
            } else if (arg.equalsIgnoreCase("noDirs")) {
                noDirs = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else if (arg.equalsIgnoreCase("verbose")) {
                verbose = true;
                jarActive = false;
                manActive = false;
                zipActive = false;
                sourceDirActive = false;
                leadDirActive = false;
            } else {
                reportError("Invalid switch - " + arg);
            }
        } else {
            if (jarActive) {
                if (jarName != null) {
                    reportError("Duplicate value - " + arg);
                }
                jarName = arg;
            } else if (manActive) {
                if (manName != null) {
                    reportError("Duplicate value - " + arg);
                }
                manName = arg;
            } else if (zipActive) {
                if (zipName != null) {
                    reportError("Duplicate value - " + arg);
                }
                zipName = arg;
            } else if (sourceDirActive) {
                if (sourceDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                sourceDir = arg;
            } else if (leadDirActive) {
                if (leadDir != null) {
                    reportError("Duplicate value - " + arg);
                }
                leadDir = arg;
            } else {
                reportError("Too many parameters - " + arg);
            }
        }
    }
    if (sourceDir == null || (zipName == null && jarName == null)) {
        reportError("Missing parameters");
    }
    if (manName != null && zipName != null) {
        reportError("Manifests not supported on ZIP files");
    }
    if (leadDir == null) {
        leadDir = new File(sourceDir).getAbsolutePath().replace('\\', '/') + '/';
    }
    if (verbose) {
        System.out.println("Effective command: " + ZipImploder.class.getName()
                + (jarName != null ? " -jar " + jarName + (manName != null ? " -manifest " + manName : "") : "")
                + (zipName != null ? " -zip " + zipName : "") + " -dir " + sourceDir + " -lead " + leadDir
                + (noDirs ? " -noDirs" : "") + (verbose ? " -verbose" : ""));
    }
    try {
        ZipImploder zi = new ZipImploder(verbose);
        if (leadDir != null) {
            zi.setBaseDir(leadDir);
        }
        if (manName != null) {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(manName));
            try {
                zi.setManifest(new Manifest(bis));
            } finally {
                bis.close();
            }
        }
        zi.setIncludeDirs(!noDirs);
        zi.process(zipName, jarName, sourceDir);
        if (verbose) {
            System.out.println("\nDone Directories=" + zi.getDirCount() + " Files=" + zi.getFileCount());
        }
    } catch (IOException ioe) {
        System.err.println("Exception - " + ioe.getMessage());
        // ioe.printStackTrace(); // *** debug ***
        System.exit(2);
    }
}

From source file:edu.duke.igsp.gkde.Main.java

public static void main(String[] argv) throws Exception {

    Options opts = new Options();
    opts.addOption("s", true, "wiggle track step (default=1)");
    opts.addOption("l", true, "feature length (default=600)");
    opts.addOption("f", true, "fragment size (default=estimated from data)");
    //    opts.addOption("b", true, "bandwidth (default=200)");
    //    opts.addOption("w", true, "window (default=3800");
    opts.addOption("wg", true, "wg threshold set (defualt = calculated)");
    opts.addOption("c", true, "genomic total read weight (defualt = calculated)");
    opts.addOption("h", false, "print usage");
    opts.addOption(OptionBuilder.withArgName("input dir").hasArg()
            .withDescription("input directory (default=current directory)").isRequired(false).create("d"));
    opts.addOption(OptionBuilder.withArgName("output dir").hasArg()
            .withDescription("output directory (default=current directory)").isRequired(false).create("o"));
    opts.addOption(OptionBuilder.withArgName("background dir").hasArg()
            .withDescription("background directory (default=none)").isRequired(false).create("b"));
    opts.addOption(OptionBuilder.withArgName("ploidy dir").hasArg()
            .withDescription("ploidy/input directory (default=none)").isRequired(false).create("p"));
    opts.addOption(OptionBuilder.withArgName("wig | bed | npf").hasArg()
            .withDescription("output format (default wig)").isRequired(false).create("of"));
    opts.addOption(OptionBuilder.withArgName("dnase | chip | faire | atac").hasArg()
            .withDescription("input data").isRequired(true).create("in"));
    opts.addOption(OptionBuilder.withArgName("weight clip").hasArg()
            .withDescription("weight clip value (default none)").isRequired(false).create("wc"));
    opts.addOption("t", true, "threshold (standard deviations) (default=4.0)");
    //    opts.addOption("r", true, "background ratio (default=2.0)");
    opts.addOption("v", false, "verbose output");

    CommandLineParser parser = new GnuParser();
    int fragment_size = -1;
    int fragment_offset = 0;
    long featureLength = 600l;
    //    float thresh = 2;
    float threshold = KDEChromosome.Settings.DEFAULT_THRESHOLD;
    int step = 1;
    boolean showHelp = false;
    boolean verbose = false;
    String inputDirectory = null;
    String backgroundDirectory = null;
    String ploidyDirectory = null;
    String[] files = null;/*from  w  w w  .j a v  a2 s  .co  m*/
    String[] bgfiles = {};
    String[] ipfiles = {};
    String outputFormat = "wig";
    String inputDataType = "dnase";
    File outputDirectory = new File(System.getProperty("user.dir"));

    long bandwidth = 0l;
    long window = 0l;
    double ncuts = 0.0d;
    float temp_threshold = 0f;
    int weight_clip = 0;

    System.out.println("F-Seq Version 1.85");

    try {
        CommandLine cmd = parser.parse(opts, argv);
        showHelp = (cmd.hasOption("h"));
        verbose = (cmd.hasOption("v"));
        if (cmd.hasOption("s"))
            step = Integer.parseInt(cmd.getOptionValue("s"));
        if (cmd.hasOption("f"))
            fragment_size = Integer.parseInt(cmd.getOptionValue("f"));
        if (cmd.hasOption("d")) //input directory
            inputDirectory = cmd.getOptionValue("d");
        if (cmd.hasOption("b")) //background directory
            backgroundDirectory = cmd.getOptionValue("b");
        if (cmd.hasOption("p")) //ploidy|input directory
            ploidyDirectory = cmd.getOptionValue("p");
        if (cmd.hasOption("l")) // bandwidth
            featureLength = Long.parseLong(cmd.getOptionValue("l"));
        if (cmd.hasOption("of")) { // output format
            outputFormat = cmd.getOptionValue("of");
            if (!outputFormat.equals("wig") && !outputFormat.equals("bed") && !outputFormat.equals("npf")) {
                System.out.println("Parameter error: output format must be 'wig' or 'bed'.");
                showHelp = true;
            }
        }
        if (cmd.hasOption("in")) { // input data type
            inputDataType = cmd.getOptionValue("in");
            if (!inputDataType.equals("dnase") && !inputDataType.equals("chip")
                    && !inputDataType.equals("faire") && !inputDataType.equals("atac")) {
                System.out.println(
                        "Parameter error: input data type must be 'dnase', 'chip', 'faire', or 'atac'.");
                showHelp = true;
            }
        }
        if (cmd.hasOption("wc")) { // weight clip
            weight_clip = Integer.parseInt(cmd.getOptionValue("wc"));
        }
        if (cmd.hasOption("t")) { // threshold (standard deviations)
            threshold = Float.parseFloat(cmd.getOptionValue("t"));
        }
        if (cmd.hasOption("o")) { // output directory
            String out = cmd.getOptionValue("o");
            outputDirectory = new File(out);
            if (!outputDirectory.exists() && !outputDirectory.isDirectory()) {
                System.out.println("Output directory '" + out + "' is not a valid directory.");
                showHelp = true;
            }
        }

        if (cmd.hasOption("wg"))
            temp_threshold = Float.parseFloat(cmd.getOptionValue("wg"));
        if (cmd.hasOption("c"))
            ncuts = Double.parseDouble(cmd.getOptionValue("c"));

        // TESTING ONLY
        //   if(cmd.hasOption("w")) // window
        //     window = Long.parseLong(cmd.getOptionValue("w"));
        //if(cmd.hasOption("b")) // window
        //  bandwidth = Long.parseLong(cmd.getOptionValue("b"));

        files = cmd.getArgs(); // input files
        //bgfiles = cmd.getArgs(); // background files
    } catch (Exception e) {
        System.out.println("Error parsing arguments: " + e.getMessage());
        e.printStackTrace();
        showHelp = true;
    }

    if (showHelp || (inputDirectory == null && files.length == 0)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("fseq [options]... [file(s)]...", opts);
        System.exit(1);
    }

    File[] pfiles = getFiles(inputDirectory, files);
    File[] background_files = getFiles(backgroundDirectory, bgfiles);
    File[] ploidy_files = getFiles(ploidyDirectory, ipfiles);

    KDEChromosome[] chrs = null;
    // assume all files are of the same type, if not we'll get parsing errors
    String path = pfiles[0].getPath();
    String extension = path.substring(path.lastIndexOf('.')).toLowerCase();
    System.out.println("Path: " + path + ", extension: " + extension);
    if (extension.equals(".bed")) {
        System.out.println("Parsing BED file.");
        chrs = BedReader.read(pfiles);
    } else if (extension.equals(".sam") || extension.equals(".bam")) {
        System.out.println("Parsing SAM/BAM file.");
        chrs = SamReader.read(pfiles, weight_clip);
    }
    //KDEChromosome[] input = BedReader.read(ifiles);

    //compute fragment offset
    if (fragment_size == -1) {
        fragment_size = wgShiftCalc(chrs);
    }
    fragment_offset = (int) (fragment_size / 2);

    if (ncuts == 0.0d) {
        for (int i = 0; i < chrs.length; ++i) {
            // computes the total read weight of all cuts on a chromosome
            ncuts += chrs[i].getTotalWeight();
        }
    }

    KDEChromosome.Settings settings = null;
    if (bandwidth > 0 || window > 0) {
        settings = new KDEChromosome.Settings(bandwidth, window, threshold, fragment_offset, ncuts,
                inputDataType);
    } else {
        settings = new KDEChromosome.Settings(featureLength, threshold, fragment_offset, ncuts, inputDataType);
    }

    float wg_threshold = wgThreshold(settings, chrs);
    if (temp_threshold != 0f) {
        wg_threshold = temp_threshold;
    }
    //KDEChromosome.Settings bg_settings = null;
    //bg_settings = new KDEChromosome.Settings(featureLength*2, threshold, fragment_offset);

    //int background_size = 0;
    //int input_size = 0;
    //float bg_ratio = 0;
    //float sd = 0;

    if (verbose) {
        System.out.println("Settings: ");
        System.out.println("\twindow=" + (settings.window * 2));
        System.out.println("\tbandwidth=" + (settings.bandwidth));
        //System.out.println("\tfragment offset=" + (settings.offset));
        System.out.println("\tthreshold = " + wg_threshold);
        System.out.println("\test. fragment size = " + fragment_size);
        System.out.println("\tsequence length = " + chrs[0].getSequenceLength());
    }

    //    if(backgroundDirectory != null) {
    //       for(int i = 0; i < input.length; ++i) {
    //          background_size += input[i].getLength();
    //       }
    //       for(int i = 0; i < chrs.length; ++i) {
    //          input_size += chrs[i].getLength();
    //       }
    //       bg_ratio = (float)input_size/(float)background_size;
    //       sd = computeSD(bg_settings, input);
    //       //System.out.println("Sample Ratio: " + bg_ratio);
    //       //System.out.println("Input Size: " + input_size);
    //       //System.out.println("Background Size: " + background_size);
    //       //System.out.println("Input standard deviation: " + (settings.threshold * (float)Math.sqrt((double)bg_ratio * (double)sd * (double)sd)));
    //       //System.out.println("Data standard deviation: " + settings.threshold * computeSD(settings, chrs));
    //    }

    for (int i = 0; i < chrs.length; ++i) {
        if (chrs[i].getFirstPos() == chrs[i].getLastPos()) {
            System.out.println("Warning: " + chrs[i].getChromosome() + " has size zero.  Skipping.");
            continue;
        }
        File ofile = Util.makeUniqueFileWithExtension(outputDirectory, chrs[i].getChromosome(), outputFormat);

        DensityWriter dw = null;
        if (outputFormat.equals("wig")) {
            dw = new WiggleDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
        } else {
            if (outputFormat.equals("npf")) {
                dw = new NpfDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
            } else {
                dw = new BedDensityWriter(ofile, chrs[i].getChromosome(), chrs[i].getFirstPos(), step);
            }
        }

        //Function takes all? or new function for each?
        //      if(backgroundDirectory != null) {
        //         boolean hit = false;
        //         for(int j = 0; j < background_files.length; ++j) {
        //            if(background_files[j].getName().equals(chrs[i].getChromosome() + ".bff")) {
        //               System.out.println("Running background on Chromosome " + chrs[i].getChromosome());
        //               chrs[i].runBG(settings, dw, verbose, wg_threshold, background_files[j]);
        //               hit = true;
        //            }
        //         }
        //         if(!hit)
        //            System.out.println("No background for Chromosome " + chrs[i].getChromosome());
        //      } else {
        //         if(ploidyDirectory !=)
        //         chrs[i].run(settings, dw, verbose, wg_threshold);
        //      }
        chrs[i].run(settings, dw, verbose, wg_threshold, background_files, ploidy_files);
        dw.close();
    }

    //kde.showGraph();
}

From source file:DateParse2.java

public static void main(String[] args) {

    //+/*ww  w. j a  v a  2  s.co  m*/
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String input[] = { "BD: 1913-10-01 Vancouver, B.C.", "MD: 1948-03-01 Ottawa, ON",
            "DD: 1983-06-06 Toronto, ON" };
    for (int i = 0; i < input.length; i++) {
        String aLine = input[i];
        String action;
        switch (aLine.charAt(0)) {
        case 'B':
            action = "Born";
            break;
        case 'M':
            action = "Married";
            break;
        case 'D':
            action = "Died";
            break;
        // others...
        default:
            System.err.println("Invalid code in " + aLine);
            continue;
        }
        int p = aLine.indexOf(' ');
        ParsePosition pp = new ParsePosition(p);
        Date d = formatter.parse(aLine, pp);
        if (d == null) {
            System.err.println("Invalid date in " + aLine);
            continue;
        }
        String location = aLine.substring(pp.getIndex());
        System.out.println(action + " on " + d + " in " + location);
    }
    //-
}

From source file:CTmousetrack.java

public static void main(String[] args) {

    String outLoc = new String("." + File.separator + "CTdata"); // Location of the base output data folder; only used when writing out CT data to a local folder
    String srcName = "CTmousetrack"; // name of the output CT source
    long blockPts = 10; // points per block flush
    long sampInterval = 10; // time between sampling updates, msec
    double trimTime = 0.0; // amount of data to keep (trim time), sec
    boolean debug = false; // turn on debug?

    // Specify the CT output connection
    CTWriteMode writeMode = CTWriteMode.LOCAL; // The selected mode for writing out CT data
    String serverHost = ""; // Server (FTP or HTTP/S) host:port
    String serverUser = ""; // Server (FTP or HTTPS) username
    String serverPassword = ""; // Server (FTP or HTTPS) password

    // For UDP output mode
    DatagramSocket udpServerSocket = null;
    InetAddress udpServerAddress = null;
    String udpHost = "";
    int udpPort = -1;

    // Concatenate all of the CTWriteMode types
    String possibleWriteModes = "";
    for (CTWriteMode wm : CTWriteMode.values()) {
        possibleWriteModes = possibleWriteModes + ", " + wm.name();
    }//from  w  w  w. j  ava2s  .c o m
    // Remove ", " from start of string
    possibleWriteModes = possibleWriteModes.substring(2);

    //
    // Argument processing using Apache Commons CLI
    //
    // 1. Setup command line options
    Options options = new Options();
    options.addOption("h", "help", false, "Print this message.");
    options.addOption(Option.builder("o").argName("base output dir").hasArg().desc(
            "Base output directory when writing data to local folder (i.e., this is the location of CTdata folder); default = \""
                    + outLoc + "\".")
            .build());
    options.addOption(Option.builder("s").argName("source name").hasArg()
            .desc("Name of source to write data to; default = \"" + srcName + "\".").build());
    options.addOption(Option.builder("b").argName("points per block").hasArg()
            .desc("Number of points per block; UDP output mode will use 1 point/block; default = "
                    + Long.toString(blockPts) + ".")
            .build());
    options.addOption(Option.builder("dt").argName("samp interval msec").hasArg()
            .desc("Sampling period in msec; default = " + Long.toString(sampInterval) + ".").build());
    options.addOption(Option.builder("t").argName("trim time sec").hasArg().desc(
            "Trim (ring-buffer loop) time (sec); this is only used when writing data to local folder; specify 0 for indefinite; default = "
                    + Double.toString(trimTime) + ".")
            .build());
    options.addOption(
            Option.builder("w").argName("write mode").hasArg()
                    .desc("Type of write connection; one of " + possibleWriteModes
                            + "; all but UDP mode write out to CT; default = " + writeMode.name() + ".")
                    .build());
    options.addOption(Option.builder("host").argName("host[:port]").hasArg()
            .desc("Host:port when writing via FTP, HTTP, HTTPS, UDP.").build());
    options.addOption(Option.builder("u").argName("username,password").hasArg()
            .desc("Comma-delimited username and password when writing to CT via FTP or HTTPS.").build());
    options.addOption("x", "debug", false, "Enable CloudTurbine debug output.");

    // 2. Parse command line options
    CommandLineParser parser = new DefaultParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException exp) { // oops, something went wrong
        System.err.println("Command line argument parsing failed: " + exp.getMessage());
        return;
    }

    // 3. Retrieve the command line values
    if (line.hasOption("help")) { // Display help message and quit
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp("CTmousetrack", "", options,
                "NOTE: UDP output is a special non-CT output mode where single x,y points are sent via UDP to the specified host:port.");
        return;
    }

    outLoc = line.getOptionValue("o", outLoc);
    if (!outLoc.endsWith("\\") && !outLoc.endsWith("/")) {
        outLoc = outLoc + File.separator;
    }
    // Make sure the base output folder location ends in "CTdata"
    if (!outLoc.endsWith("CTdata\\") && !outLoc.endsWith("CTdata/")) {
        outLoc = outLoc + "CTdata" + File.separator;
    }

    srcName = line.getOptionValue("s", srcName);

    blockPts = Long.parseLong(line.getOptionValue("b", Long.toString(blockPts)));

    sampInterval = Long.parseLong(line.getOptionValue("dt", Long.toString(sampInterval)));

    trimTime = Double.parseDouble(line.getOptionValue("t", Double.toString(trimTime)));

    // Type of output connection
    String writeModeStr = line.getOptionValue("w", writeMode.name());
    boolean bMatch = false;
    for (CTWriteMode wm : CTWriteMode.values()) {
        if (wm.name().toLowerCase().equals(writeModeStr.toLowerCase())) {
            writeMode = wm;
            bMatch = true;
        }
    }
    if (!bMatch) {
        System.err.println("Unrecognized write mode, \"" + writeModeStr + "\"; write mode must be one of "
                + possibleWriteModes);
        System.exit(0);
    }
    if (writeMode != CTWriteMode.LOCAL) {
        // User must have specified the host
        // If FTP or HTTPS, they may also specify username/password
        serverHost = line.getOptionValue("host", serverHost);
        if (serverHost.isEmpty()) {
            System.err.println(
                    "When using write mode \"" + writeModeStr + "\", you must specify the server host.");
            System.exit(0);
        }
        if (writeMode == CTWriteMode.UDP) {
            // Force blockPts to be 1
            blockPts = 1;
            // User must have specified both host and port
            int colonIdx = serverHost.indexOf(':');
            if ((colonIdx == -1) || (colonIdx >= serverHost.length() - 1)) {
                System.err.println(
                        "For UDP output mode, both the host and port (<host>:<port>)) must be specified.");
                System.exit(0);
            }
            udpHost = serverHost.substring(0, colonIdx);
            String udpPortStr = serverHost.substring(colonIdx + 1);
            try {
                udpPort = Integer.parseInt(udpPortStr);
            } catch (NumberFormatException nfe) {
                System.err.println("The UDP port must be a positive integer.");
                System.exit(0);
            }
        }
        if ((writeMode == CTWriteMode.FTP) || (writeMode == CTWriteMode.HTTPS)) {
            String userpassStr = line.getOptionValue("u", "");
            if (!userpassStr.isEmpty()) {
                // This string should be comma-delimited username and password
                String[] userpassCSV = userpassStr.split(",");
                if (userpassCSV.length != 2) {
                    System.err.println("When specifying a username and password for write mode \""
                            + writeModeStr + "\", separate the username and password by a comma.");
                    System.exit(0);
                }
                serverUser = userpassCSV[0];
                serverPassword = userpassCSV[1];
            }
        }
    }

    debug = line.hasOption("debug");

    System.err.println("CTmousetrack parameters:");
    System.err.println("\toutput mode = " + writeMode.name());
    if (writeMode == CTWriteMode.UDP) {
        System.err.println("\twrite to " + udpHost + ":" + udpPort);
    } else {
        System.err.println("\tsource = " + srcName);
        System.err.println("\ttrim time = " + trimTime + " sec");
    }
    System.err.println("\tpoints per block = " + blockPts);
    System.err.println("\tsample interval = " + sampInterval + " msec");

    try {
        //
        // Setup CTwriter or UDP output
        //
        CTwriter ctw = null;
        CTinfo.setDebug(debug);
        if (writeMode == CTWriteMode.LOCAL) {
            ctw = new CTwriter(outLoc + srcName, trimTime);
            System.err.println("\tdata will be written to local folder \"" + outLoc + "\"");
        } else if (writeMode == CTWriteMode.FTP) {
            CTftp ctftp = new CTftp(srcName);
            try {
                ctftp.login(serverHost, serverUser, serverPassword);
            } catch (Exception e) {
                throw new IOException(
                        new String("Error logging into FTP server \"" + serverHost + "\":\n" + e.getMessage()));
            }
            ctw = ctftp; // upcast to CTWriter
            System.err.println("\tdata will be written to FTP server at " + serverHost);
        } else if (writeMode == CTWriteMode.HTTP) {
            // Don't send username/pw in HTTP mode since they will be unencrypted
            CThttp cthttp = new CThttp(srcName, "http://" + serverHost);
            ctw = cthttp; // upcast to CTWriter
            System.err.println("\tdata will be written to HTTP server at " + serverHost);
        } else if (writeMode == CTWriteMode.HTTPS) {
            CThttp cthttp = new CThttp(srcName, "https://" + serverHost);
            // Username/pw are optional for HTTPS mode; only use them if username is not empty
            if (!serverUser.isEmpty()) {
                try {
                    cthttp.login(serverUser, serverPassword);
                } catch (Exception e) {
                    throw new IOException(new String(
                            "Error logging into HTTP server \"" + serverHost + "\":\n" + e.getMessage()));
                }
            }
            ctw = cthttp; // upcast to CTWriter
            System.err.println("\tdata will be written to HTTPS server at " + serverHost);
        } else if (writeMode == CTWriteMode.UDP) {
            try {
                udpServerSocket = new DatagramSocket();
            } catch (SocketException se) {
                System.err.println("Error creating socket for UDP:\n" + se);
                System.exit(0);
            }
            try {
                udpServerAddress = InetAddress.getByName(udpHost);
            } catch (UnknownHostException uhe) {
                System.err.println("Error getting UDP server host address:\n" + uhe);
                System.exit(0);
            }
        }
        if (writeMode != CTWriteMode.UDP) {
            ctw.setBlockMode(blockPts > 1, blockPts > 1);
            ctw.autoFlush(0); // no autoflush
            ctw.autoSegment(1000);
        }

        // screen dims
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        double width = screenSize.getWidth();
        double height = screenSize.getHeight();

        // use Map for consolidated putData
        Map<String, Object> cmap = new LinkedHashMap<String, Object>();

        // loop and write some output
        for (int i = 0; i < 1000000; i++) { // go until killed
            long currentTime = System.currentTimeMillis();
            Point mousePos = MouseInfo.getPointerInfo().getLocation();
            float x_pt = (float) (mousePos.getX() / width); // normalize
            float y_pt = (float) ((height - mousePos.getY()) / height); // flip Y (so bottom=0)
            if (writeMode != CTWriteMode.UDP) {
                // CT output mode
                ctw.setTime(currentTime);
                cmap.clear();
                cmap.put("x", x_pt);
                cmap.put("y", y_pt);
                ctw.putData(cmap);
                if (((i + 1) % blockPts) == 0) {
                    ctw.flush();
                    System.err.print(".");
                }
            } else {
                // UDP output mode
                // We force blockPts to be 1 for UDP output mode, i.e. we "flush" the data every time
                // Write the following data (21 bytes total):
                //     header = "MOUSE", 5 bytes
                //     current time, long, 8 bytes
                //     2 floats (x,y) 4 bytes each, 8 bytes
                int len = 21;
                ByteBuffer bb = ByteBuffer.allocate(len);
                String headerStr = "MOUSE";
                bb.put(headerStr.getBytes("UTF-8"));
                bb.putLong(currentTime);
                bb.putFloat(x_pt);
                bb.putFloat(y_pt);
                // Might be able to use the following, but not sure:
                //     byte[] sendData = bb.array();
                byte[] sendData = new byte[len];
                bb.position(0);
                bb.get(sendData, 0, len);
                DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, udpServerAddress,
                        udpPort);
                try {
                    udpServerSocket.send(sendPacket);
                } catch (IOException e) {
                    System.err.println("Test server caught exception trying to send data to UDP client:\n" + e);
                }
                System.err.print(".");
            }
            try {
                Thread.sleep(sampInterval);
            } catch (Exception e) {
            }
            ;
        }
        if (writeMode != CTWriteMode.UDP) {
            ctw.flush(); // wrap up
        }
    } catch (Exception e) {
        System.err.println("CTmousetrack exception: " + e);
        e.printStackTrace();
    }
}