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, int endIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:com.gzj.tulip.jade.statement.SystemInterpreter.java

public static void main(String[] args) throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("table", "my_table_name");
    parameters.put("id", "my_id");
    parameters.put(":1", "first_param");

    final Pattern PATTERN = Pattern.compile("\\{([a-zA-Z0-9_\\.\\:]+)\\}|##\\((.+)\\)");

    String sql = "select form ##(:table) {name} where {id}='{1}'";

    StringBuilder sb = new StringBuilder(sql.length() + 200);
    Matcher matcher = PATTERN.matcher(sql);
    int start = 0;
    while (matcher.find(start)) {
        sb.append(sql.substring(start, matcher.start()));
        String group = matcher.group();
        String key = null;//from   w  ww  .j  a  va 2  s  . co  m
        if (group.startsWith("{")) {
            key = matcher.group(1);
        } else if (group.startsWith("##(")) {
            key = matcher.group(2);
        }
        System.out.println(key);
        if (key == null || key.length() == 0) {
            continue;
        }
        Object value = parameters.get(key); // {paramName}?{:1}?
        if (value == null) {
            if (key.startsWith(":") || key.startsWith("$")) {
                value = parameters.get(key.substring(1)); // {:paramName}
            } else {
                char ch = key.charAt(0);
                if (ch >= '0' && ch <= '9') {
                    value = parameters.get(":" + key); // {1}?
                }
            }
        }
        if (value == null) {
            value = parameters.get(key); // ?
        }
        if (value != null) {
            sb.append(value);
        } else {
            sb.append(group);
        }
        start = matcher.end();
    }
    sb.append(sql.substring(start));
    System.out.println(sb);

}

From source file:com.glaf.jbpm.action.MultiPooledTaskInstanceAction.java

public static void main(String[] args) throws Exception {
    String actorIdxy = "{joy,sam},{pp,qq},{kit,cora},{eyb2000,huangcw}";
    StringTokenizer st2 = new StringTokenizer(actorIdxy, ";");
    while (st2.hasMoreTokens()) {
        String elem2 = st2.nextToken();
        if (StringUtils.isNotEmpty(elem2)) {
            elem2 = elem2.trim();//from w  ww  . j ava 2  s . com
            if ((elem2.length() > 0 && elem2.charAt(0) == '{') && elem2.endsWith("}")) {
                elem2 = elem2.substring(elem2.indexOf("{") + 1, elem2.indexOf("}"));
                Set<String> actorIds = new HashSet<String>();
                StringTokenizer st4 = new StringTokenizer(elem2, ",");
                while (st4.hasMoreTokens()) {
                    String elem4 = st4.nextToken();
                    elem4 = elem4.trim();
                    if (elem4.length() > 0) {
                        actorIds.add(elem4);
                    }
                }
                System.out.println(actorIds);
            }
        }
    }
}

From source file:client.MultiplexingClient.java

