Example usage for java.lang StringBuilder StringBuilder

List of usage examples for java.lang StringBuilder StringBuilder

Introduction

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

Prototype

public StringBuilder(CharSequence seq) 

Source Link

Document

Constructs a string builder that contains the same characters as the specified CharSequence .

Usage

From source file:com.cloudhopper.httpclient.util.HttpPostMain.java

static public void main(String[] args) throws Exception {
    ///*  w  w w  . j  a  va2 s . c  o  m*/
    // target urls
    //
    String strURL = "http://209.226.31.233:9009/SendSmsService/b98183b99a1f473839ce569c78b84dbd";

    // Username: Twitter
    // Password: Twitter123

    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    //        for (int i = 0; i < 1; i++) {
    //
    // create a new ticket id
    //
    //String ticketId = TicketUtil.generate(1, System.currentTimeMillis());

    /**
    StringBuilder string0 = new StringBuilder(200)
        .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
        .append("<S:Envelope xmlns:S=\"http://schemas.xmlsoap.org/soap/envelope/\">\n")
        .append("       <S:Header>\n")
        .append("               <ns3:TransactionID xmlns:ns4=\"http://vmp.vzw.com/schema\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\">" + ticketId + "</ns3:TransactionID>\n")
        .append("       </S:Header>\n")
        .append("       <S:Body>\n")
        .append("               <ns2:OptinReq xmlns:ns4=\"http://schemas.xmlsoap.org/soap/envelope/\"\n")
        .append("xmlns:ns3=\"http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-6-MM7-1-4\"\n")
        .append("xmlns:ns2=\"http://vmp.vzw.com/schema\">\n")
        .append("                      <ns2:VASPID>twitter</ns2:VASPID>\n")
        .append("                      <ns2:VASID>tm33t!</ns2:VASID>\n")
        .append("                      <ns2:ShortCode>800080008001</ns2:ShortCode>\n")
        .append("                      <ns2:Number>9257089093</ns2:Number>\n")
        .append("                      <ns2:Source>provider</ns2:Source>\n")
        .append("                      <ns2:Message/>\n")
        .append("               </ns2:OptinReq>\n")
        .append("       </S:Body>\n")
        .append("</S:Envelope>");
     */

    // simple send sms
    StringBuilder string1 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n")
            .append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:loc=\"http://www.csapi.org/schema/parlayx/sms/send/v2_3/local\">\n")
            .append("   <soapenv:Header/>\n").append("   <soapenv:Body>\n").append("      <loc:sendSms>\n")
            .append("         <loc:addresses>tel:+16472260233</loc:addresses>\n")
            .append("         <loc:senderName>6388</loc:senderName>\n")
            .append("         <loc:message>Test Message &</loc:message>\n").append("      </loc:sendSms>\n")
            .append("   </soapenv:Body>\n").append("</soapenv:Envelope>\n");

    // startSmsNotification - place to deliver SMS to

    String req = string1.toString();
    logger.debug("Request XML -> \n" + req);

    HttpPost post = new HttpPost(strURL);

    StringEntity postEntity = new StringEntity(req, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope("209.226.31.233", AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("Twitter", "Twitter123"));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local 
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    //
    // was the request OK?
    //
    if (httpResponse.getStatusLine().getStatusCode() != 200) {
        logger.error("Request failed with StatusCode=" + httpResponse.getStatusLine().getStatusCode());
    }

    // get an input stream
    String responseBody = EntityUtils.toString(responseEntity);

    long stop = System.currentTimeMillis();

    logger.debug("----------------------------------------");
    logger.debug("Response took " + (stop - start) + " ms");
    logger.debug(responseBody);
    logger.debug("----------------------------------------");
    //        }

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();
}

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;/* w w w  .jav a  2s  .  c o  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:net.modelbased.proasense.storage.reader.StorageReaderMongoServiceRestBenchmark.java

public static void main(String[] args) {
    // Get benchmark properties
    StorageReaderMongoServiceRestBenchmark benchmark = new StorageReaderMongoServiceRestBenchmark();
    benchmark.loadClientProperties();/*from  w w w  .j a v  a 2s .c  o  m*/

    // ProaSense Storage Reader Service configuration properties
    String STORAGE_READER_SERVICE_URL = benchmark.clientProperties
            .getProperty("proasense.storage.reader.service.url");

    String QUERY_SIMPLE_COLLECTIONID = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.simple.collectionid");
    String NO_QUERY_SIMPLE_STARTTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.simple.starttime");
    String NO_QUERY_SIMPLE_ENDTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.simple.endtime");

    String QUERY_DERIVED_COLLECTIONID = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.derived.collectionid");
    String NO_QUERY_DERIVED_STARTTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.derived.starttime");
    String NO_QUERY_DERIVED_ENDTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.derived.endtime");

    String QUERY_PREDICTED_COLLECTIONID = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.predicted.collectionid");
    String NO_QUERY_PREDICTED_STARTTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.predicted.starttime");
    String NO_QUERY_PREDICTED_ENDTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.predicted.endtime");

    String QUERY_ANOMALY_COLLECTIONID = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.anomaly.collectionid");
    String NO_QUERY_ANOMALY_STARTTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.anomaly.starttime");
    String NO_QUERY_ANOMALY_ENDTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.anomaly.endtime");

    String QUERY_RECOMMENDATION_COLLECTIONID = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.recommendation.collectionid");
    String NO_QUERY_RECOMMENDATION_STARTTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.recommendation.starttime");
    String NO_QUERY_RECOMMENDATION_ENDTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.recommendation.endtime");

    String QUERY_FEEDBACK_COLLECTIONID = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.feedback.collectionid");
    String NO_QUERY_FEEDBACK_STARTTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.feedback.starttime");
    String NO_QUERY_FEEDBACK_ENDTIME = benchmark.clientProperties
            .getProperty("proasense.benchmark.query.feedback.endtime");

    String propertyKey = "value";

    // Default HTTP client and common property variables for requests
    HttpClient client = new DefaultHttpClient();
    StringBuilder requestUrl = null;
    List<NameValuePair> params = null;
    String queryString = null;
    StatusLine status = null;

    // Default query for simple events
    requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL);
    requestUrl.append("/query/simple/default");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID));
    params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME));
    params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    HttpGet query11 = new HttpGet(requestUrl.toString());
    query11.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query11).getStatusLine();
        System.out.println("SIMPLE.DEFAULT:" + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Average query for simple events
    requestUrl = new StringBuilder(STORAGE_READER_SERVICE_URL);
    requestUrl.append("/query/simple/value");

    params = new LinkedList<NameValuePair>();
    params.add(new BasicNameValuePair("sensorId", QUERY_SIMPLE_COLLECTIONID));
    params.add(new BasicNameValuePair("startTime", NO_QUERY_SIMPLE_STARTTIME));
    params.add(new BasicNameValuePair("endTime", NO_QUERY_SIMPLE_ENDTIME));
    params.add(new BasicNameValuePair("propertyKey", "value"));

    queryString = URLEncodedUtils.format(params, "utf-8");
    requestUrl.append("?");
    requestUrl.append(queryString);

    HttpGet query12 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query12.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query12).getStatusLine();
        System.out.println("SIMPLE.AVERAGE:" + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Maximum query for simple events
    HttpGet query13 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query13.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query13).getStatusLine();
        System.out.println("SIMPLE.MAXIMUM:" + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Minimum query for simple events
    HttpGet query14 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query14.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query14).getStatusLine();
        System.out.println("SIMPLE.MINUMUM:" + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Default query for derived events
    HttpGet query21 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query21.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query21).getStatusLine();
        System.out.println("DERIVED.DEFAULT:" + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Average query for derived events
    HttpGet query22 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query22.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query22).getStatusLine();
        System.out.println("DERIVED.AVERAGE:" + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Maximum query for derived events
    HttpGet query23 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query23.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query23).getStatusLine();
        System.out.println("DERIVED.MAXIMUM: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Minimum query for derived events
    HttpGet query24 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query24.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query24).getStatusLine();
        System.out.println("DERIVED.MINIMUM: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Default query for predicted events
    HttpGet query31 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query31.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query31).getStatusLine();
        System.out.println("PREDICTED.DEFAULT: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Average query for predicted events
    HttpGet query32 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query32.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query32).getStatusLine();
        System.out.println("PREDICTED.AVERAGE: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Maximum query for predicted events
    HttpGet query33 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query33.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query33).getStatusLine();
        System.out.println("PREDICTED.MAXIMUM: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Minimum query for derived events
    HttpGet query34 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query34.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query34).getStatusLine();
        System.out.println("PREDICTED.MINIMUM: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Default query for anomaly events
    HttpGet query41 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query41.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query41).getStatusLine();
        System.out.println("ANOMALY.DEFAULT: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Default query for recommendation events
    HttpGet query51 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query51.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query51).getStatusLine();
        System.out.println("RECOMMENDATION.DEFAULT: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Average query for recommendation events
    HttpGet query52 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query52.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query52).getStatusLine();
        System.out.println("RECOMMENDATION.AVERAGE: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Maximum query for derived events
    HttpGet query53 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query53.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query53).getStatusLine();
        System.out.println("RECOMMENDATION.MAXIMUM: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Minimum query for derived events
    HttpGet query54 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query54.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query54).getStatusLine();
        System.out.println("RECOMMENDATION.MINIMUM: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }

    // Default query for feedback events
    HttpGet query61 = new HttpGet(STORAGE_READER_SERVICE_URL);
    query54.setHeader("Content-type", "application/json");
    try {
        status = client.execute(query54).getStatusLine();
        System.out.println("FEEDBACK.DEFAULT: " + status.toString());
    } catch (Exception e) {
        System.out.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:com.genentech.chemistry.openEye.apps.SDFTopologicalIndexer.java

/**
 * @param args// w w w . ja v a 2s .com
 */
public static void main(String... args) throws IOException { // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    opt.setArgName("fn");
    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 (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    if (args.length == 0) {
        System.err.println("Specify at least one index type");
        exitWithHelp(options);
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    Set<String> selectedIndexes = new HashSet<String>(args.length);
    if (args.length == 1 && "all".equalsIgnoreCase(args[0]))
        selectedIndexes = AVAILIndexes;
    else
        selectedIndexes.addAll(Arrays.asList(args));

    if (!AVAILIndexes.containsAll(selectedIndexes)) {
        selectedIndexes.removeAll(AVAILIndexes);
        StringBuilder err = new StringBuilder("Unknown Index types: ");
        for (String it : selectedIndexes)
            err.append(it).append(" ");
        System.err.println(err);
        exitWithHelp(options);
    }

    SDFTopologicalIndexer sdfIndexer = new SDFTopologicalIndexer(outFile, selectedIndexes);

    sdfIndexer.run(inFile);
    sdfIndexer.close();
}

From source file:de.citec.csra.elancsv.parser.SimpleParser.java

public static void main(String[] args) throws IOException, ParseException {

    Options opts = new Options();
    opts.addOption("file", true, "Tab-separated ELAN export file to load.");
    opts.addOption("tier", true,
            "Tier to analyze. Optional: Append ::num to interpret annotations numerically.");
    opts.addOption("format", true,
            "How to read information from the file name. %V -> participant, %A -> annoatator, %C -> condition, e.g. \"%V - %A\"");
    opts.addOption("help", false, "Print this help and exit");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = parser.parse(opts, args);
    if (cmd.hasOption("help")) {
        helpExit(opts, "where OPTION includes:");
    }/*from  ww w .  java 2 s. c om*/

    String infile = cmd.getOptionValue("file");
    if (infile == null) {
        helpExit(opts, "Error: no file given.");
    }

    String format = cmd.getOptionValue("format");
    if (format == null) {
        helpExit(opts, "Error: no format given.");
    }

    String tier = cmd.getOptionValue("tier");
    if (tier == null) {
        helpExit(opts, "Error: no tier given.");
    }

    //      TODO count values in annotations (e.g. search all robot occurrences)
    String[] tn = tier.split("::");
    boolean numeric = false;
    if (tn.length == 2 && tn[1].equals("num")) {
        numeric = true;
        tier = tn[0];
    }

    format = "^" + format + "$";
    format = format.replaceFirst("%V", "(?<V>.*?)");
    format = format.replaceFirst("%A", "(?<A>.*?)");
    format = format.replaceFirst("%C", "(?<C>.*?)");
    Pattern pa = Pattern.compile(format);

    Map<String, Participant> participants = new HashMap<>();
    BufferedReader br = new BufferedReader(new FileReader(infile));
    String line;
    int lineno = 0;
    while ((line = br.readLine()) != null) {
        String[] parts = line.split("\t");
        lineno++;
        if (parts.length < 5) {
            System.err.println("WARNING: line '" + lineno + "' too short '" + line + "'");
            continue;
        }
        Annotation a = new Annotation(Long.valueOf(parts[ElanFormat.START.field]),
                Long.valueOf(parts[ElanFormat.STOP.field]), Long.valueOf(parts[ElanFormat.DURATION.field]),
                parts[ElanFormat.VALUE.field]);
        String tname = parts[ElanFormat.TIER.field];
        String file = parts[ElanFormat.FILE.field].replaceAll(".eaf", "");

        Matcher m = pa.matcher(file);
        String vp = file;
        String condition = "?";
        String annotator = "?";
        String participantID = vp;

        if (m.find()) {
            vp = m.group("V");
            if (format.indexOf("<A>") > 0) {
                annotator = m.group("A");
            }

            if (format.indexOf("<C>") > 0) {
                condition = m.group("C");
            }
        }
        participantID = vp + ";" + annotator;

        if (!participants.containsKey(participantID)) {
            participants.put(participantID, new Participant(vp, condition, annotator));
        }
        Participant p = participants.get(participantID);

        if (!p.tiers.containsKey(tname)) {
            p.tiers.put(tname, new Tier(tname));
        }

        p.tiers.get(tname).annotations.add(a);

    }

    Map<String, Map<String, Number>> values = new HashMap<>();
    Set<String> rownames = new HashSet<>();

    String allCountKey = "c: all values";
    String allDurationKey = "d: all values";
    String allMeanKey = "m: all values";

    for (Map.Entry<String, Participant> e : participants.entrySet()) {
        //         System.out.println(e);
        Tier t = e.getValue().tiers.get(tier);
        String participantID = e.getKey();

        if (!values.containsKey(participantID)) {
            values.put(participantID, new HashMap<String, Number>());
        }
        Map<String, Number> row = values.get(participantID); //participant id

        if (t != null) {

            row.put(allCountKey, 0l);
            row.put(allDurationKey, 0l);
            row.put(allMeanKey, 0l);

            for (Annotation a : t.annotations) {

                long countAll = (long) row.get(allCountKey) + 1;
                long durationAll = (long) row.get(allDurationKey) + a.duration;
                long meanAll = durationAll / countAll;

                row.put(allCountKey, countAll);
                row.put(allDurationKey, durationAll);
                row.put(allMeanKey, meanAll);

                if (!numeric) {
                    String countKey = "c: " + a.value;
                    String durationKey = "d: " + a.value;
                    String meanKey = "m: " + a.value;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(durationKey)) {
                        row.put(durationKey, 0l);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    long count = (long) row.get(countKey) + 1;
                    long duration = (long) row.get(durationKey) + a.duration;
                    double mean = duration * 1.0 / count;

                    row.put(countKey, count);
                    row.put(durationKey, duration);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(durationKey);
                    rownames.add(meanKey);
                } else {
                    String countKey = "c: " + t.name;
                    String sumKey = "s: " + t.name;
                    String meanKey = "m: " + t.name;

                    if (!row.containsKey(countKey)) {
                        row.put(countKey, 0l);
                    }
                    if (!row.containsKey(sumKey)) {
                        row.put(sumKey, 0d);
                    }
                    if (!row.containsKey(meanKey)) {
                        row.put(meanKey, 0d);
                    }

                    double d = 0;
                    try {
                        d = Double.valueOf(a.value);
                    } catch (NumberFormatException ex) {

                    }

                    long count = (long) row.get(countKey) + 1;
                    double sum = (double) row.get(sumKey) + d;
                    double mean = sum / count;

                    row.put(countKey, count);
                    row.put(sumKey, sum);
                    row.put(meanKey, mean);

                    rownames.add(countKey);
                    rownames.add(sumKey);
                    rownames.add(meanKey);
                }

            }
        }

    }

    ArrayList<String> list = new ArrayList(rownames);
    Collections.sort(list);
    StringBuilder header = new StringBuilder("ID;Annotator;");
    header.append(allCountKey);
    header.append(";");
    header.append(allDurationKey);
    header.append(";");
    header.append(allMeanKey);
    header.append(";");
    for (String l : list) {
        header.append(l);
        header.append(";");
    }
    System.out.println(header);

    for (Map.Entry<String, Map<String, Number>> e : values.entrySet()) {
        StringBuilder row = new StringBuilder(e.getKey());
        row.append(";");
        if (e.getValue().containsKey(allCountKey)) {
            row.append(e.getValue().get(allCountKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allDurationKey)) {
            row.append(e.getValue().get(allDurationKey));
        } else {
            row.append("0");
        }
        row.append(";");
        if (e.getValue().containsKey(allMeanKey)) {
            row.append(e.getValue().get(allMeanKey));
        } else {
            row.append("0");
        }
        row.append(";");
        for (String l : list) {
            if (e.getValue().containsKey(l)) {
                row.append(e.getValue().get(l));
            } else {
                row.append("0");
            }
            row.append(";");
        }
        System.out.println(row);
    }
}

From source file:Main.java

public static String MemoryToString(long l) {
    return (new StringBuilder(String.valueOf(String.valueOf(l / 1024L / 1024L)))).append("M").toString();
}

From source file:Main.java

static boolean isPalindrome(String text) {
    System.out.println("Original text = " + text);

    String reverse = new StringBuilder(text).reverse().toString();
    System.out.println("Reverse text  = " + reverse);
    return text.equalsIgnoreCase(reverse);
}

From source file:Main.java

public static String pad(int hour, int minute) {
    return new StringBuilder(pad(hour)).append(":").append(pad(minute)).toString();
}

From source file:Main.java

private static String getVirtualImei() {
    StringBuilder result = new StringBuilder("1234567");
    for (int i = 0; i < 8; i++) {
        result.append((int) (Math.random() * 10));
    }/*from w w  w .j  a  v a  2 s  .co  m*/
    return result.toString();
}

From source file:Main.java

public static String byteArrayToHex(byte[] a) {
    StringBuilder sb = new StringBuilder(a.length * 2);
    for (byte b : a)
        sb.append(String.format("%02x", b & 0xff));
    return sb.toString();
}