Example usage for java.lang String contains

List of usage examples for java.lang String contains

Introduction

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

Prototype

public boolean contains(CharSequence s) 

Source Link

Document

Returns true if and only if this string contains the specified sequence of char values.

Usage

From source file:MainGeneratePicasaIniFile.java

public static void main(String[] args) {
    try {//  w  w  w. j a  va  2 s.c om

        Calendar start = Calendar.getInstance();

        start.set(1899, 11, 30, 0, 0);

        PicasawebService myService = new PicasawebService("My Application");
        myService.setUserCredentials(args[0], args[1]);

        // Get a list of all entries
        URL metafeedUrl = new URL("http://picasaweb.google.com/data/feed/api/user/" + args[0] + "?kind=album");
        System.out.println("Getting Picasa Web Albums entries...\n");
        UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);

        // resultFeed.

        File root = new File(args[2]);
        File[] albuns = root.listFiles();

        int j = 0;
        List<GphotoEntry> entries = resultFeed.getEntries();
        for (int i = 0; i < entries.size(); i++) {
            GphotoEntry entry = entries.get(i);
            String href = entry.getHtmlLink().getHref();

            String name = entry.getTitle().getPlainText();

            for (File album : albuns) {
                if (album.getName().equals(name) && !href.contains("02?")) {
                    File picasaini = new File(album, "Picasa.ini");

                    if (!picasaini.exists()) {
                        StringBuilder builder = new StringBuilder();

                        builder.append("\n");
                        builder.append("[Picasa]\n");
                        builder.append("name=");
                        builder.append(name);
                        builder.append("\n");
                        builder.append("location=");
                        Collection<Extension> extensions = entry.getExtensions();

                        for (Extension extension : extensions) {

                            if (extension instanceof GphotoLocation) {
                                GphotoLocation location = (GphotoLocation) extension;
                                if (location.getValue() != null) {
                                    builder.append(location.getValue());
                                }
                            }
                        }
                        builder.append("\n");
                        builder.append("category=Folders on Disk");
                        builder.append("\n");
                        builder.append("date=");
                        String source = name.substring(0, 10);

                        DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");

                        Date date = formater.parse(source);

                        Calendar end = Calendar.getInstance();

                        end.setTime(date);

                        builder.append(daysBetween(start, end));
                        builder.append(".000000");
                        builder.append("\n");
                        builder.append(args[0]);
                        builder.append("_lh=");
                        builder.append(entry.getGphotoId());
                        builder.append("\n");
                        builder.append("P2category=Folders on Disk");
                        builder.append("\n");

                        URL feedUrl = new URL("https://picasaweb.google.com/data/feed/api/user/" + args[0]
                                + "/albumid/" + entry.getGphotoId());

                        AlbumFeed feed = myService.getFeed(feedUrl, AlbumFeed.class);

                        for (GphotoEntry photo : feed.getEntries()) {
                            builder.append("\n");
                            builder.append("[");
                            builder.append(photo.getTitle().getPlainText());
                            builder.append("]");
                            builder.append("\n");
                            long id = Long.parseLong(photo.getGphotoId());

                            builder.append("IIDLIST_");
                            builder.append(args[0]);
                            builder.append("_lh=");
                            builder.append(Long.toHexString(id));
                            builder.append("\n");
                        }

                        System.out.println(builder.toString());
                        IOUtils.write(builder.toString(), new FileOutputStream(picasaini));
                        j++;
                    }
                }

            }

        }
        System.out.println(j);
        System.out.println("\nTotal Entries: " + entries.size());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:cc.twittertools.index.IndexStatuses.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment"));
    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(//from w ww.j  a  v a 2 s.c om
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids")
            .create(DELETES_OPTION));
    options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)
            || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndexStatuses.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);
    String indexPath = cmdline.getOptionValue(INDEX_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexed(true);
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) {
        textOptions.setStoreTermVectors(true);
    }

    LOG.info("collection: " + collectionPath);
    LOG.info("index: " + indexPath);

    LongOpenHashSet deletes = null;
    if (cmdline.hasOption(DELETES_OPTION)) {
        deletes = new LongOpenHashSet();
        File deletesFile = new File(cmdline.getOptionValue(DELETES_OPTION));
        if (!deletesFile.exists()) {
            System.err.println("Error: " + deletesFile + " does not exist!");
            System.exit(-1);
        }
        LOG.info("Reading deletes from " + deletesFile);

        FileInputStream fin = new FileInputStream(deletesFile);
        byte[] ignoreBytes = new byte[2];
        fin.read(ignoreBytes); // "B", "Z" bytes from commandline tools
        BufferedReader br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fin)));

        String s;
        while ((s = br.readLine()) != null) {
            if (s.contains("\t")) {
                deletes.add(Long.parseLong(s.split("\t")[0]));
            } else {
                deletes.add(Long.parseLong(s));
            }
        }
        br.close();
        fin.close();
        LOG.info("Read " + deletes.size() + " tweetids from deletes file.");
    }

    long maxId = Long.MAX_VALUE;
    if (cmdline.hasOption(MAX_ID_OPTION)) {
        maxId = Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION));
        LOG.info("index: " + maxId);
    }

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    StatusStream stream = new JsonStatusCorpusReader(file);

    Directory dir = FSDirectory.open(new File(indexPath));
    IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_43, IndexStatuses.ANALYZER);
    config.setOpenMode(OpenMode.CREATE);

    IndexWriter writer = new IndexWriter(dir, config);
    int cnt = 0;
    Status status;
    try {
        while ((status = stream.next()) != null) {
            if (status.getText() == null) {
                continue;
            }

            // Skip deletes tweetids.
            if (deletes != null && deletes.contains(status.getId())) {
                continue;
            }

            if (status.getId() > maxId) {
                continue;
            }

            cnt++;
            Document doc = new Document();
            doc.add(new LongField(StatusField.ID.name, status.getId(), Field.Store.YES));
            doc.add(new LongField(StatusField.EPOCH.name, status.getEpoch(), Field.Store.YES));
            doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES));

            doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions));

            doc.add(new IntField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount(), Store.YES));
            doc.add(new IntField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount(), Store.YES));
            doc.add(new IntField(StatusField.STATUSES_COUNT.name, status.getStatusesCount(), Store.YES));

            long inReplyToStatusId = status.getInReplyToStatusId();
            if (inReplyToStatusId > 0) {
                doc.add(new LongField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId,
                        Field.Store.YES));
                doc.add(new LongField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId(),
                        Field.Store.YES));
            }

            String lang = status.getLang();
            if (!lang.equals("unknown")) {
                doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES));
            }

            long retweetStatusId = status.getRetweetedStatusId();
            if (retweetStatusId > 0) {
                doc.add(new LongField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId, Field.Store.YES));
                doc.add(new LongField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId(),
                        Field.Store.YES));
                doc.add(new IntField(StatusField.RETWEET_COUNT.name, status.getRetweetCount(), Store.YES));
                if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) {
                    LOG.warn("Error parsing retweet fields of " + status.getId());
                }
            }

            writer.addDocument(doc);
            if (cnt % 100000 == 0) {
                LOG.info(cnt + " statuses indexed");
            }
        }

        LOG.info(String.format("Total of %s statuses added", cnt));

        if (cmdline.hasOption(OPTIMIZE_OPTION)) {
            LOG.info("Merging segments...");
            writer.forceMerge(1);
            LOG.info("Done!");
        }

        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        writer.close();
        dir.close();
        stream.close();
    }
}