public static void main(String[] args) throws Exception {
    // Prepare to parse the command line
    Options options = new Options();
    Option sslOpt = new Option("s", "ssl", false, "Use SSL");
    Option debugOpt = new Option("d", true,
            "Debug level (NONE, FINER, FINE, CONFIG, INFO, WARNING, SEVERE. Default INFO.");
    Option numConnectionsOpt = new Option("n", true, "Number of connections to establish. [Default: 1]");
    Option numPcktOpt = new Option("p", true, "Number of packets to send in each connection. [Default: 20]");
    Option pcktMaxSizeOpt = new Option("m", true, "Maximum size of packets. [Default: 4096]");
    Option help = new Option("h", "print this message");

    options.addOption(help);/*from  ww w . j a v  a2  s.com*/
    options.addOption(debugOpt);
    options.addOption(numConnectionsOpt);
    options.addOption(numPcktOpt);
    options.addOption(pcktMaxSizeOpt);
    options.addOption(sslOpt);
    CommandLineParser parser = new PosixParser();
    // parse the command line arguments
    CommandLine line = parser.parse(options, args);

    if (line.hasOption(help.getOpt()) || line.getArgs().length < 1) {
        showUsage(options);
        return;
    }

    if (line.hasOption(sslOpt.getOpt())) {
        channelFactory = new SSLChannelFactory(true, TRUSTSTORE, TRUSTSTORE_PASSWORD);
    } else {
        channelFactory = new PlainChannelFactory();
    }

    if (line.hasOption(numConnectionsOpt.getOpt())) {
        connectionCount = Integer.parseInt(line.getOptionValue(numConnectionsOpt.getOpt()));
    } else {
        connectionCount = 1;
    }

    if (line.hasOption(numPcktOpt.getOpt())) {
        packetsToSend = Integer.parseInt(line.getOptionValue(numPcktOpt.getOpt()));
    } else {
        packetsToSend = 20;
    }

    if (line.hasOption(pcktMaxSizeOpt.getOpt())) {
        maxPcktSize = Integer.parseInt(line.getOptionValue(pcktMaxSizeOpt.getOpt()));
    } else {
        maxPcktSize = 4096;
    }

    InetSocketAddress remotePoint;
    try {
        String host = line.getArgs()[0];
        int colonIndex = host.indexOf(':');
        remotePoint = new InetSocketAddress(host.substring(0, colonIndex),
                Integer.parseInt(host.substring(colonIndex + 1)));
    } catch (Exception e) {
        showUsage(options);
        return;
    }

    // Setups the logging context for Log4j
    //     NDC.push(Thread.currentThread().getName());

    st = new SelectorThread();
    for (int i = 0; i < connectionCount; i++) {
        new MultiplexingClient(remotePoint);
        // Must sleep for a while between opening connections in order
        // to give the remote host enough time to handle them. Otherwise,
        // the remote host backlog will get full and the connection
        // attemps will start to be refused.
        Thread.sleep(100);
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step6HITPreparator.java

public static void main(String[] args) throws Exception {
    // input dir - list of xml query containers
    // step5-linguistic-annotation/
    System.err.println("Starting step 6 HIT Preparation");

    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (outputDir.exists()) {
        outputDir.delete();//from   ww w.  java2 s  . co  m
    }
    outputDir.mkdir();

    List<String> queries = new ArrayList<>();

    // iterate over query containers
    int countClueWeb = 0;
    int countSentence = 0;
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        if (queries.contains(f.getName()) || queries.size() == 0) {
            // groups contain only non-empty documents
            Map<Integer, List<QueryResultContainer.SingleRankedResult>> groups = new HashMap<>();

            // split to groups according to number of sentences
            for (QueryResultContainer.SingleRankedResult rankedResult : queryResultContainer.rankedResults) {
                if (rankedResult.originalXmi != null) {
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));
                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    Collection<Sentence> sentences = JCasUtil.select(jCas, Sentence.class);

                    int groupId = sentences.size() / 40;
                    if (rankedResult.originalXmi == null) {
                        System.err.println("Empty document: " + rankedResult.clueWebID);
                    } else {
                        if (!groups.containsKey(groupId)) {
                            groups.put(groupId, new ArrayList<>());

                        }
                    }
                    //handle it
                    groups.get(groupId).add(rankedResult);
                    countClueWeb++;
                }
            }

            for (Map.Entry<Integer, List<QueryResultContainer.SingleRankedResult>> entry : groups.entrySet()) {
                Integer groupId = entry.getKey();
                List<QueryResultContainer.SingleRankedResult> rankedResults = entry.getValue();

                // make sure the results are sorted
                // DEBUG
                //                for (QueryResultContainer.SingleRankedResult r : rankedResults) {
                //                    System.out.print(r.rank + "\t");
                //                }

                Collections.sort(rankedResults, (o1, o2) -> o1.rank.compareTo(o2.rank));

                // iterate over results for one query and group
                for (int i = 0; i < rankedResults.size() && i < TOP_RESULTS_PER_GROUP; i++) {
                    QueryResultContainer.SingleRankedResult rankedResult = rankedResults.get(i);

                    QueryResultContainer.SingleRankedResult r = rankedResults.get(i);
                    int rank = r.rank;
                    MustacheFactory mf = new DefaultMustacheFactory();
                    Mustache mustache = mf.compile("template/template.html");
                    String queryId = queryResultContainer.qID;
                    String query = queryResultContainer.query;
                    // make the first letter uppercase
                    query = query.substring(0, 1).toUpperCase() + query.substring(1);

                    List<String> relevantInformationExamples = queryResultContainer.relevantInformationExamples;
                    List<String> irrelevantInformationExamples = queryResultContainer.irrelevantInformationExamples;
                    byte[] bytes = new BASE64Decoder()
                            .decodeBuffer(new ByteArrayInputStream(rankedResult.originalXmi.getBytes()));

                    JCas jCas = JCasFactory.createJCas();
                    XmiCasDeserializer.deserialize(new ByteArrayInputStream(bytes), jCas.getCas());

                    List<generators.Sentence> sentences = new ArrayList<>();
                    List<Integer> paragraphs = new ArrayList<>();
                    paragraphs.add(0);

                    for (WebParagraph webParagraph : JCasUtil.select(jCas, WebParagraph.class)) {
                        for (Sentence s : JCasUtil.selectCovered(Sentence.class, webParagraph)) {

                            String sentenceBegin = String.valueOf(s.getBegin());
                            generators.Sentence sentence = new generators.Sentence(s.getCoveredText(),
                                    sentenceBegin);
                            sentences.add(sentence);
                            countSentence++;
                        }
                        int SentenceID = paragraphs.get(paragraphs.size() - 1);
                        if (sentences.size() > 120)
                            while (SentenceID < sentences.size()) {
                                if (!paragraphs.contains(SentenceID))
                                    paragraphs.add(SentenceID);
                                SentenceID = SentenceID + 120;
                            }
                        paragraphs.add(sentences.size());

                    }
                    System.err.println("Output dir: " + outputDir);
                    int startID = 0;
                    int endID;

                    for (int j = 0; j < paragraphs.size(); j++) {

                        endID = paragraphs.get(j);
                        int sentLength = endID - startID;
                        if (sentLength > 120 || j == paragraphs.size() - 1) {
                            if (sentLength > 120) {

                                endID = paragraphs.get(j - 1);
                                j--;
                            }
                            sentLength = endID - startID;
                            if (sentLength <= 40)
                                groupId = 40;
                            else if (sentLength <= 80 && sentLength > 40)
                                groupId = 80;
                            else if (sentLength > 80)
                                groupId = 120;

                            File folder = new File(outputDir + "/" + groupId);
                            if (!folder.exists()) {
                                System.err.println("creating directory: " + outputDir + "/" + groupId);
                                boolean result = false;

                                try {
                                    folder.mkdir();
                                    result = true;
                                } catch (SecurityException se) {
                                    //handle it
                                }
                                if (result) {
                                    System.out.println("DIR created");
                                }
                            }

                            String newHtmlFile = folder.getAbsolutePath() + "/" + f.getName() + "_"
                                    + rankedResult.clueWebID + "_" + sentLength + ".html";
                            System.err.println("Printing a file: " + newHtmlFile);
                            File newHTML = new File(newHtmlFile);
                            int t = 0;
                            while (newHTML.exists()) {
                                newHTML = new File(folder.getAbsolutePath() + "/" + f.getName() + "_"
                                        + rankedResult.clueWebID + "_" + sentLength + "." + t + ".html");
                                t++;
                            }
                            mustache.execute(new PrintWriter(new FileWriter(newHTML)),
                                    new generators(query, relevantInformationExamples,
                                            irrelevantInformationExamples, sentences.subList(startID, endID),
                                            queryId, rank))
                                    .flush();
                            startID = endID;
                        }
                    }
                }
            }

        }
    }
    System.out.println("Printed " + countClueWeb + " documents with " + countSentence + " sentences");
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    Document document = new Document(PageSize.A6);
    PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    document.open();// w w w . j  a v  a 2s  .co  m
    document.add(new Paragraph("Hello World"));
    document.add(new Paragraph("Hello People"));
    document.close();

    PdfReader reader = new PdfReader("2.pdf");
    PdfDictionary page = reader.getPageN(1);
    PRIndirectReference objectReference = (PRIndirectReference) page.get(PdfName.CONTENTS);
    PRStream stream = (PRStream) PdfReader.getPdfObject(objectReference);
    byte[] streamBytes = PdfReader.getStreamBytes(stream);
    String contentStream = new String(streamBytes);
    System.out.println(contentStream);
    PRTokeniser tokenizer = new PRTokeniser(streamBytes);
    while (tokenizer.nextToken()) {
        if (tokenizer.getTokenType() == PRTokeniser.TK_STRING) {
            System.out.println(tokenizer.getStringValue());
        }
    }
    StringBuffer buf = new StringBuffer();
    int pos = contentStream.indexOf("Hello World") + 11;
    buf.append(contentStream.substring(0, pos));
    buf.append("Hello");
    buf.append(contentStream.substring(pos));
    String hackedContentStream = buf.toString();
    document = new Document(PageSize.A6);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorldStreamHacked.pdf"));
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    cb.setLiteral(hackedContentStream);
    document.close();
}

