Example usage for java.lang StringBuilder toString

List of usage examples for java.lang StringBuilder toString

Introduction

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

Prototype

@Override
    @HotSpotIntrinsicCandidate
    public String toString() 

Source Link

Usage

From source file:dhtaccess.benchmark.LatencyMeasure.java

public static void main(String[] args) {
    boolean details = false;
    int repeats = DEFAULT_REPEATS;
    boolean doPut = true;

    // parse options
    Options options = new Options();
    options.addOption("h", "help", false, "print help");
    options.addOption("d", "details", false, "requests secret hash and TTL");
    options.addOption("r", "repeats", true, "number of requests");
    options.addOption("n", "no-put", false, "does not put");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/* w  w  w  .  j  a v  a  2  s.c om*/
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println("There is an invalid option.");
        e.printStackTrace();
        System.exit(1);
    }

    String optVal;
    if (cmd.hasOption('h')) {
        usage(COMMAND);
        System.exit(1);
    }
    if (cmd.hasOption('d')) {
        details = true;
    }
    optVal = cmd.getOptionValue('r');
    if (optVal != null) {
        repeats = Integer.parseInt(optVal);
    }
    if (cmd.hasOption('n')) {
        doPut = false;
    }

    args = cmd.getArgs();

    // parse arguments
    if (args.length < 1) {
        usage(COMMAND);
        System.exit(1);
    }

    // prepare for RPC
    int numAccessor = args.length;
    DHTAccessor[] accessorArray = new DHTAccessor[numAccessor];
    try {
        for (int i = 0; i < numAccessor; i++) {
            accessorArray[i] = new DHTAccessor(args[i]);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        System.exit(1);
    }

    // generate key prefix
    Random rnd = new Random(System.currentTimeMillis());

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < KEY_PREFIX_LENGTH; i++) {
        sb.append((char) ('a' + rnd.nextInt(26)));
    }
    String keyPrefix = sb.toString();
    String valuePrefix = VALUE_PREFIX;

    // benchmarking
    System.out.println("Repeats " + repeats + " times.");

    if (doPut) {
        System.out.println("Putting: " + keyPrefix + "<number>");

        for (int i = 0; i < repeats; i++) {
            byte[] key = null, value = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
                value = (valuePrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            acc.put(key, value, TTL);
        }
    }

    System.out.println("Benchmarking by getting.");

    int count = 0;
    long startTime = System.currentTimeMillis();

    if (details) {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<DetailedGetResult> valueSet = acc.getDetails(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    } else {
        for (int i = 0; i < repeats; i++) {
            byte[] key = null;
            try {
                key = (keyPrefix + i).getBytes(ENCODE);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(1);
            }

            int accIndex = rnd.nextInt(numAccessor);
            DHTAccessor acc = accessorArray[accIndex];
            Set<byte[]> valueSet = acc.get(key);
            if (valueSet != null && !valueSet.isEmpty()) {
                count++;
            }
        }
    }

    System.out.println(System.currentTimeMillis() - startTime + " msec.");
    System.out.println("Rate of successful gets: " + count + " / " + repeats);
}

From source file:com.benasmussen.tools.testeditor.ExtractorCLI.java

public static void main(String[] args) throws Exception {
    HelpFormatter formatter = new HelpFormatter();

    // cli options
    Options options = new Options();
    options.addOption(CMD_OPT_INPUT, true, "Input file");
    // options.addOption(CMD_OPT_OUTPUT, true, "Output file");

    try {//  www .  j a v a2  s . c o m

        // evaluate command line options
        CommandLineParser parser = new GnuParser();
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption(CMD_OPT_INPUT)) {
            // option value
            String optionValue = cmd.getOptionValue(CMD_OPT_INPUT);

            // input file
            File inputFile = new File(optionValue);

            // id extractor
            IdExtractor idExtractor = new IdExtractor(inputFile);
            Vector<Vector> data = idExtractor.parse();

            // // TODO implement output folder
            // if (cmd.hasOption(CMD_OPT_OUTPUT))
            // {
            // // file output
            // throw new Exception("Not implemented");
            // }
            // else
            // {
            // console output
            System.out.println("Id;Value");
            for (Vector vector : data) {
                StringBuilder sb = new StringBuilder();
                if (vector.size() >= 1) {
                    sb.append(vector.get(0));
                }
                sb.append(";");
                if (vector.size() >= 2) {
                    sb.append(vector.get(1));
                }
                System.out.println(sb.toString());
            }
            // }
        } else {
            throw new IllegalArgumentException();
        }

    } catch (ParseException e) {
        formatter.printHelp("ExtractorCLI", options);
    } catch (IllegalArgumentException e) {
        formatter.printHelp("ExtractorCLI", options);
    }
}