From source file:io.anserini.index.IndexTweets.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));
    options.addOption(new Option(OPTIMIZE_OPTION, "merge indexes into a single segment"));
    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("dir").hasArg().withDescription("source collection directory")
            .create(COLLECTION_OPTION));
    options.addOption(//from   w ww  .j  a  va  2 s .  c o  m
            OptionBuilder.withArgName("dir").hasArg().withDescription("index location").create(INDEX_OPTION));
    options.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("file with deleted tweetids")
            .create(DELETES_OPTION));
    options.addOption(OptionBuilder.withArgName("id").hasArg().withDescription("max id").create(MAX_ID_OPTION));

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)
            || !cmdline.hasOption(INDEX_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(IndexTweets.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);
    String indexPath = cmdline.getOptionValue(INDEX_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    if (cmdline.hasOption(STORE_TERM_VECTORS_OPTION)) {
        textOptions.setStoreTermVectors(true);
    }

    LOG.info("collection: " + collectionPath);
    LOG.info("index: " + indexPath);

    LongOpenHashSet deletes = null;
    if (cmdline.hasOption(DELETES_OPTION)) {
        deletes = new LongOpenHashSet();
        File deletesFile = new File(cmdline.getOptionValue(DELETES_OPTION));
        if (!deletesFile.exists()) {
            System.err.println("Error: " + deletesFile + " does not exist!");
            System.exit(-1);
        }
        LOG.info("Reading deletes from " + deletesFile);

        FileInputStream fin = new FileInputStream(deletesFile);
        byte[] ignoreBytes = new byte[2];
        fin.read(ignoreBytes); // "B", "Z" bytes from commandline tools
        BufferedReader br = new BufferedReader(new InputStreamReader(new CBZip2InputStream(fin)));

        String s;
        while ((s = br.readLine()) != null) {
            if (s.contains("\t")) {
                deletes.add(Long.parseLong(s.split("\t")[0]));
            } else {
                deletes.add(Long.parseLong(s));
            }
        }
        br.close();
        fin.close();
        LOG.info("Read " + deletes.size() + " tweetids from deletes file.");
    }

    long maxId = Long.MAX_VALUE;
    if (cmdline.hasOption(MAX_ID_OPTION)) {
        maxId = Long.parseLong(cmdline.getOptionValue(MAX_ID_OPTION));
        LOG.info("index: " + maxId);
    }

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    StatusStream stream = new JsonStatusCorpusReader(file);

    Directory dir = FSDirectory.open(Paths.get(indexPath));
    final IndexWriterConfig config = new IndexWriterConfig(ANALYZER);

    config.setOpenMode(IndexWriterConfig.OpenMode.CREATE);

    IndexWriter writer = new IndexWriter(dir, config);
    int cnt = 0;
    Status status;
    try {
        while ((status = stream.next()) != null) {
            if (status.getText() == null) {
                continue;
            }

            // Skip deletes tweetids.
            if (deletes != null && deletes.contains(status.getId())) {
                continue;
            }

            if (status.getId() > maxId) {
                continue;
            }

            cnt++;
            Document doc = new Document();
            doc.add(new LongPoint(StatusField.ID.name, status.getId()));
            doc.add(new StoredField(StatusField.ID.name, status.getId()));
            doc.add(new LongPoint(StatusField.EPOCH.name, status.getEpoch()));
            doc.add(new StoredField(StatusField.EPOCH.name, status.getEpoch()));
            doc.add(new TextField(StatusField.SCREEN_NAME.name, status.getScreenname(), Store.YES));

            doc.add(new Field(StatusField.TEXT.name, status.getText(), textOptions));

            doc.add(new IntPoint(StatusField.FRIENDS_COUNT.name, status.getFollowersCount()));
            doc.add(new StoredField(StatusField.FRIENDS_COUNT.name, status.getFollowersCount()));
            doc.add(new IntPoint(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount()));
            doc.add(new StoredField(StatusField.FOLLOWERS_COUNT.name, status.getFriendsCount()));
            doc.add(new IntPoint(StatusField.STATUSES_COUNT.name, status.getStatusesCount()));
            doc.add(new StoredField(StatusField.STATUSES_COUNT.name, status.getStatusesCount()));

            long inReplyToStatusId = status.getInReplyToStatusId();
            if (inReplyToStatusId > 0) {
                doc.add(new LongPoint(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId));
                doc.add(new StoredField(StatusField.IN_REPLY_TO_STATUS_ID.name, inReplyToStatusId));
                doc.add(new LongPoint(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId()));
                doc.add(new StoredField(StatusField.IN_REPLY_TO_USER_ID.name, status.getInReplyToUserId()));
            }

            String lang = status.getLang();
            if (!lang.equals("unknown")) {
                doc.add(new TextField(StatusField.LANG.name, status.getLang(), Store.YES));
            }

            long retweetStatusId = status.getRetweetedStatusId();
            if (retweetStatusId > 0) {
                doc.add(new LongPoint(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId));
                doc.add(new StoredField(StatusField.RETWEETED_STATUS_ID.name, retweetStatusId));
                doc.add(new LongPoint(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId()));
                doc.add(new StoredField(StatusField.RETWEETED_USER_ID.name, status.getRetweetedUserId()));
                doc.add(new IntPoint(StatusField.RETWEET_COUNT.name, status.getRetweetCount()));
                doc.add(new StoredField(StatusField.RETWEET_COUNT.name, status.getRetweetCount()));
                if (status.getRetweetCount() < 0 || status.getRetweetedStatusId() < 0) {
                    LOG.warn("Error parsing retweet fields of " + status.getId());
                }
            }

            writer.addDocument(doc);
            if (cnt % 100000 == 0) {
                LOG.info(cnt + " statuses indexed");
            }
        }

        LOG.info(String.format("Total of %s statuses added", cnt));

        if (cmdline.hasOption(OPTIMIZE_OPTION)) {
            LOG.info("Merging segments...");
            writer.forceMerge(1);
            LOG.info("Done!");
        }

        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        writer.close();
        dir.close();
        stream.close();
    }
}

From source file:ch.swisscom.mid.verifier.MobileIdCmsVerifier.java

public static void main(String[] args) {

    if (args == null || args.length < 1) {
        System.out.println("Usage: ch.swisscom.mid.verifier.MobileIdCmsVerifier [OPTIONS]");
        System.out.println();/*from   w ww  . j  a v  a 2 s  .c  o m*/
        System.out.println("Options:");
        System.out.println(
                "  -cms=VALUE or -stdin   - base64 encoded CMS/PKCS7 signature string, either as VALUE or via standard input");
        System.out.println(
                "  -jks=VALUE             - optional path to truststore file (default is 'jks/truststore.jks')");
        System.out.println("  -jkspwd=VALUE          - optional truststore password (default is 'secret')");
        System.out.println();
        System.out.println("Example:");
        System.out.println("  java ch.swisscom.mid.verifier.MobileIdCmsVerifier -cms=MIII...");
        System.out.println("  echo -n MIII... | java ch.swisscom.mid.verifier.MobileIdCmsVerifier -stdin");
        System.exit(1);
    }

    try {

        MobileIdCmsVerifier verifier = null;

        String jks = "jks/truststore.jks";
        String jkspwd = "secret";

        String param;
        for (int i = 0; i < args.length; i++) {
            param = args[i].toLowerCase();
            if (param.contains("-jks=")) {
                jks = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-jkspwd=")) {
                jkspwd = args[i].substring(args[i].indexOf("=") + 1).trim();
            } else if (param.contains("-cms=")) {
                verifier = new MobileIdCmsVerifier(args[i].substring(args[i].indexOf("=") + 1).trim());
            } else if (param.contains("-stdin")) {
                BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
                String stdin;
                if ((stdin = in.readLine()) != null && stdin.length() != 0)
                    verifier = new MobileIdCmsVerifier(stdin.trim());
            }
        }

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream(jks), jkspwd.toCharArray());

        // If you are behind a Proxy..
        // System.setProperty("proxyHost", "10.185.32.54");
        // System.setProperty("proxyPort", "8079");
        // or set it via VM arguments: -DproxySet=true -DproxyHost=10.185.32.54 -DproxyPort=8079

        // Print Issuer/SubjectDN/SerialNumber of all x509 certificates that can be found in the CMSSignedData
        verifier.printAllX509Certificates();

        // Print Signer's X509 Certificate Details
        System.out.println("X509 SignerCert SerialNumber: " + verifier.getX509SerialNumber());
        System.out.println("X509 SignerCert Issuer: " + verifier.getX509IssuerDN());
        System.out.println("X509 SignerCert Subject DN: " + verifier.getX509SubjectDN());
        System.out.println("X509 SignerCert Validity Not Before: " + verifier.getX509NotBefore());
        System.out.println("X509 SignerCert Validity Not After: " + verifier.getX509NotAfter());
        System.out.println("X509 SignerCert Validity currently valid: " + verifier.isCertCurrentlyValid());

        System.out.println("User's unique Mobile ID SerialNumber: " + verifier.getMIDSerialNumber());

        // Print signed content (should be equal to the DTBS Message of the Signature Request)
        System.out.println("Signed Data: " + verifier.getSignedData());

        // Verify the signature on the SignerInformation object
        System.out.println("Signature Valid: " + verifier.isVerified());

        // Validate certificate path against trust anchor incl. OCSP revocation check
        System.out.println("X509 SignerCert Valid (Path+OCSP): " + verifier.isCertValid(keyStore));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.genentech.chemistry.openEye.apps.enumerate.SDFEnumerator.java

public static void main(String... args) throws IOException {
    Options options = new Options();
    Option opt = new Option("out", true, "output file oe-supported");
    opt.setRequired(true);/*from   w  w  w . j  ava 2 s . co m*/
    options.addOption(opt);

    opt = new Option("hydrogenExplicit", false, "Use explicit hydrogens");
    options.addOption(opt);

    opt = new Option("correctValences", false, "Correct valences after the enumeration");
    options.addOption(opt);

    opt = new Option("regenerate2D", false, "Regenerate 2D coordinates for the products");
    options.addOption(opt);

    opt = new Option("reactAllSites", false, "Generate a product for each match in a reagent.");
    options.addOption(opt);

    opt = new Option("randomFraction", true, "Only output a fraction of the products.");
    options.addOption(opt);

    opt = new Option("maxAtoms", true, "Only output products with <= maxAtoms.");
    options.addOption(opt);

    opt = new Option("notReacted", true,
            "Output file for reagents that didn't produce at leaste one output molecule, useful for debugging SMIRKS.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp("", options);
    }

    args = cmd.getArgs();
    if (args.length < 2) {
        exitWithHelp("Transformation and/or reagentFiles missing", options);
    }
    String smirks = args[0];
    if (new File(smirks).canRead())
        smirks = IOUtil.fileToString(smirks).trim();
    if (!smirks.contains(">>"))
        smirks = scaffoldToSmirks(smirks);
    String[] reagentSmiOrFiles = Arrays.copyOfRange(args, 1, args.length);

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String outFile = cmd.getOptionValue("out");
    OELibraryGen lg = new OELibraryGen();
    lg.Init(smirks);
    if (!lg.IsValid())
        exitWithHelp("Invalid Transform: " + smirks, options);

    lg.SetExplicitHydrogens(cmd.hasOption("hydrogenExplicit"));
    lg.SetValenceCorrection(cmd.hasOption("correctValences"));
    lg.SetRemoveUnmappedFragments(true);

    boolean regenerate2D = cmd.hasOption("regenerate2D");
    boolean reactAllSites = cmd.hasOption("reactAllSites");
    String unreactedFile = null;
    if (cmd.hasOption("notReacted")) {
        unreactedFile = cmd.getOptionValue("notReacted");
    }

    double randomFract = 2;
    if (cmd.hasOption("randomFraction"))
        randomFract = Double.parseDouble(cmd.getOptionValue("randomFraction"));

    int maxAtoms = 0;
    if (cmd.hasOption("maxAtoms"))
        maxAtoms = Integer.parseInt(cmd.getOptionValue("maxAtoms"));

    SDFEnumerator en = new SDFEnumerator(lg, reactAllSites, reagentSmiOrFiles);
    en.generateLibrary(outFile, maxAtoms, randomFract, regenerate2D, unreactedFile);
    en.delete();
}

From source file:com.github.fritaly.svngraph.SvnGraph.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.out.println(String.format("%s <input-file> <output-file>", SvnGraph.class.getSimpleName()));
        System.exit(1);/*  w ww  .ja va  2  s  .  c om*/
    }

    final File input = new File(args[0]);

    if (!input.exists()) {
        throw new IllegalArgumentException(
                String.format("The given file '%s' doesn't exist", input.getAbsolutePath()));
    }

    final File output = new File(args[1]);

    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);

    final History history = new History(document);

    final Set<String> rootPaths = history.getRootPaths();

    System.out.println(rootPaths);

    for (String path : rootPaths) {
        System.out.println(path);
        System.out.println(history.getHistory(path).getRevisions());
        System.out.println();
    }

    int count = 0;

    FileWriter fileWriter = null;
    GraphMLWriter graphWriter = null;

    try {
        fileWriter = new FileWriter(output);

        graphWriter = new GraphMLWriter(fileWriter);

        final NodeStyle tagStyle = graphWriter.getNodeStyle();
        tagStyle.setFillColor(Color.WHITE);

        graphWriter.graph();

        // map associating node labels to their corresponding node id in the graph
        final Map<String, String> nodeIdsPerLabel = new TreeMap<>();

        // the node style associated to each branch
        final Map<String, NodeStyle> nodeStyles = new TreeMap<>();

        for (Revision revision : history.getSignificantRevisions()) {
            System.out.println(revision.getNumber() + " - " + revision.getMessage());

            // TODO Render also the deletion of branches
            // there should be only 1 significant update per revision (the one with action ADD)
            for (Update update : revision.getSignificantUpdates()) {
                if (update.isCopy()) {
                    // a merge is also considered a copy
                    final RevisionPath source = update.getCopySource();

                    System.out.println(String.format("  > %s %s from %s@%d", update.getAction(),
                            update.getPath(), source.getPath(), source.getRevision()));

                    final String sourceRoot = Utils.getRootName(source.getPath());

                    if (sourceRoot == null) {
                        // skip the revisions whose associated root is
                        // null (happens whether a branch was created
                        // outside the 'branches' directory for
                        // instance)
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                source.getRevision()));
                        continue;
                    }

                    final String sourceLabel = computeNodeLabel(sourceRoot, source.getRevision());

                    // create a node for the source (path, revision)
                    final String sourceId;

                    if (nodeIdsPerLabel.containsKey(sourceLabel)) {
                        // retrieve the id of the existing node
                        sourceId = nodeIdsPerLabel.get(sourceLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(source.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(sourceRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(sourceRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(sourceRoot));
                        }

                        sourceId = graphWriter.node(sourceLabel);

                        nodeIdsPerLabel.put(sourceLabel, sourceId);
                    }

                    // and another for the newly created directory
                    final String targetRoot = Utils.getRootName(update.getPath());

                    if (targetRoot == null) {
                        System.err.println(String.format("Skipped revision %d because of a null root",
                                revision.getNumber()));
                        continue;
                    }

                    final String targetLabel = computeNodeLabel(targetRoot, revision.getNumber());

                    if (Utils.isTagPath(update.getPath())) {
                        graphWriter.setNodeStyle(tagStyle);
                    } else {
                        if (!nodeStyles.containsKey(targetRoot)) {
                            final NodeStyle style = new NodeStyle();
                            style.setFillColor(randomColor());

                            nodeStyles.put(targetRoot, style);
                        }

                        graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                    }

                    final String targetId;

                    if (nodeIdsPerLabel.containsKey(targetLabel)) {
                        // retrieve the id of the existing node
                        targetId = nodeIdsPerLabel.get(targetLabel);
                    } else {
                        // create the new node
                        if (Utils.isTagPath(update.getPath())) {
                            graphWriter.setNodeStyle(tagStyle);
                        } else {
                            if (!nodeStyles.containsKey(targetRoot)) {
                                final NodeStyle style = new NodeStyle();
                                style.setFillColor(randomColor());

                                nodeStyles.put(targetRoot, style);
                            }

                            graphWriter.setNodeStyle(nodeStyles.get(targetRoot));
                        }

                        targetId = graphWriter.node(targetLabel);

                        nodeIdsPerLabel.put(targetLabel, targetId);
                    }

                    // create an edge between the 2 nodes
                    graphWriter.edge(sourceId, targetId);
                } else {
                    System.out.println(String.format("  > %s %s", update.getAction(), update.getPath()));
                }
            }

            System.out.println();

            count++;
        }

        // Dispatch the revisions per corresponding branch
        final Map<String, Set<Long>> revisionsPerBranch = new TreeMap<>();

        for (String nodeLabel : nodeIdsPerLabel.keySet()) {
            if (nodeLabel.contains("@")) {
                final String branchName = StringUtils.substringBefore(nodeLabel, "@");
                final long revision = Long.parseLong(StringUtils.substringAfter(nodeLabel, "@"));

                if (!revisionsPerBranch.containsKey(branchName)) {
                    revisionsPerBranch.put(branchName, new TreeSet<Long>());
                }

                revisionsPerBranch.get(branchName).add(revision);
            } else {
                throw new IllegalStateException(nodeLabel);
            }
        }

        // Recreate the missing edges between revisions from a same branch
        for (String branchName : revisionsPerBranch.keySet()) {
            final List<Long> branchRevisions = new ArrayList<>(revisionsPerBranch.get(branchName));

            for (int i = 0; i < branchRevisions.size() - 1; i++) {
                final String nodeLabel1 = String.format("%s@%d", branchName, branchRevisions.get(i));
                final String nodeLabel2 = String.format("%s@%d", branchName, branchRevisions.get(i + 1));

                graphWriter.edge(nodeIdsPerLabel.get(nodeLabel1), nodeIdsPerLabel.get(nodeLabel2));
            }
        }

        graphWriter.closeGraph();

        System.out.println(String.format("Found %d significant revisions", count));
    } finally {
        if (graphWriter != null) {
            graphWriter.close();
        }
        if (fileWriter != null) {
            fileWriter.close();
        }
    }

    System.out.println("Done");
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer.java