From source file:edu.msu.cme.rdp.classifier.train.validation.distance.TaxaSimilarityMain.java

/**
 * This calculates the average similarity (Sab score or pairwise alignment) between taxa at given ranks and plot the box and whisker plot and accumulation curve. 
 * The distances associate to a given rank contains the distances between different child taxa. It does not include the distances within the same child taxa.
 * For example, if a query and it's closest match are from the same genus, the distance value is added to that genus.
 * If there are from different genera but the same family, the distance value is added to that family, etc.
 * @param args/*from ww  w .j a  va2  s.c  o  m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException, OverlapCheckFailedException {
    String usage = "Usage: taxonfile trainset.fasta query.fasta outdir kmersize rankFile sab|pw \n"
            + "  This program calculates the average similarity (Sab score, or pairwise alignment) within taxa\n"
            + "  and plot the box and whisker plot and accumulation curve plot. \n"
            + "  rankFile: a file contains a list of ranks to be calculated and plotted. One rank per line, no particular order required. \n"
            + "  Note pw is extremely slower, recommended only for lower ranks such as species, genus and family. ";

    if (args.length != 7) {
        System.err.println(usage);
        System.exit(1);
    }
    List<String> ranks = readRanks(args[5]);
    File outdir = new File(args[3]);
    if (!outdir.isDirectory()) {
        System.err.println("outdir must be a directory");
        System.exit(1);
    }
    int kmer = Integer.parseInt(args[4]);
    GoodWordIterator.setWordSize(kmer);
    TaxaSimilarityMain theObj = new TaxaSimilarityMain(ranks);

    String plotTitle = new File(args[2]).getName();
    int index = plotTitle.indexOf(".");
    if (index != -1) {
        plotTitle = plotTitle.substring(0, index);
    }
    if (args[6].equalsIgnoreCase("sab")) {
        theObj.calSabSimilarity(args[0], args[1], args[2]);
    } else {
        theObj.calPairwiseSimilaritye(args[0], args[1], args[2]);
    }

    theObj.createPlot(plotTitle, outdir);

}

From source file:kilim.tools.DumpClass.java

public static void main(String[] args) throws IOException {
    String name = args.length == 2 ? args[1] : args[0];

    if (name.endsWith(".jar")) {
        try {/*from w  w  w .  ja va 2 s . c  om*/
            Enumeration<JarEntry> e = new JarFile(name).entries();
            while (e.hasMoreElements()) {
                ZipEntry en = (ZipEntry) e.nextElement();
                String n = en.getName();
                if (!n.endsWith(".class"))
                    continue;
                n = n.substring(0, n.length() - 6).replace('/', '.');
                new DumpClass(n);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        new DumpClass(name);
    }
}