From source file:com.yahoo.labs.samoa.topology.impl.StormTopologySubmitter.java

public static void main(String[] args) throws IOException {
    Properties props = StormSamoaUtils.getProperties();

    String uploadedJarLocation = props.getProperty(StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY);
    if (uploadedJarLocation == null) {
        logger.error("Invalid properties file. It must have key {}",
                StormJarSubmitter.UPLOADED_JAR_LOCATION_KEY);
        return;/*from w  ww .ja v  a  2s .  co m*/
    }

    List<String> tmpArgs = new ArrayList<String>(Arrays.asList(args));
    int numWorkers = StormSamoaUtils.numWorkers(tmpArgs);

    args = tmpArgs.toArray(new String[0]);
    StormTopology stormTopo = StormSamoaUtils.argsToTopology(args);

    Config conf = new Config();
    conf.putAll(Utils.readStormConfig());
    conf.putAll(Utils.readCommandLineOpts());
    conf.setDebug(false);
    conf.setNumWorkers(numWorkers);

    String profilerOption = props.getProperty(StormTopologySubmitter.YJP_OPTIONS_KEY);
    if (profilerOption != null) {
        String topoWorkerChildOpts = (String) conf.get(Config.TOPOLOGY_WORKER_CHILDOPTS);
        StringBuilder optionBuilder = new StringBuilder();
        if (topoWorkerChildOpts != null) {
            optionBuilder.append(topoWorkerChildOpts);
            optionBuilder.append(' ');
        }
        optionBuilder.append(profilerOption);
        conf.put(Config.TOPOLOGY_WORKER_CHILDOPTS, optionBuilder.toString());
    }

    Map<String, Object> myConfigMap = new HashMap<String, Object>(conf);
    StringWriter out = new StringWriter();

    try {
        JSONValue.writeJSONString(myConfigMap, out);
    } catch (IOException e) {
        System.out.println("Error in writing JSONString");
        e.printStackTrace();
        return;
    }

    Config config = new Config();
    config.putAll(Utils.readStormConfig());

    String nimbusHost = (String) config.get(Config.NIMBUS_HOST);

    NimbusClient nc = new NimbusClient(nimbusHost);
    String topologyName = stormTopo.getTopologyName();
    try {
        System.out.println("Submitting topology with name: " + topologyName);
        nc.getClient().submitTopology(topologyName, uploadedJarLocation, out.toString(),
                stormTopo.getStormBuilder().createTopology());
        System.out.println(topologyName + " is successfully submitted");

    } catch (AlreadyAliveException aae) {
        System.out.println("Fail to submit " + topologyName + "\nError message: " + aae.get_msg());
    } catch (InvalidTopologyException ite) {
        System.out.println("Invalid topology for " + topologyName);
        ite.printStackTrace();
    } catch (TException te) {
        System.out.println("Texception for " + topologyName);
        te.printStackTrace();
    }
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.cleanDL.java

public static void main(String[] args) throws IOException {
    List<String> lines = FileUtils.readLines(new File("/Users/Shyam/mention.eval.dl"));

    for (String line : lines) {
        String[] parts = line.split("\\s+");
        System.out.println(parts[0] + parts[1] + parts[2]);
        StringBuilder sb = new StringBuilder();
        for (int i = 3; i < parts.length; i++)
            sb.append(parts[i] + " ");
        if (mentionFilter(parts)) {
            System.out.println("removing " + Arrays.asList(parts));
            continue;
        }/*from w w  w  . j av a  2  s.co m*/
        if (mentions.containsKey(parts[0])) {
            mentions.get(parts[0]).add(new DocMention(parts[0], sb.toString(), Integer.parseInt(parts[1]),
                    Integer.parseInt(parts[2])));
        } else {
            mentions.put(parts[0], new ArrayList<DocMention>());
            mentions.get(parts[0]).add(new DocMention(parts[0], sb.toString(), Integer.parseInt(parts[1]),
                    Integer.parseInt(parts[2])));
        }
    }
    for (String doc : mentions.keySet()) {
        handleDoc(mentions.get(doc));
    }

    outputMentions();
}

From source file:FileCompressor.java

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

    String file = "D:\\XJad.rar.txt";
    BufferedReader reader = new BufferedReader(new FileReader(file));
    BufferedWriter writer = new BufferedWriter(new FileWriter(file + "_out.txt"));
    StringBuilder content = new StringBuilder();
    String tmp;/* ww  w  .  j  ava 2  s. c o m*/

    while ((tmp = reader.readLine()) != null) {
        content.append(tmp);
        content.append(System.getProperty("line.separator"));
    }

    FileCompressor f = new FileCompressor();
    writer.write(f.compress(content.toString()));

    writer.close();
    reader.close();

    reader = new BufferedReader(new FileReader(file + "_out.txt"));
    StringBuilder content2 = new StringBuilder();

    while ((tmp = reader.readLine()) != null) {
        content2.append(tmp);
        content2.append(System.getProperty("line.separator"));
    }

    String decompressed = f.decompress(content2.toString());
    String c = content.toString();
    System.out.println(decompressed.equals(c));
}