public static void main(String[] args) {
    connect(HOST, DATABASE, USER, PASSWORD);

    Map<Integer, String> items = new HashMap<Integer, String>();
    Map<Integer, String> failed = new HashMap<Integer, String>();

    // fetch coveredTexts of dubious items and clean it
    PreparedStatement select = null;
    try {//from  w  w  w.jav a 2s .c  om
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.append("SELECT * FROM EvaluationItem ");
        selectQuery.append("WHERE LOCATE(coveredText, '  ') > 0 ");
        selectQuery.append("OR LOCATE('" + LRB + "', coveredText) > 0 ");
        selectQuery.append("OR LOCATE('" + RRB + "', coveredText) > 0 ");
        selectQuery.append("OR LEFT(coveredText, 1) = ' ' ");
        selectQuery.append("OR RIGHT(coveredText, 1) = ' ' ");

        select = connection.prepareStatement(selectQuery.toString());
        log.info("Running query [" + selectQuery.toString() + "].");
        ResultSet rs = select.executeQuery();

        while (rs.next()) {
            int id = rs.getInt("id");
            String coveredText = rs.getString("coveredText");

            try {
                // special handling of double whitespace: in this case, re-fetch the text
                if (coveredText.contains("  ")) {
                    coveredText = retrieveCoveredText(rs.getString("collectionId"), rs.getString("documentId"),
                            rs.getInt("beginOffset"), rs.getInt("endOffset"));
                }

                // replace bracket placeholders and trim the text
                coveredText = StringUtils.replace(coveredText, LRB, "(");
                coveredText = StringUtils.replace(coveredText, RRB, ")");
                coveredText = coveredText.trim();

                items.put(id, coveredText);
            } catch (IllegalArgumentException e) {
                failed.put(id, e.getMessage());
            }
        }
    } catch (SQLException e) {
        log.error("Exception while selecting: " + e.getMessage());
    } finally {
        closeQuietly(select);
    }

    // write logs
    BufferedWriter bwf = null;
    BufferedWriter bws = null;
    try {
        bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(LOG_FAILED)), "UTF-8"));
        for (Entry<Integer, String> e : failed.entrySet()) {
            bwf.write(e.getKey() + " - " + e.getValue() + "\n");
        }

        bws = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(new File(LOG_SUCCESSFUL)), "UTF-8"));
        for (Entry<Integer, String> e : items.entrySet()) {
            bws.write(e.getKey() + " - " + e.getValue() + "\n");
        }
    } catch (IOException e) {
        log.error("Got an IOException while writing the log files.");
    } finally {
        IOUtils.closeQuietly(bwf);
        IOUtils.closeQuietly(bws);
    }

    log.info("Texts for [" + items.size() + "] items need to be cleaned up.");

    // update the dubious items with the cleaned coveredText
    PreparedStatement update = null;
    try {
        String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?";

        update = connection.prepareStatement(updateQuery);
        int i = 0;
        for (Entry<Integer, String> e : items.entrySet()) {
            int id = e.getKey();
            String coveredText = e.getValue();

            // update item in database
            update.setString(1, coveredText);
            update.setInt(2, id);
            update.executeUpdate();
            log.debug("Updating " + id + " with [" + coveredText + "]");

            // show percentage of updated items
            i++;
            int part = (int) Math.ceil((double) items.size() / 100);
            if (i % part == 0) {
                log.info(i / part + "% finished (" + i + "/" + items.size() + ").");
            }
        }
    } catch (SQLException e) {
        log.error("Exception while updating: " + e.getMessage());
    } finally {
        closeQuietly(update);
    }

    closeQuietly(connection);
}