From source file:com.mycompany.test.Jaroop.java

/**
 * This is the main program which will receive the request, calls required methods
 * and processes the response.//  w ww.  j  av  a 2  s.  c  o m
 * @param args
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Scanner scannedInput = new Scanner(System.in);
    String in = "";
    if (args.length == 0) {
        System.out.println("Enter the query");
        in = scannedInput.nextLine();
    } else {
        in = args[0];
    }
    in = in.toLowerCase().replaceAll("\\s+", "_");
    int httpStatus = checkInvalidInput(in);
    if (httpStatus == 0) {
        System.out.print("Not found");
        System.exit(0);
    }
    String url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles="
            + in;
    HttpURLConnection connection = getConnection(url);
    BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String request = "";
    StringBuilder response = new StringBuilder();
    while ((request = input.readLine()) != null) {
        //only appending what ever is required for JSON parsing and ignoring the rest
        response.append("{");
        //appending the key "extract" to the string so that the JSON parser can parse it's value,
        //also we don't need last 3 paranthesis in the response, excluding them as well.
        response.append(request.substring(request.indexOf("\"extract"), request.length() - 3));
    }
    parseJSON(response.toString());
}

From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java

public static void main(String[] args) {
    Options options = new Options();

    options.addOption("u", null, true, "Solr URI");
    options.addOption("q", null, true, "Query");
    options.addOption("n", null, true, "Max # of results");
    options.addOption("o", null, true, "An optional TREC-style output file");
    options.addOption("w", null, false, "Do a warm-up query call, before each query");

    CommandLineParser parser = new org.apache.commons.cli.GnuParser();

    BufferedWriter trecOutFile = null;

    try {/*from  ww w  . ja va2s .  c  om*/
        CommandLine cmd = parser.parse(options, args);
        String queryFile = null, solrURI = null;

        if (cmd.hasOption("u")) {
            solrURI = cmd.getOptionValue("u");
        } else {
            Usage("Specify Solr URI");
        }

        SolrServerWrapper solr = new SolrServerWrapper(solrURI);

        if (cmd.hasOption("q")) {
            queryFile = cmd.getOptionValue("q");
        } else {
            Usage("Specify Query file");
        }

        int numRet = 100;

        if (cmd.hasOption("n")) {
            numRet = Integer.parseInt(cmd.getOptionValue("n"));
        }

        if (cmd.hasOption("o")) {
            trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o"))));
        }

        List<String> fieldList = new ArrayList<String>();
        fieldList.add(UtilConst.ID_FIELD);
        fieldList.add(UtilConst.SCORE_FIELD);

        double totalTime = 0;
        double retQty = 0;

        ArrayList<Double> queryTimes = new ArrayList<Double>();

        boolean bDoWarmUp = cmd.hasOption("w");

        if (bDoWarmUp) {
            System.out.println("Using a warmup step!");
        }

        int queryQty = 0;
        for (String t : FileUtils.readLines(new File(queryFile))) {
            t = t.trim();
            if (t.isEmpty())
                continue;
            int ind = t.indexOf('|');
            if (ind < 0)
                throw new Exception("Wrong format, line: '" + t + "'");
            String qID = t.substring(0, ind);
            String q = t.substring(ind + 1);

            SolrDocumentList res = null;

            if (bDoWarmUp) {
                res = solr.runQuery(q, fieldList, numRet);
            }

            Long tm1 = System.currentTimeMillis();
            res = solr.runQuery(q, fieldList, numRet);
            Long tm2 = System.currentTimeMillis();
            retQty += res.getNumFound();
            System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms");
            double delta = (tm2 - tm1);
            totalTime += delta;
            queryTimes.add(delta);
            ++queryQty;

            if (trecOutFile != null) {

                ArrayList<SolrRes> resArr = new ArrayList<SolrRes>();
                for (SolrDocument doc : res) {
                    String id = (String) doc.getFieldValue(UtilConst.ID_FIELD);
                    float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD);
                    resArr.add(new SolrRes(id, "", score));
                }
                SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]);
                Arrays.sort(results);

                SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length);
            }
        }
        double devTime = 0, meanTime = totalTime / queryQty;
        for (int i = 0; i < queryQty; ++i) {
            double d = queryTimes.get(i) - meanTime;
            devTime += d * d;
        }
        devTime = Math.sqrt(devTime / (queryQty - 1));
        System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime));
        System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty));

        solr.close();
        trecOutFile.close();
    } catch (ParseException e) {
        Usage("Cannot parse arguments");
    } catch (Exception e) {
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }

}