From source file:com.sxj.spring.modules.mapper.JsonMapper.java

public static void main(String... args) throws JsonProcessingException, IOException {
    JsonMapper mapper = JsonMapper.nonEmptyMapper();
    CJ30 cj30 = new CJ30();
    Map<String, String> name = cj30.getName();
    name.put("2", "");
    name.put("3", "?");
    name.put("4", "");
    name.put("5", "");
    name.put("7", "");
    name.put("8", "?");
    Map<String, Map<String, Data>> data = cj30.getData();
    Map<String, Data> subject1 = new HashMap<String, Data>();
    Data d1 = new Data();
    d1.setDate("01/14");
    d1.setMin(41700);/*  w  w w  .ja va2 s.com*/
    d1.setMax(41780);
    d1.setAverage(41740);
    subject1.put("1421164800", d1);

    Data d2 = new Data();
    d2.setDate("01/15");
    d2.setMin(41550);
    d2.setMax(41620);
    d2.setAverage(41585);
    subject1.put("1421251200", d2);
    data.put("2", subject1);

    Map<String, Data> subject2 = new HashMap<String, Data>();
    Data d3 = new Data();
    d3.setDate("01/14");
    d3.setMin(12450);
    d3.setMax(12490);
    d3.setAverage(12470);
    subject2.put("1421164800", d3);

    Data d4 = new Data();
    d4.setDate("01/15");
    d4.setMin(12730);
    d4.setMax(12770);
    d4.setAverage(12750);
    subject2.put("1421251200", d4);
    data.put("3", subject2);
    String json = mapper.toJson(cj30);
    System.out.println(json);

    FileReader reader = new FileReader(new File("E:\\cj30.js"));
    char[] buffer = new char[1024];
    int read = 0;
    StringBuilder sb = new StringBuilder();
    while ((read = reader.read(buffer)) > 0) {
        sb.append(buffer, 0, read);
    }
    CJ30 fromJson = mapper.fromJson(sb.toString(), CJ30.class);
    System.out.println(fromJson.getName());
}

From source file:com.genentech.retrival.tabExport.TABExporter.java

