Example usage for java.lang StringBuilder append

List of usage examples for java.lang StringBuilder append

Introduction

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

Prototype

@Override
    public StringBuilder append(double d) 

Source Link

Usage

From source file:de.zazaz.iot.bosch.indego.util.CmdLineTool.java

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

    StringBuilder commandList = new StringBuilder();
    for (DeviceCommand cmd : DeviceCommand.values()) {
        if (commandList.length() > 0) {
            commandList.append(", ");
        }/*from  w ww. j  a va  2s.com*/
        commandList.append(cmd.toString());
    }

    options.addOption(Option //
            .builder() //
            .longOpt("base-url") //
            .desc("Sets the base URL of the web service") //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("u") //
            .longOpt("username") //
            .desc("The username for authentication (usually mail address)") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("p") //
            .longOpt("password") //
            .desc("The password for authentication") //
            .required() //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("c") //
            .longOpt("command") //
            .desc(String.format("The command, which should be sent to the device (%s)", commandList)) //
            .hasArg() //
            .build());
    options.addOption(Option //
            .builder("q") //
            .longOpt("query-status") //
            .desc("Queries the status of the device") //
            .build());
    options.addOption(Option //
            .builder() //
            .longOpt("query-calendar") //
            .desc("Queries the calendar of the device") //
            .build());
    options.addOption(Option //
            .builder("?") //
            .longOpt("help") //
            .desc("Prints this help") //
            .build());

    CommandLineParser parser = new DefaultParser();
    CommandLine cmds = null;
    try {
        cmds = parser.parse(options, args);
    } catch (ParseException ex) {
        System.err.println(ex.getMessage());
        System.err.println();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        System.exit(1);
        return;
    }

    if (cmds.hasOption("?")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(CmdLineTool.class.getName(), options);
        return;
    }

    String baseUrl = cmds.getOptionValue("base-url");
    String username = cmds.getOptionValue('u');
    String password = cmds.getOptionValue('p');
    String commandStr = cmds.getOptionValue('c');
    boolean doQueryState = cmds.hasOption('q');
    boolean doQueryCalendar = cmds.hasOption("query-calendar");

    DeviceCommand command = null;
    if (commandStr != null) {
        try {
            command = DeviceCommand.valueOf(commandStr.toUpperCase());
        } catch (IllegalArgumentException ex) {
            System.err.println("Unknown command: " + commandStr);
            System.exit(1);
        }
    }

    IndegoController controller = new IndegoController(baseUrl, username, password);
    try {
        System.out.println("Connecting to device");
        controller.connect();
        System.out.println(String.format("...Connection established. Device serial number is: %s",
                controller.getDeviceSerialNumber()));
        if (command != null) {
            System.out.println(String.format("Sending command (%s)...", command));
            controller.sendCommand(command);
            System.out.println("...Command sent successfully!");
        }
        if (doQueryState) {
            System.out.println("Querying device state");
            DeviceStateInformation state = controller.getState();
            printState(System.out, state);
        }
        if (doQueryCalendar) {
            System.out.println("Querying device calendar");
            DeviceCalendar calendar = controller.getCalendar();
            printCalendar(System.out, calendar);
        }
    } catch (IndegoException ex) {
        ex.printStackTrace();
        System.exit(2);
    } finally {
        controller.disconnect();
    }
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer2.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;
    PreparedStatement update = null;
    try {// www. j  av  a2  s .com
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.append("SELECT * FROM cachedparse WHERE pennTree = 'ERROR' OR pennTree = ''");

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

        //         CSVWriter writer;
        String text;
        JCas jcas = JCasFactory.createJCas();
        String updateQuery = "UPDATE CachedParse SET pennTree = ? WHERE collectionId = ? AND documentId = ? AND beginOffset = ? AND endOffset = ?";
        update = connection.prepareStatement(updateQuery);
        //         File base = new File("");

        AnalysisEngine sentences = createEngine(DummySentenceSplitter.class);
        AnalysisEngine tokenizer = createEngine(StanfordSegmenter.class,
                StanfordSegmenter.PARAM_CREATE_SENTENCES, false, StanfordSegmenter.PARAM_CREATE_TOKENS, true);
        AnalysisEngine parser = createEngine(StanfordParser.class, StanfordParser.PARAM_WRITE_CONSTITUENT, true,
                //               StanfordParser.PARAM_CREATE_DEPENDENCY_TAGS, true,
                StanfordParser.PARAM_WRITE_PENN_TREE, true, StanfordParser.PARAM_LANGUAGE, "en",
                StanfordParser.PARAM_VARIANT, "factored");

        while (rs.next()) {
            String collectionId = rs.getString("collectionId");
            String documentId = rs.getString("documentId");
            int beginOffset = rs.getInt("beginOffset");
            int endOffset = rs.getInt("endOffset");
            text = retrieveCoveredText(collectionId, documentId, beginOffset, endOffset);

            jcas.setDocumentText(text);
            jcas.setDocumentLanguage("en");
            sentences.process(jcas);
            tokenizer.process(jcas);
            parser.process(jcas);

            //            writer = new CSVWriter(new FileWriter(new File(base, documentId + ".csv"));

            System.out.println("Updating " + text);
            for (PennTree p : JCasUtil.select(jcas, PennTree.class)) {
                String tree = StringUtils.normalizeSpace(p.getPennTree());
                update.setString(1, tree);
                update.setString(2, collectionId);
                update.setString(3, documentId);
                update.setInt(4, beginOffset);
                update.setInt(5, endOffset);
                update.executeUpdate();
                System.out.println("with tree " + tree);
                break;
            }
            jcas.reset();
        }
    } catch (SQLException e) {
        log.error("Exception while selecting: " + e.getMessage());
    } catch (UIMAException e) {
        e.printStackTrace();
    } finally {
        closeQuietly(select);
        closeQuietly(update);
    }

    // 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:com.appeligo.responsetest.ServerResponseChecker.java

