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

@HotSpotIntrinsicCandidate
public StringBuilder() 

Source Link

Document

Constructs a string builder with no characters in it and an initial capacity of 16 characters.

Usage

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 {/*  w  ww.ja v a  2 s.c om*/
        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:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.//from w  w  w .j a  v a 2 s. c  o m
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

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

/**
 * @param args//from w w  w . j av a  2 s.  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: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;/*from  www  .j  a  va  2s .  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:edu.illinois.cs.cogcomp.datalessclassification.ta.W2VDatalessAnnotator.java

/**
 * @param args config: config file path testFile: Test File
 *//*from w  w w . ja  v a2  s. co m*/
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:ex4.java

public static void main(String[] params) {
    CommandLine commandLine = null;//from w w  w  .  j a va  2  s  . c  om
    String sqlpath = "", host = "", port = "3306", username = "", password = "", database = "";
    Boolean query = false;
    Option option_sql = Option.builder("s").argName("sql").hasArg()
            .desc("Path to a file containing a valid MySQL sql statement").build();
    Option option_hostname = Option.builder("h").argName("host").hasArg().desc("ClearDB MySQL Hostname")
            .build();
    Option option_port = Option.builder("n").argName("port").hasArg().desc("ClearDB MySQL Port").build();
    Option option_username = Option.builder("u").argName("username").hasArg().desc("ClearDB MySQL Username")
            .build();
    Option option_password = Option.builder("p").argName("password").hasArg().desc("ClearDB MySQL Password")
            .build();
    Option option_dbname = Option.builder("d").argName("dbname").hasArg().desc("ClearDB MySQL Database Name")
            .build();
    Option option_help = Option.builder("w").argName("wanthelp").hasArg().desc("Help").build();
    Option option_query = Option.builder().longOpt("query").desc("Query type SQL Statement").build();
    Options options = new Options();
    CommandLineParser parser = new DefaultParser();

    options.addOption(option_sql);
    options.addOption(option_hostname);
    options.addOption(option_port);
    options.addOption(option_username);
    options.addOption(option_password);
    options.addOption(option_dbname);
    options.addOption(option_query);
    options.addOption(option_help);

    try {
        commandLine = parser.parse(options, params);
    } catch (MissingOptionException e) {
        help(options);
    } catch (MissingArgumentException e) {
        help(options);
    } catch (ParseException e) {
        System.out.println(e);
    }

    if (commandLine.hasOption("w") || params.length == 0) {
        help(options);
    }

    if (commandLine.hasOption("s")) {
        sqlpath = commandLine.getOptionValue("s");
    } else {
        System.out.println("Missing path to a SQL statement file");
        help(options);
    }
    if (commandLine.hasOption("h")) {
        host = commandLine.getOptionValue("h");
    } else {
        System.out.println("Missing ClearDB hostname (e.g. us-cdbr-iron-east-??.cleardb.net)");
        help(options);
    }
    if (commandLine.hasOption("n")) {
        port = commandLine.getOptionValue("n");
    } else {
        System.out.println("Missing ClearDB Port Value.  Defaulting to 3306");
    }
    if (commandLine.hasOption("u")) {
        username = commandLine.getOptionValue("u");
    } else {
        System.out.println("Missing ClearDB Username");
        help(options);
    }
    if (commandLine.hasOption("p")) {
        password = commandLine.getOptionValue("p");
    } else {
        System.out.println("Missing ClearDB Password");
        help(options);
    }
    if (commandLine.hasOption("d")) {
        database = commandLine.getOptionValue("d");
    } else {
        System.out.println("Missing ClearDB Database Name");
        help(options);
    }

    if (commandLine.hasOption("query")) {
        query = true;
    }

    String connectionURL = new StringBuilder().append("jdbc:mysql://").append(host).append(":").append(port)
            .append("/").append(database).append("?reconnect=true").toString();

    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.out.println(e);
    }

    try {
        Connection con = DriverManager.getConnection(connectionURL, username, password);
        Statement stmt = con.createStatement();
        if (query) {
            System.out.println("Querying target MySQL DB ...");
            ResultSet rs = stmt.executeQuery(readFile(sqlpath, Charset.defaultCharset()));
            while (rs.next())
                System.out.println(rs.getInt("emp_no") + "  " + rs.getDate("birth_date") + "  "
                        + rs.getString("first_name") + "  " + rs.getString("last_name") + "  "
                        + rs.getString("gender") + "  " + rs.getDate("hire_date"));
        } else {
            System.out.println("Updating target MySQL DB ...");
            int result = stmt.executeUpdate(readFile(sqlpath, Charset.defaultCharset()));
            System.out.println(result);
        }
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:cc.twittertools.stream.GatherStatusStream.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws TwitterException {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("list").hasArgs()
            .withDescription("comma-separated list of BCP 47 language identifiers").withLongOpt(LANGUAGE_OPTION)
            .create('l'));
    options.addOption(OptionBuilder.withArgName("list").hasArgs()
            .withDescription(//  w w w.  j a  v  a 2  s . c om
                    "comma-separated list of longitude,latitude pairs specifying a set of bounding boxes")
            .withLongOpt(LOCATIONS_OPTION).create('g'));
    options.addOption("n", NO_BOUNDING_BOX_OPTION, false, "do not consider places' bounding box");

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

    PatternLayout layoutStandard = new PatternLayout();
    layoutStandard.setConversionPattern("[%p] %d %c %M - %m%n");

    PatternLayout layoutSimple = new PatternLayout();
    layoutSimple.setConversionPattern("%m%n");

    // Filter for the statuses: we only want INFO messages
    LevelRangeFilter filter = new LevelRangeFilter();
    filter.setLevelMax(Level.INFO);
    filter.setLevelMin(Level.INFO);
    filter.setAcceptOnMatch(true);
    filter.activateOptions();

    TimeBasedRollingPolicy statusesRollingPolicy = new TimeBasedRollingPolicy();
    statusesRollingPolicy.setFileNamePattern("statuses.log" + HOUR_ROLL);
    statusesRollingPolicy.activateOptions();

    RollingFileAppender statusesAppender = new RollingFileAppender();
    statusesAppender.setRollingPolicy(statusesRollingPolicy);
    statusesAppender.addFilter(filter);
    statusesAppender.setLayout(layoutSimple);
    statusesAppender.activateOptions();

    TimeBasedRollingPolicy warningsRollingPolicy = new TimeBasedRollingPolicy();
    warningsRollingPolicy.setFileNamePattern("warnings.log" + HOUR_ROLL);
    warningsRollingPolicy.activateOptions();

    RollingFileAppender warningsAppender = new RollingFileAppender();
    warningsAppender.setRollingPolicy(statusesRollingPolicy);
    warningsAppender.setThreshold(Level.WARN);
    warningsAppender.setLayout(layoutStandard);
    warningsAppender.activateOptions();

    ConsoleAppender consoleAppender = new ConsoleAppender();
    consoleAppender.setThreshold(Level.WARN);
    consoleAppender.setLayout(layoutStandard);
    consoleAppender.activateOptions();

    // configures the root logger
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.removeAllAppenders();
    rootLogger.addAppender(consoleAppender);
    rootLogger.addAppender(statusesAppender);
    rootLogger.addAppender(warningsAppender);

    // creates filters for the query
    FilterQuery fq = new FilterQuery();
    StringBuilder criteria = new StringBuilder();

    /*
     * @see https://dev.twitter.com/docs/streaming-apis/parameters#language
     */
    final boolean filterLanguage = cmdline.hasOption(LANGUAGE_OPTION);
    String[] languages = null;
    if (filterLanguage) {
        languages = cmdline.getOptionValue(LANGUAGE_OPTION).split(",");
        fq.language(languages);
        criteria.append("languages: [" + cmdline.getOptionValue(LANGUAGE_OPTION) + "]\t");
    }
    final String[] langs = languages;

    /*
     * @see https://dev.twitter.com/docs/streaming-apis/parameters#locations
     */
    double[][] locations = null;
    if (cmdline.hasOption(LOCATIONS_OPTION)) {
        String[] locationsArg = cmdline.getOptionValue(LOCATIONS_OPTION).split(",");
        int nCoords = locationsArg.length;
        if (nCoords % 2 == 0) {
            int pairs = nCoords / 2;
            locations = new double[pairs][2];
            int cnt = 0;
            for (int i = 0; i < pairs; i++) {
                locations[i][0] = Double.parseDouble(locationsArg[cnt]);
                cnt++;
                locations[i][1] = Double.parseDouble(locationsArg[cnt]);
                cnt++;
            }
            fq.locations(locations);
            criteria.append("locations: [" + cmdline.getOptionValue(LOCATIONS_OPTION) + "]\t");
        } else {
            System.err.println("There is a missing coordinate. See "
                    + "https://dev.twitter.com/docs/streaming-apis/parameters#locations");
            System.exit(-1);
        }
    } else {
        fq.locations(new double[][] { { -180, -90 }, { 180, 90 } });
    }
    final double[][] loc = locations;

    final boolean no_bounding_box = cmdline.hasOption(NO_BOUNDING_BOX_OPTION);
    if (no_bounding_box) {
        criteria.append("--no-bounding-box\t");
    }

    // creates a custom logger and log messages
    final Logger logger = Logger.getLogger(GatherStatusStream.class);

    logger.info(criteria);

    RawStreamListener rawListener = new RawStreamListener() {

        @Override
        public void onMessage(String rawString) {
            if (no_bounding_box && loc != null) {
                try {
                    JSONObject status = new JSONObject(rawString);
                    JSONObject coordObj = status.getJSONObject("coordinates");
                    JSONArray coords = coordObj.getJSONArray("coordinates");
                    double longitude = coords.getDouble(0);
                    double latitude = coords.getDouble(1);

                    // checks location
                    for (int i = 0; i < loc.length; i += 2) {
                        if (((loc[i][0] <= longitude) && (longitude <= loc[i + 1][0]))
                                || ((loc[i][1] <= latitude) && (latitude <= loc[i + 1][1]))) {
                            break;
                        } else if (i == loc.length - 1)
                            return;
                    }
                } catch (JSONException e) { /* Either "Coordinates" is null or trash is coming*/
                    return;
                }
            }

            if (filterLanguage) {
                try {
                    JSONObject status = new JSONObject(rawString);
                    // checks language
                    String lang = status.getString("lang");
                    for (int i = 0; i < langs.length; i++) {
                        if (langs[i].equals(lang))
                            break;
                        else if (i == langs.length - 1)
                            return;
                    }
                } catch (JSONException e) { /* Trash is coming */
                    return;
                }
            }
            cnt++;
            logger.info(rawString);
            if (cnt % 1000 == 0) {
                System.out.println(cnt + " messages received.");
            }
        }

        @Override
        public void onException(Exception ex) {
            logger.warn(ex);
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(rawListener);
    twitterStream.filter(fq);
}

From source file:com.sun.faban.harness.util.CLI.java

/**
 * The first argument to the CLI is the action. It can be:<ul>
 * <li>pending</li>/*w w w  .j a v a 2 s  .  c o m*/
 * <li>status runId</li>
 * <li>submit benchmark profile configfile.xml</ul>
 * </ul>
 *
 * @param args The command line arguments.
 */
public static void main(String[] args) {

    if (args.length == 0) {
        printUsage();
        System.exit(1);
    }

    ArrayList<String> argList = new ArrayList<String>();
    // Do the getopt thing.
    char opt = (char) -1;
    String master = null;
    String user = null;
    String password = null;

    for (String arg : args) {
        if (arg.startsWith("-M")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'M';
                continue;
            }
            master = optArg;
        } else if (arg.startsWith("-U")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'U';
                continue;
            }
            user = optArg;
        } else if (arg.startsWith("-P")) {
            String optArg = arg.substring(2);
            if (optArg.length() == 0) {
                opt = 'P';
                continue;
            }
            password = optArg;
        } else if (opt != (char) -1) {
            switch (opt) {
            case 'M':
                master = arg;
                opt = (char) -1;
                break;
            case 'U':
                user = arg;
                opt = (char) -1;
                break;
            case 'P':
                password = arg;
                opt = (char) -1;
                break;
            }
        } else {
            argList.add(arg);
            opt = (char) -1;
        }
    }

    if (master == null)
        master = "http://localhost:9980/";
    else if (!master.endsWith("/"))
        master += '/';

    CLI cli = new CLI();
    String action = argList.get(0);

    try {
        if ("pending".equals(action)) {
            cli.doGet(master + "pending");
        } else if ("status".equals(action)) {
            if (argList.size() > 1)
                cli.doGet(master + "status/" + argList.get(1));
            else
                printUsage();
        } else if ("submit".equals(action)) {
            if (argList.size() > 3) {
                cli.doPostSubmit(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("kill".equals(action)) {
            if (argList.size() > 1) {
                cli.doPostKill(master, user, password, argList);
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("wait".equals(action)) {
            if (argList.size() > 1) {
                cli.pollStatus(master + "status/" + argList.get(1));
            } else {
                printUsage();
                System.exit(1);
            }
        } else if ("showlogs".equals(action)) {
            StringBuilder url = new StringBuilder();
            if (argList.size() > 1) {
                url.append(master).append("logs/");
                url.append(argList.get(1));
            } else {
                printUsage();
            }
            for (int i = 2; i < argList.size(); i++) {
                if ("-t".equals(argList.get(i)))
                    url.append("/tail");
                if ("-f".equals(argList.get(i)))
                    url.append("/follow");
                if ("-ft".equals(argList.get(i)))
                    url.append("/tail/follow");
                if ("-tf".equals(argList.get(i)))
                    url.append("/tail/follow");
            }
            cli.doGet(url.toString());
        } else {
            printUsage();
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
}

From source file:com.edduarte.protbox.Protbox.java

public static void main(String... args) {

    // activate debug / verbose mode
    if (args.length != 0) {
        List<String> argsList = Arrays.asList(args);
        if (argsList.contains("-v")) {
            Constants.verbose = true;/*from   www.  j  ava2  s .  c om*/
        }
    }

    // use System's look and feel
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception ex) {
        // If the System's look and feel is not obtainable, continue execution with JRE look and feel
    }

    // check this is a single instance
    try {
        new ServerSocket(1882);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(null,
                "Another instance of Protbox is already running.\n" + "Please close the other instance first.",
                "Protbox already running", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // check if System Tray is supported by this operative system
    if (!SystemTray.isSupported()) {
        JOptionPane.showMessageDialog(null,
                "Your operative system does not support system tray functionality.\n"
                        + "Please try running Protbox on another operative system.",
                "System tray not supported", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
    }

    // add PKCS11 providers
    FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")),
            HiddenFileFilter.VISIBLE);

    File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter);

    if (providersConfigFiles != null) {
        for (File f : providersConfigFiles) {
            try {
                List<String> lines = FileUtils.readLines(f);
                String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get();
                lines.remove(aliasLine);
                String alias = aliasLine.split("=")[1].trim();

                StringBuilder sb = new StringBuilder();
                for (String s : lines) {
                    sb.append(s);
                    sb.append("\n");
                }

                Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString())));
                Security.addProvider(p);

                pkcs11Providers.put(p.getName(), alias);

            } catch (IOException | ProviderException ex) {
                if (ex.getMessage().equals("Initialization failed")) {
                    ex.printStackTrace();

                    String s = "The following error occurred:\n" + ex.getCause().getMessage()
                            + "\n\nIn addition, make sure you have "
                            + "an available smart card reader connected before opening the application.";
                    JTextArea textArea = new JTextArea(s);
                    textArea.setColumns(60);
                    textArea.setLineWrap(true);
                    textArea.setWrapStyleWord(true);
                    textArea.setSize(textArea.getPreferredSize().width, 1);

                    JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider",
                            JOptionPane.ERROR_MESSAGE);
                    System.exit(1);
                } else {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(null,
                            "Error while setting up PKCS11 provider from configuration file " + f.getName()
                                    + ".\n" + ex.getMessage(),
                            "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    // adds a shutdown hook to save instantiated directories into files when the application is being closed
    Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit));

    // get system tray and run tray applet
    tray = SystemTray.getSystemTray();
    SwingUtilities.invokeLater(() -> {

        if (Constants.verbose) {
            logger.info("Starting application");
        }

        //Start a new TrayApplet object
        trayApplet = TrayApplet.getInstance();
    });

    // prompts the user to choose which provider to use
    ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> {

        // loads eID token
        eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> {
            user = returnedUser;
            certificateData = returnedCertificateData;

            // gets a password to use on the saved registry files (for loading and saving)
            final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null);
            consumerHolder.set(password -> {
                registriesPasswordKey = password;
                try {
                    // if there are serialized files, load them if they can be decoded by this user's private key
                    final List<SavedRegistry> serializedDirectories = new ArrayList<>();
                    if (Constants.verbose) {
                        logger.info("Reading serialized registry files...");
                    }

                    File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles();
                    if (registryFileList != null) {
                        for (File f : registryFileList) {
                            if (f.isFile()) {
                                byte[] data = FileUtils.readFileToByteArray(f);
                                try {
                                    Cipher cipher = Cipher.getInstance("AES");
                                    cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey);
                                    byte[] registryDecryptedData = cipher.doFinal(data);
                                    serializedDirectories.add(new SavedRegistry(f, registryDecryptedData));
                                } catch (GeneralSecurityException ex) {
                                    if (Constants.verbose) {
                                        logger.info("Inserted Password does not correspond to " + f.getName());
                                    }
                                }
                            }
                        }
                    }

                    // if there were no serialized directories, show NewDirectory window to configure the first folder
                    if (serializedDirectories.isEmpty() || registryFileList == null) {
                        if (Constants.verbose) {
                            logger.info("No registry files were found: running app as first time!");
                        }
                        NewRegistryWindow.start(true);

                    } else { // there were serialized directories
                        loadRegistry(serializedDirectories);
                        trayApplet.repaint();
                        showTrayApplet();
                    }

                } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException
                        | ProtboxException ex) {

                    JOptionPane.showMessageDialog(null,
                            "The inserted password was invalid! Please try another one!", "Invalid password!",
                            JOptionPane.ERROR_MESSAGE);
                    insertPassword(consumerHolder.get());
                }
            });
            insertPassword(consumerHolder.get());
        });
    });
}

From source file:UploadUrlGenerator.java

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

    opts.addOption(Option.builder().longOpt(ENDPOINT_OPTION).required().hasArg().argName("url")
            .desc("Sets the ECS S3 endpoint to use, e.g. https://ecs.company.com:9021").build());
    opts.addOption(Option.builder().longOpt(ACCESS_KEY_OPTION).required().hasArg().argName("access-key")
            .desc("Sets the Access Key (user) to sign the request").build());
    opts.addOption(Option.builder().longOpt(SECRET_KEY_OPTION).required().hasArg().argName("secret")
            .desc("Sets the secret key to sign the request").build());
    opts.addOption(Option.builder().longOpt(BUCKET_OPTION).required().hasArg().argName("bucket-name")
            .desc("The bucket containing the object").build());
    opts.addOption(Option.builder().longOpt(KEY_OPTION).required().hasArg().argName("object-key")
            .desc("The object name (key) to access with the URL").build());
    opts.addOption(Option.builder().longOpt(EXPIRES_OPTION).hasArg().argName("minutes")
            .desc("Minutes from local time to expire the request.  1 day = 1440, 1 week=10080, "
                    + "1 month (30 days)=43200, 1 year=525600.  Defaults to 1 hour (60).")
            .build());/*from   www.java2 s  .c o  m*/
    opts.addOption(Option.builder().longOpt(VERB_OPTION).hasArg().argName("http-verb").type(HttpMethod.class)
            .desc("The HTTP verb that will be used with the URL (PUT, GET, etc).  Defaults to GET.").build());
    opts.addOption(Option.builder().longOpt(CONTENT_TYPE_OPTION).hasArg().argName("mimetype")
            .desc("Sets the Content-Type header (e.g. image/jpeg) that will be used with the request.  "
                    + "Must match exactly.  Defaults to application/octet-stream for PUT/POST and "
                    + "null for all others")
            .build());

    DefaultParser dp = new DefaultParser();

    CommandLine cmd = null;
    try {
        cmd = dp.parse(opts, args);
    } catch (ParseException e) {
        System.err.println("Error: " + e.getMessage());
        HelpFormatter hf = new HelpFormatter();
        hf.printHelp("java -jar UploadUrlGenerator-xxx.jar", opts, true);
        System.exit(255);
    }

    URI endpoint = URI.create(cmd.getOptionValue(ENDPOINT_OPTION));
    String accessKey = cmd.getOptionValue(ACCESS_KEY_OPTION);
    String secretKey = cmd.getOptionValue(SECRET_KEY_OPTION);
    String bucket = cmd.getOptionValue(BUCKET_OPTION);
    String key = cmd.getOptionValue(KEY_OPTION);
    HttpMethod method = HttpMethod.GET;
    if (cmd.hasOption(VERB_OPTION)) {
        method = HttpMethod.valueOf(cmd.getOptionValue(VERB_OPTION).toUpperCase());
    }
    int expiresMinutes = 60;
    if (cmd.hasOption(EXPIRES_OPTION)) {
        expiresMinutes = Integer.parseInt(cmd.getOptionValue(EXPIRES_OPTION));
    }
    String contentType = null;
    if (method == HttpMethod.PUT || method == HttpMethod.POST) {
        contentType = "application/octet-stream";
    }

    if (cmd.hasOption(CONTENT_TYPE_OPTION)) {
        contentType = cmd.getOptionValue(CONTENT_TYPE_OPTION);
    }

    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    ClientConfiguration cc = new ClientConfiguration();
    // Force use of v2 Signer.  ECS does not support v4 signatures yet.
    cc.setSignerOverride("S3SignerType");
    AmazonS3Client s3 = new AmazonS3Client(credentials, cc);
    s3.setEndpoint(endpoint.toString());
    S3ClientOptions s3c = new S3ClientOptions();
    s3c.setPathStyleAccess(true);
    s3.setS3ClientOptions(s3c);

    // Sign the URL
    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, expiresMinutes);
    GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucket, key).withExpiration(c.getTime())
            .withMethod(method);
    if (contentType != null) {
        req = req.withContentType(contentType);
    }
    URL u = s3.generatePresignedUrl(req);
    System.out.printf("URL: %s\n", u.toURI().toASCIIString());
    System.out.printf("HTTP Verb: %s\n", method);
    System.out.printf("Expires: %s\n", c.getTime());
    System.out.println("To Upload with curl:");

    StringBuilder sb = new StringBuilder();
    sb.append("curl ");

    if (method != HttpMethod.GET) {
        sb.append("-X ");
        sb.append(method.toString());
        sb.append(" ");
    }

    if (contentType != null) {
        sb.append("-H \"Content-Type: ");
        sb.append(contentType);
        sb.append("\" ");
    }

    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        sb.append("-T <filename> ");
    }

    sb.append("\"");
    sb.append(u.toURI().toASCIIString());
    sb.append("\"");

    System.out.println(sb.toString());

    System.exit(0);
}