public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nStruct = 0;

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("sqlFile", true, "sql-xml file");
    opt.setRequired(true);//from w w  w  .  ja v a 2s.  c o m
    options.addOption(opt);

    opt = new Option("sqlName", true, "name of SQL element in xml file");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option("o", true, "output file");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("newLineReplacement", true,
            "If given newlines in fields will be replaced by this string.");
    options.addOption(opt);

    opt = new Option("noHeader", false, "Do not output header line");
    options.addOption(opt);

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

    String outFile = cmd.getOptionValue("o");
    String sqlFile = cmd.getOptionValue("sqlFile");
    String sqlName = cmd.getOptionValue("sqlName");
    String newLineReplacement = cmd.getOptionValue("newLineReplacement");

    args = cmd.getArgs();

    try {
        PrintStream out = System.out;
        if (outFile != null)
            out = new PrintStream(outFile);

        SQLStatement stmt = SQLStatement.createFromFile(new File(sqlFile), sqlName);
        Object[] sqlArgs = args;
        if (stmt.getParamTypes().length != args.length) {
            System.err.printf(
                    "\nWarining sql statement needs %d parameters but got only %d. Filling up with NULLs.\n",
                    stmt.getParamTypes().length, args.length);
            sqlArgs = new Object[stmt.getParamTypes().length];
            System.arraycopy(args, 0, sqlArgs, 0, args.length);
        }

        Selecter sel = Selecter.factory(stmt);
        if (!sel.select(sqlArgs)) {
            System.err.println("No rows returned!");
            System.exit(0);
        }

        String[] fieldNames = sel.getFieldNames();
        if (fieldNames.length == 0) {
            System.err.println("Query did not return any columns");
            exitWithHelp(options);
        }

        if (!cmd.hasOption("noHeader")) {
            StringBuilder sb = new StringBuilder(200);
            for (String f : fieldNames)
                sb.append(f).append('\t');
            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String header = sb.toString();

            out.println(header);
        }

        StringBuilder sb = new StringBuilder(200);
        while (sel.hasNext()) {
            Record sqlRec = sel.next();
            sb.setLength(0);

            for (int i = 0; i < fieldNames.length; i++) {
                String fld = sqlRec.getStrg(i);
                if (newLineReplacement != null)
                    fld = NEWLinePattern.matcher(fld).replaceAll(newLineReplacement);

                sb.append(fld).append('\t');
            }

            if (sb.length() > 1)
                sb.setLength(sb.length() - 1); // chop last \t
            String row = sb.toString();

            out.println(row);

            nStruct++;
        }

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("TABExporter: Exported %d records in %dsec\n", nStruct,
                (System.currentTimeMillis() - start) / 1000);
    }
}

From source file:com.datastax.sparql.ConsoleCompiler.java

public static void main(final String[] args) throws IOException {
    //args = "/examples/modern1.sparql";
    final Options options = new Options();
    options.addOption("f", "file", true, "a file that contains a SPARQL query");
    options.addOption("g", "graph", true,
            "the graph that's used to execute the query [classic|modern|crew|kryo file]");
    // TODO: add an OLAP option (perhaps: "--olap spark"?)

    final CommandLineParser parser = new DefaultParser();
    final CommandLine commandLine;

    try {//from  www . j  a  v  a  2 s .c om
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
        printHelp(1);
        return;
    }

    final InputStream inputStream = commandLine.hasOption("file")
            ? new FileInputStream(commandLine.getOptionValue("file"))
            : System.in;
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
    final StringBuilder queryBuilder = new StringBuilder();

    if (!reader.ready()) {
        printHelp(1);
    }

    String line;
    while (null != (line = reader.readLine())) {
        queryBuilder.append(System.lineSeparator()).append(line);
    }

    final String queryString = queryBuilder.toString();
    final Graph graph;

    if (commandLine.hasOption("graph")) {
        switch (commandLine.getOptionValue("graph").toLowerCase()) {
        case "classic":
            graph = TinkerFactory.createClassic();
            break;
        case "modern":
            graph = TinkerFactory.createModern();
            System.out.println("Modern Graph Created");
            break;
        case "crew":
            graph = TinkerFactory.createTheCrew();
            break;
        default:
            graph = TinkerGraph.open();
            System.out.println("Graph Created");
            long startTime = System.nanoTime();
            graph.io(IoCore.gryo()).readGraph(commandLine.getOptionValue("graph"));
            long endTime = System.nanoTime();
            System.out.println("Time taken to load graph from kyro file: " + (endTime - startTime) / 1000000
                    + " mili seconds");
            break;
        }
    } else {

        graph = TinkerFactory.createModern();
    }

    final Traversal<Vertex, ?> traversal = SparqlToGremlinCompiler.convertToGremlinTraversal(graph,
            queryString);

    printWithHeadline("SPARQL Query", queryString);
    printWithHeadline("Traversal (prior execution)", traversal);

    Bytecode traversalByteCode = traversal.asAdmin().getBytecode();

    //JavaTranslator.of(graph.traversal()).translate(traversalByteCode);

    System.out.println("the Byte Code : " + traversalByteCode.toString());
    printWithHeadline("Result", String.join(System.lineSeparator(), JavaTranslator.of(graph.traversal())
            .translate(traversalByteCode).toStream().map(Object::toString).collect(Collectors.toList())));
    printWithHeadline("Traversal (after execution)", traversal);
}