/**
 * @param args/*from   w  w w.  ja  v  a 2s  .co m*/
 */
public static void main(String[] args) {

    PatternLayout pattern = new PatternLayout("%d{ISO8601} %-5p [%-c{1} - %t] - %m%n");
    ConsoleAppender consoleAppender = new ConsoleAppender(pattern);
    LevelRangeFilter infoFilter = new LevelRangeFilter();
    infoFilter.setLevelMin(Level.INFO);
    consoleAppender.addFilter(infoFilter);
    BasicConfigurator.configure(consoleAppender);

    String configFile = "/etc/flip.tv/responsetest.xml";

    if (args.length > 0) {
        if (args.length == 2 && args[0].equals("-config")) {
            configFile = args[1];
        } else {
            log.error("Usage: java " + ServerResponseChecker.class.getName() + " [-config <xmlfile>]");
            System.exit(1);
        }
    }

    try {
        XMLConfiguration config = new XMLConfiguration(configFile);

        logFile = config.getString("logFile", logFile);
        servlet = config.getString("servlet", servlet);
        timeoutSeconds = config.getLong("timeoutSeconds", timeoutSeconds);
        responseTimeThresholdSeconds = config.getLong("responseTimeThresholdSeconds",
                responseTimeThresholdSeconds);
        reporter = config.getString("reporter", reporter);
        smtpServer = config.getString("smtpServer", smtpServer);
        smtpUsername = config.getString("smtpUsername", smtpUsername);
        smtpPassword = config.getString("smtpPassword", smtpPassword);
        smtpDebug = config.getBoolean("smtpDebug", smtpDebug);
        mailTo = config.getString("mailTo", mailTo);
    } catch (ConfigurationException e) {
        e.printStackTrace();
    }

    marker = logFile + ".mailed";

    try {
        BasicConfigurator.configure(new RollingFileAppender(pattern, logFile, true));
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Add email appender
    SMTPAppender mailme = new SMTPAppender();
    LevelRangeFilter warnFilter = new LevelRangeFilter();
    warnFilter.setLevelMin(Level.WARN);
    mailme.addFilter(warnFilter);
    mailme.setSMTPDebug(smtpDebug);
    mailme.setSMTPHost(smtpServer);
    mailme.setTo(mailTo);
    mailme.setFrom(reporter + " <" + smtpUsername + ">");
    mailme.setBufferSize(1);
    mailme.setSubject(servlet + " Not Responding!");
    mailme.setSMTPUsername(smtpUsername);
    mailme.setSMTPPassword(smtpPassword);
    mailme.setLayout(new SimpleLayout());
    mailme.activateOptions();
    mailme.setLayout(pattern);
    BasicConfigurator.configure(mailme);

    long before;
    ConnectionThread connectionThread = new ConnectionThread();
    connectionThread.start();
    synchronized (connectionThread) {
        connectionThread.setOkToGo(true);
        connectionThread.notifyAll();
        before = System.currentTimeMillis();
        long delay = timeoutSeconds * 1000;
        while (!done && delay > 0) {
            try {
                connectionThread.wait(delay);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            delay -= (System.currentTimeMillis() - before);
        }
    }
    long after = System.currentTimeMillis();
    responseMillis = after - before;
    String reportStatus = "Could not report";
    try {
        StringBuilder sb = new StringBuilder();
        sb.append(servlet + "/responsetest/report.action");
        sb.append("?reporter=" + URLEncoder.encode(reporter));
        sb.append("&status=" + URLEncoder.encode(status));
        sb.append("&bytesRead=" + bytesRead);
        sb.append("&timedOut=" + (!done));
        if (throwable == null) {
            sb.append("&exception=none");
        } else {
            sb.append("&exception="
                    + URLEncoder.encode(throwable.getClass().getName() + "-" + throwable.getMessage()));
        }
        sb.append("&responseMillis=" + responseMillis);
        URL reportURL = new URL(sb.toString());
        connection = (HttpURLConnection) reportURL.openConnection();
        connection.connect();
        reportStatus = connection.getResponseCode() + " - " + connection.getResponseMessage();
    } catch (Throwable t) {
        reportStatus = t.getClass().getName() + "-" + t.getMessage();
    }
    StringBuilder sb = new StringBuilder();
    sb.append(servlet + ": ");
    sb.append(status + ", " + bytesRead + " bytes, ");
    if (done) {
        sb.append("DONE, ");
    } else {
        sb.append("TIMED OUT, ");
    }
    sb.append(responseMillis + " millisecond response, ");
    sb.append(" report status=" + reportStatus);
    File markerFile = new File(marker);
    if (done && status.startsWith("200") && (throwable == null)) {
        if ((responseMillis / 1000) < responseTimeThresholdSeconds) {
            if (markerFile.exists()) {
                markerFile.delete();
            }
            log.debug(sb.toString());
        } else {
            if (markerFile.exists()) {
                log.info(sb.toString());
            } else {
                try {
                    new FileOutputStream(marker).close();
                    log.warn(sb.toString());
                } catch (IOException e) {
                    log.info(sb.toString());
                    log.info("Can't send email alert because could not write marker file: " + marker + ". "
                            + e.getMessage());
                }
            }
        }
    } else {
        if (throwable != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            sb.append(sw.toString());
        }
        if (markerFile.exists()) {
            log.info(sb.toString());
        } else {
            try {
                new FileOutputStream(marker).close();
                log.fatal(sb.toString()); // chosen appender layout ignoresThrowable()
            } catch (IOException e) {
                log.info(sb.toString());
                log.info("Can't send email alert because could not write marker file: " + marker + ". "
                        + e.getMessage());
            }
        }
    }
}

From source file:aldenjava.opticalmapping.Cigar.java

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

    System.out.println("Please enter the cigar string to convert:");
    StringBuilder cigar = new StringBuilder();
    int c = System.in.read();
    while (c != -1) {
        cigar.append((char) c);
        if (System.in.available() == 0)
            break;
        c = System.in.read();//w  ww.  j  av a 2s . com
    }

    String precigar = Cigar.convertpreCIGAR(cigar.toString().trim());
    System.out.println("The precigar is:");
    System.out.println(precigar);
}

From source file:ca.uqac.dim.net.verify.NetworkChecker.java

/**
 * Main loop. Processes command line arguments, loads the network, builds and
 * sends a file to NuSMV and handles its response.
 * @param args Command-line arguments//from www  .j  a va 2s  .  c o m
 */
public static void main(String[] args) {
    // Configuration variables
    boolean opt_show_file = false, opt_show_messages = true, opt_show_stats = false;

    // Create and parse command line options
    Option opt = null;
    Options options = new Options();
    options.addOption("f", "file", false, "Output NuSMV file to stdout");
    options.addOption("s", "time", false, "Display statistics");
    options.addOption("h", "help", false, "Show usage information");
    options.addOption("q", "quiet", false, "Do not display any message or explanation");
    opt = new Option("i", "file", true, "Input directory");
    opt.setRequired(true);
    options.addOption(opt);
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Error parsing command line arguments");
        showUsage(options);
        System.exit(1);
    }
    if (cmd == null) {
        System.err.println("Error parsing command line arguments");
        showUsage(options);
        System.exit(1);
    }

    // Get options
    assert cmd != null;
    opt_show_file = cmd.hasOption("f");
    opt_show_messages = !cmd.hasOption("q");
    opt_show_stats = cmd.hasOption("s");

    if (opt_show_messages)
        System.err.println(
                "Distributed anomaly verifier\n(C) 2012 Sylvain Hall, Universit du Qubec  Chicoutimi\n");

    // Get input directory and blob
    assert cmd.hasOption("i");
    String slash = System.getProperty("file.separator");
    String input_dir = cmd.getOptionValue("i");
    int loc = input_dir.lastIndexOf(slash);
    String dir_name = "", blob = "";
    if (loc == -1) {
        dir_name = "";
        blob = input_dir;
    } else {
        dir_name = input_dir.substring(0, loc);
        blob = input_dir.substring(loc + 1);
    }

    // Load network
    Network net = null;
    try {
        net = loadNetworkFromDirectory(dir_name, blob, slash);
    } catch (FileNotFoundException e) {
        System.err.print("Error reading ");
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (IOException e) {
        System.err.println(e);
        System.exit(1);
    }

    // Build NuSMV file
    assert net != null;
    StringBuilder sb = new StringBuilder();
    if (opt_show_file) {
        sb.append("-- File auto-generated by DistributedChecker\n");
        sb.append("-- (C) 2012  Sylvain Hall, Universit du Qubec  Chicoutimi\n\n");
    }
    sb.append(net.toSmv(opt_show_file));
    // Simple shadowing
    String f_shadowing = "G (frozen -> !(interval_l <= rule_interval_l & interval_r >= rule_interval_r & decision != rule_decision))";
    sb.append("\n\nLTLSPEC\n").append(f_shadowing);

    // Run NuSMV and parse its return value
    if (opt_show_file) {
        System.out.println(sb);
        System.exit(0);
    }
    RuntimeInfos ri = null;
    try {
        ri = runNuSMV(sb.toString());
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    } catch (InterruptedException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    assert ri != null;

    // If requested, compute and show an explanation from NuSMV's returned contents
    if (opt_show_messages) {
        ExplanationTrace t = null;
        try {
            t = net.explain(ri.m_return_contents);
        } catch (NuSmvParseException e) {
            System.err.println("Error reading NuSMV's answer");
            System.exit(1);
        }
        if (t == null) {
            // No explanation => no anomaly found
            System.out.println("No anomaly found");
        } else
            System.out.println(t);
    }

    // If requested, show runtime statistics
    if (opt_show_stats) {
        StringBuilder out = new StringBuilder();
        out.append(net.getNodeSize()).append(",");
        out.append(net.getFirewallRuleSize()).append(",");
        out.append(net.getRoutingTableSize()).append(",");
        out.append(ri.m_runtime);
        System.out.println(out);
    }
    System.exit(0);
}

From source file:ca.uqac.lif.bullwinkle.BullwinkleCli.java

/**
 * @param args/*from  www  .  j ava2s . c  o m*/
 */
public static void main(String[] args) {
    // Setup parameters
    int verbosity = 1;
    String output_format = "xml", grammar_filename = null, filename_to_parse = null;

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2014 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file LICENSE-2.0 for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("f")) {
        output_format = c_line.getOptionValue("f");
    }
    // Get grammar file
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no grammar file specified");
        System.exit(ERR_ARGUMENTS);
    }
    grammar_filename = remaining_args.get(0);
    // Get file to parse, if any
    if (remaining_args.size() >= 2) {
        filename_to_parse = remaining_args.get(1);
    }

    // Read grammar file
    BnfParser parser = null;
    try {
        parser = new BnfParser(new File(grammar_filename));
    } catch (InvalidGrammarException e) {
        System.err.println("ERROR: invalid grammar");
        System.exit(ERR_GRAMMAR);
    } catch (IOException e) {
        System.err.println("ERROR reading grammar " + grammar_filename);
        System.exit(ERR_IO);
    }
    assert parser != null;

    // Read input file
    BufferedReader bis = null;
    if (filename_to_parse == null) {
        // Read from stdin
        bis = new BufferedReader(new InputStreamReader(System.in));
    } else {
        // Read from file
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filename_to_parse))));
        } catch (FileNotFoundException e) {
            System.err.println("ERROR: file not found " + filename_to_parse);
            System.exit(ERR_IO);
        }
    }
    assert bis != null;
    String str;
    StringBuilder input_file = new StringBuilder();
    try {
        while ((str = bis.readLine()) != null) {
            input_file.append(str).append("\n");
        }
    } catch (IOException e) {
        System.err.println("ERROR reading input");
        System.exit(ERR_IO);
    }
    String file_contents = input_file.toString();

    // Parse contents of file
    ParseNode p_node = null;
    try {
        p_node = parser.parse(file_contents);
    } catch (ca.uqac.lif.bullwinkle.BnfParser.ParseException e) {
        System.err.println("ERROR parsing input\n");
        e.printStackTrace();
        System.exit(ERR_PARSE);
    }
    if (p_node == null) {
        System.err.println("ERROR parsing input\n");
        System.exit(ERR_PARSE);
    }
    assert p_node != null;

    // Output parse node to desired format
    PrintStream output = System.out;
    OutputFormatVisitor out_vis = null;
    if (output_format.compareToIgnoreCase("xml") == 0) {
        // Output to XML
        out_vis = new XmlVisitor();
    } else if (output_format.compareToIgnoreCase("dot") == 0) {
        // Output to DOT
        out_vis = new GraphvizVisitor();
    } else if (output_format.compareToIgnoreCase("txt") == 0) {
        // Output to indented plain text
        out_vis = new IndentedTextVisitor();
    } else if (output_format.compareToIgnoreCase("json") == 0) {
        // Output to JSON
    }
    if (out_vis == null) {
        System.err.println("ERROR: unknown output format " + output_format);
        System.exit(ERR_ARGUMENTS);
    }
    assert out_vis != null;
    p_node.prefixAccept(out_vis);
    output.print(out_vis.toOutputString());

    // Terminate without error
    System.exit(ERR_OK);
}