From source file:de.uni_rostock.goodod.evaluator.EvaluatorApp.java

public static void main(String[] args) {
    Logger root = Logger.getRootLogger();
    if (false == root.getAllAppenders().hasMoreElements()) {
        root.addAppender(new ConsoleAppender(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
        root.setLevel(Level.INFO);
    }/*from ww  w  . ja  v  a 2 s . c om*/
    config = Configuration.getConfiguration(args);

    if (config.getBoolean("helpMode", false)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("evaluator [option]... <test_spec.plist | ontology1.owl ontology2.owl> ",
                config.getOptions());
        System.exit(0);
    }

    if (config.getBoolean("debug", false)) {
        root.setLevel(Level.DEBUG);
    }

    OntologyTest theTest = null;
    String testFile = config.getString("testFile");
    try {
        theTest = new OntologyTest(config.configurationAt("testDescription"));
        theTest.executeTest();
    } catch (Throwable e) {
        logger.fatal("Fatal error", e);
        System.exit(1);
    }

    logger.info(theTest.toString());
    String similarityType = config.getString("similarity");

    String baseName = similarityType + "-" + testFile.substring(0, (testFile.length() - 6));

    File precisionFile = null;
    File recallFile = null;
    File fmeasureFile = null;
    File similarityFile = null;

    precisionFile = new File(baseName + ".precision.csv");
    recallFile = new File(baseName + ".recall.csv");
    fmeasureFile = new File(baseName + ".fmeasure.csv");
    similarityFile = new File(baseName + ".csv");

    try {
        if (theTest.providesFMeasure()) {
            theTest.writePrecisionTable(new FileWriter(precisionFile));
            theTest.writeRecallTable(new FileWriter(recallFile));
            theTest.writeFMeasureTable(new FileWriter(fmeasureFile));
        } else {
            theTest.writeSimilarityTable(new FileWriter(similarityFile));
        }
    } catch (IOException e) {
        logger.warn("Could not write test data", e);
    }
}