From source file:edu.uci.mhlee.BasicCrawler.java

public static void main(String[] args) {
    String href = "http://aaaa/?alskdjfalk=10";
    String[] aaa = href.split("(\\?.*)?$");
    System.out.println(aaa[0]);/* ww w. j a  va  2s .c  o m*/
    System.out.println(aaa.length);
    Pattern URL_QUERY = Pattern.compile(".*\\.(\\?.*)?$");
    System.out.println(URL_QUERY.matcher(href).matches());
    System.out.println(href.contains("?"));
}

From source file:com.eviware.loadui.launcher.LoadUILauncher.java

public static void main(String[] args) {
    for (String arg : args) {
        System.out.println("LoadUILauncher arg: " + arg);
        if (arg.contains("cmd")) {
            List<String> argList = new ArrayList<>(Arrays.asList(args));
            argList.remove(arg);/*from w w w.  java 2 s  . c  om*/
            String[] newArgs = argList.toArray(new String[argList.size()]);
            Application.launch(CommandApplication.class, newArgs);
            return;
        }
    }

    Application.launch(FXApplication.class, args);

    // Is the below just old legacy code from JavaFX 1?

    //      System.setSecurityManager( null );
    //
    //      LoadUILauncher launcher = new LoadUILauncher( args );
    //      launcher.init();
    //      launcher.start();
    //
    //      new Thread( new LauncherWatchdog( launcher.framework, 20000 ), "loadUI Launcher Watchdog" ).start();
}