From source file:io.alicorn.device.client.DeviceClient.java

public static void main(String[] args) {
    logger.info("Starting Alicorn Client System");

    // Prepare Display Color.
    transform3xWrite(DisplayTools.commandForColor(0, 204, 255));

    // Setup text information.
    //        transform3xWrite(DisplayTools.commandForText("Sup Fam"));

    class StringWrapper {
        public String string = "";
    }//from  www .  jav a2  s .c  o  m
    final StringWrapper string = new StringWrapper();

    // Text Handler.
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            String latestString = "";
            String outputStringLine1Complete = "";
            long outputStringLine1Cursor = 1;
            int outputStringLine1Mask = 0;
            String outputStringLine2 = "";

            while (true) {
                if (!latestString.equals(string.string)) {
                    latestString = string.string;
                    String[] latestStrings = latestString.split("::");
                    outputStringLine1Complete = latestStrings[0];
                    outputStringLine1Mask = outputStringLine1Complete.length();
                    outputStringLine1Cursor = 0;

                    // Trim second line to a length of sixteen.
                    outputStringLine2 = latestStrings.length > 1 ? latestStrings[1] : "";
                    if (outputStringLine2.length() > 16) {
                        outputStringLine2 = outputStringLine2.substring(0, 16);
                    }
                }

                StringBuilder outputStringLine1 = new StringBuilder();
                if (outputStringLine1Complete.length() > 0) {
                    long cursor = outputStringLine1Cursor;
                    for (int i = 0; i < 16; i++) {
                        outputStringLine1.append(
                                outputStringLine1Complete.charAt((int) (cursor % outputStringLine1Mask)));
                        cursor += 1;
                    }
                    outputStringLine1Cursor += 1;
                } else {
                    outputStringLine1.append("                ");
                }

                try {
                    transform3xWrite(
                            DisplayTools.commandForText(outputStringLine1.toString() + outputStringLine2));
                    Thread.sleep(400);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    thread.start();

    // Event Handler
    while (true) {
        try {
            String url = "http://169.254.90.174:9789/api/iot/narwhalText";
            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(url);
            HttpResponse response = client.execute(request);
            string.string = apacheHttpEntityToString(response.getEntity());

            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.bolingcavalry.StreamingJob.java

public static void main(String[] args) throws Exception {
    // ?/* w w w .  j  ava  2  s . com*/
    final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

    env.addSource(new WikipediaEditsSource())
            //??key
            .keyBy((KeySelector<WikipediaEditEvent, String>) wikipediaEditEvent -> wikipediaEditEvent.getUser())
            //?5
            .timeWindow(Time.seconds(15))
            //?key????
            .aggregate(
                    new AggregateFunction<WikipediaEditEvent, Tuple3<String, Integer, StringBuilder>, Tuple3<String, Integer, StringBuilder>>() {
                        @Override
                        public Tuple3<String, Integer, StringBuilder> createAccumulator() {
                            //ACC
                            return new Tuple3<>("", 0, new StringBuilder());
                        }

                        @Override
                        public Tuple3<String, Integer, StringBuilder> add(WikipediaEditEvent wikipediaEditEvent,
                                Tuple3<String, Integer, StringBuilder> tuple3) {

                            StringBuilder sbud = tuple3.f2;

                            //?"Details "?
                            //??
                            if (StringUtils.isBlank(sbud.toString())) {
                                sbud.append("Details : ");
                            } else {
                                sbud.append(" ");
                            }

                            //??
                            return new Tuple3<>(wikipediaEditEvent.getUser(),
                                    wikipediaEditEvent.getByteDiff() + tuple3.f1,
                                    sbud.append(wikipediaEditEvent.getByteDiff()));
                        }

                        @Override
                        public Tuple3<String, Integer, StringBuilder> getResult(
                                Tuple3<String, Integer, StringBuilder> tuple3) {
                            return tuple3;
                        }

                        @Override
                        public Tuple3<String, Integer, StringBuilder> merge(
                                Tuple3<String, Integer, StringBuilder> tuple3,
                                Tuple3<String, Integer, StringBuilder> acc1) {
                            //???
                            return new Tuple3<>(tuple3.f0, tuple3.f1 + acc1.f1, tuple3.f2.append(acc1.f2));
                        }
                    })
            //?????key???
            .map((MapFunction<Tuple3<String, Integer, StringBuilder>, String>) tuple3 -> tuple3.toString())
            //?STDOUT
            .print();

    // 
    env.execute("Flink Streaming Java API Skeleton");
}

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

/**
 * @param args config: config file path testFile: Test File
 *//*  w  ww  .j  a va2 s.co m*/
public static void main(String[] args) {
    CommandLine cmd = getCMDOpts(args);

    ResourceManager rm;

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

        rm = new ESADatalessConfigurator().getConfig(nonDefaultRm);
    } catch (IOException e) {
        rm = new ESADatalessConfigurator().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);

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

        List<Constituent> annots = ta.getView(ViewNames.DATALESS_ESA).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 (IOException e) {
        e.printStackTrace();
        logger.error("IO Error while reading the test file ... exiting");
        System.exit(-1);
    } catch (AnnotatorException e) {
        e.printStackTrace();
        logger.error("Error Annotating the Test Document with the Dataless View ... exiting");
        System.exit(-1);
    }
}

From source file:com.javacreed.examples.spring.CreateBigTable.java

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

    final ComboPooledDataSource ds = DbUtils.createDs();
    try {/*from  w  w  w  .  jav  a 2 s .  c  o m*/
        final JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);

        CreateBigTable.LOGGER.debug("Dropping table (if exists)");
        jdbcTemplate.update("DROP TABLE IF EXISTS `big_table`");

        CreateBigTable.LOGGER.debug("Creating table");
        jdbcTemplate.update("CREATE TABLE `big_table`(`id` INT(20), `name` VARCHAR(128))");

        CreateBigTable.LOGGER.debug("Adding records");
        final StringBuilder query = new StringBuilder();
        for (int i = 0, b = 1; i < 1000000; i++) {
            if (i % 500 == 0) {
                if (i > 0) {
                    CreateBigTable.LOGGER.debug("Adding records (batch {})", b++);
                    jdbcTemplate.update(query.toString());
                    query.setLength(0);
                }

                query.append("INSERT INTO `big_table` (`id`, `name`) VALUES ");
            } else {
                query.append(",");
            }

            query.append("  (" + (i + 1) + ", 'Pack my box with five dozen liquor jugs.')");
        }

        CreateBigTable.LOGGER.debug("Adding last batch");
        jdbcTemplate.update(query.toString());
    } finally {
        DbUtils.closeQuietly(ds);
    }

    CreateBigTable.LOGGER.debug("Done");
}