From source file:edu.illinois.cs.cogcomp.datalessclassification.ta.W2VDatalessAnnotator.java

/**
 * @param args config: config file path testFile: Test File
 *///from w w  w. j  a  va 2  s . com
public static void main(String[] args) {
    CommandLine cmd = ESADatalessAnnotator.getCMDOpts(args);

    ResourceManager rm;

    try {
        String configFile = cmd.getOptionValue("config", "config/project.properties");
        ResourceManager nonDefaultRm = new ResourceManager(configFile);

        rm = new W2VDatalessConfigurator().getConfig(nonDefaultRm);
    } catch (IOException e) {
        rm = new W2VDatalessConfigurator().getDefaultConfig();
    }

    String testFile = cmd.getOptionValue("testFile", "data/graphicsTestDocument.txt");

    StringBuilder sb = new StringBuilder();

    String line;

    try (BufferedReader br = new BufferedReader(new FileReader(new File(testFile)))) {
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append(" ");
        }

        String text = sb.toString().trim();

        TokenizerTextAnnotationBuilder taBuilder = new TokenizerTextAnnotationBuilder(new StatefulTokenizer());
        TextAnnotation ta = taBuilder.createTextAnnotation(text);

        W2VDatalessAnnotator datalessAnnotator = new W2VDatalessAnnotator(rm);
        datalessAnnotator.addView(ta);

        List<Constituent> annots = ta.getView(ViewNames.DATALESS_W2V).getConstituents();

        System.out.println("Predicted LabelIDs:");

        for (Constituent annot : annots) {
            System.out.println(annot.getLabel());
        }

        Map<String, String> labelNameMap = DatalessAnnotatorUtils
                .getLabelNameMap(rm.getString(DatalessConfigurator.LabelName_Path.key));

        System.out.println("Predicted Labels:");

        for (Constituent annot : annots) {
            System.out.println(labelNameMap.get(annot.getLabel()));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error("Test File not found at " + testFile + " ... exiting");
        System.exit(-1);
    } catch (AnnotatorException e) {
        e.printStackTrace();
        logger.error("Error Annotating the Test Document with the Dataless View ... exiting");
        System.exit(-1);
    } catch (IOException e) {
        e.printStackTrace();
        logger.error("IO Error while reading the test file ... exiting");
        System.exit(-1);
    }
}

From source file:com.linkedin.kmf.KafkaMonitor.java

public static void main(String[] args) throws Exception {
    if (args.length <= 0) {
        LOG.info("USAGE: java [options] " + KafkaMonitor.class.getName() + " config/kafka-monitor.properties");
        return;/* w  ww.  j  a  v  a  2s .  c o m*/
    }

    StringBuilder buffer = new StringBuilder();
    try (BufferedReader br = new BufferedReader(new FileReader(args[0].trim()))) {
        String line;
        while ((line = br.readLine()) != null) {
            if (!line.startsWith("#"))
                buffer.append(line);
        }
    }

    @SuppressWarnings("unchecked")
    Map<String, Map> props = new ObjectMapper().readValue(buffer.toString(), Map.class);
    KafkaMonitor kafkaMonitor = new KafkaMonitor(props);
    kafkaMonitor.start();
    LOG.info("KafkaMonitor started");

    kafkaMonitor.awaitShutdown();
}