From source file:edu.msu.cme.rdp.kmer.KmerFilter.java

public static void main(String[] args) throws Exception {
    final KmerTrie kmerTrie;
    final SeqReader queryReader;
    final SequenceType querySeqType;
    final File queryFile;
    final KmerStartsWriter out;
    final boolean translQuery;
    final int wordSize;
    final int translTable;
    final boolean alignedSeqs;
    final List<String> refLabels = new ArrayList();
    final int maxThreads;

    try {//from   w  ww  .j av a  2s.co  m
        CommandLine cmdLine = new PosixParser().parse(options, args);
        args = cmdLine.getArgs();

        if (args.length < 3) {
            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("aligned")) {
            alignedSeqs = true;
        } else {
            alignedSeqs = false;
        }

        if (cmdLine.hasOption("transl-table")) {
            translTable = Integer.valueOf(cmdLine.getOptionValue("transl-table"));
        } else {
            translTable = 11;
        }

        if (cmdLine.hasOption("threads")) {
            maxThreads = Integer.valueOf(cmdLine.getOptionValue("threads"));
        } else {
            maxThreads = Runtime.getRuntime().availableProcessors();
        }

        queryFile = new File(args[1]);
        wordSize = Integer.valueOf(args[0]);
        SequenceType refSeqType = null;

        querySeqType = SeqUtils.guessSequenceType(queryFile);
        queryReader = new SequenceReader(queryFile);

        if (querySeqType == SequenceType.Protein) {
            throw new Exception("Expected nucl query sequences");
        }

        refSeqType = SeqUtils
                .guessSequenceType(new File(args[2].contains("=") ? args[2].split("=")[1] : args[2]));

        translQuery = refSeqType == SequenceType.Protein;

        if (translQuery && wordSize % 3 != 0) {
            throw new Exception("Word size must be a multiple of 3 for nucl ref seqs");
        }

        int trieWordSize;
        if (translQuery) {
            trieWordSize = wordSize / 3;
        } else {
            trieWordSize = wordSize;
        }
        kmerTrie = new KmerTrie(trieWordSize, translQuery);

        for (int index = 2; 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 (refSeqType != SeqUtils.guessSequenceType(refFile)) {
                throw new Exception(
                        "Reference file " + refFile + " contains " + SeqUtils.guessFileFormat(refFile)
                                + " sequences but expected " + refSeqType + " sequences");
            }

            SequenceReader seqReader = new SequenceReader(refFile);
            Sequence seq;

            while ((seq = seqReader.readNextSequence()) != null) {
                if (seq.getSeqName().startsWith("#")) {
                    continue;
                }
                if (alignedSeqs) {
                    kmerTrie.addModelSequence(seq, refLabels.size());
                } else {
                    kmerTrie.addSequence(seq, refLabels.size());
                }
            }
            seqReader.close();

            refLabels.add(refName);
        }

    } catch (Exception e) {
        new HelpFormatter().printHelp("KmerSearch <word_size> <query_file> [name=]<ref_file> ...", options);
        System.err.println(e.getMessage());
        e.printStackTrace();
        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();
    long seqCount = 0;
    final int maxTasks = 25000;

    /*
     * if (args.length == 4) { maxThreads = Integer.valueOf(args[3]); } else {
     */

    //}

    System.err.println("Starting kmer mapping at " + new Date());
    System.err.println("*  Number of threads:       " + maxThreads);
    System.err.println("*  References:              " + refLabels);
    System.err.println("*  Reads file:              " + queryFile);
    System.err.println("*  Kmer length:             " + kmerTrie.getWordSize());

    final AtomicInteger processed = new AtomicInteger();
    final AtomicInteger outstandingTasks = new AtomicInteger();

    ExecutorService service = Executors.newFixedThreadPool(maxThreads);

    Sequence querySeq;

    while ((querySeq = queryReader.readNextSequence()) != null) {
        seqCount++;

        String seqString = querySeq.getSeqString();

        if (seqString.length() < 3) {
            System.err.println("Sequence " + querySeq.getSeqName() + "'s length is less than 3");
            continue;
        }

        final Sequence threadSeq = querySeq;

        Runnable r = new Runnable() {

            public void run() {
                try {
                    processSeq(threadSeq, refLabels, kmerTrie, out, wordSize, translQuery, translTable, false);
                    processSeq(threadSeq, refLabels, kmerTrie, out, wordSize, translQuery, translTable, true);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                processed.incrementAndGet();
                outstandingTasks.decrementAndGet();
            }
        };

        outstandingTasks.incrementAndGet();
        service.submit(r);

        while (outstandingTasks.get() >= maxTasks)
            ;

        if ((processed.get() + 1) % 1000000 == 0) {
            System.err.println("Processed " + processed + " sequences in "
                    + (System.currentTimeMillis() - startTime) + " ms");
        }
    }

    service.shutdown();
    service.awaitTermination(1, TimeUnit.DAYS);

    System.err.println("Finished Processed " + processed + " sequences in "
            + (System.currentTimeMillis() - startTime) + " ms");

    out.close();
}