Example usage for java.lang String trim

List of usage examples for java.lang String trim

Introduction

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

Prototype

public String trim() 

Source Link

Document

Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020' (the space character).

Usage

From source file:ivory.core.tokenize.Tokenizer.java

@SuppressWarnings("static-access")
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("full path to model file or directory").hasArg()
            .withDescription("model file").create("model"));
    options.addOption(OptionBuilder.withArgName("full path to input file").hasArg()
            .withDescription("input file").isRequired().create("input"));
    options.addOption(OptionBuilder.withArgName("full path to output file").hasArg()
            .withDescription("output file").isRequired().create("output"));
    options.addOption(OptionBuilder.withArgName("en | zh | de | fr | ar | tr | es").hasArg()
            .withDescription("2-character language code").isRequired().create("lang"));
    options.addOption(OptionBuilder.withArgName("path to stopwords list").hasArg()
            .withDescription("one stopword per line").create("stopword"));
    options.addOption(OptionBuilder.withArgName("path to stemmed stopwords list").hasArg()
            .withDescription("one stemmed stopword per line").create("stemmed_stopword"));
    options.addOption(OptionBuilder.withArgName("true|false").hasArg().withDescription("turn on/off stemming")
            .create("stem"));
    options.addOption(OptionBuilder.withDescription("Hadoop option to load external jars")
            .withArgName("jar packages").hasArg().create("libjars"));

    CommandLine cmdline;/*from w w w . ja va  2  s  .c o  m*/
    CommandLineParser parser = new GnuParser();
    try {
        String stopwordList = null, stemmedStopwordList = null, modelFile = null;
        boolean isStem = true;
        cmdline = parser.parse(options, args);
        if (cmdline.hasOption("stopword")) {
            stopwordList = cmdline.getOptionValue("stopword");
        }
        if (cmdline.hasOption("stemmed_stopword")) {
            stemmedStopwordList = cmdline.getOptionValue("stemmed_stopword");
        }
        if (cmdline.hasOption("stem")) {
            isStem = Boolean.parseBoolean(cmdline.getOptionValue("stem"));
        }
        if (cmdline.hasOption("model")) {
            modelFile = cmdline.getOptionValue("model");
        }

        ivory.core.tokenize.Tokenizer tokenizer = TokenizerFactory.createTokenizer(
                cmdline.getOptionValue("lang"), modelFile, isStem, stopwordList, stemmedStopwordList, null);
        BufferedWriter out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(cmdline.getOptionValue("output")), "UTF8"));
        BufferedReader in = new BufferedReader(
                new InputStreamReader(new FileInputStream(cmdline.getOptionValue("input")), "UTF8"));

        String line = null;
        while ((line = in.readLine()) != null) {
            String[] tokens = tokenizer.processContent(line);
            String s = "";
            for (String token : tokens) {
                s += token + " ";
            }
            out.write(s.trim() + "\n");
        }
        in.close();
        out.close();

    } catch (Exception exp) {
        System.out.println(exp);
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Tokenizer", options);
        System.exit(-1);
    }
}

From source file:com.basho.contact.ContactConsole.java

public static void main(String[] args) throws IOException {
    CommandLine commandLine = processArgs(args);
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);//ww  w .  j  av  a2 s  .co m
    reader.setExpandEvents(false); // TODO: look into this
    // TODO: Pasting in text with tabs prints out a ton of completions
    //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords));

    String line;
    PrintWriter out = new PrintWriter(System.out);
    DefaultConnectionProvider connections = new DefaultConnectionProvider();
    RuntimeContext ctx = new RuntimeContext(connections, System.out, System.err);
    if (!commandLine.hasOption("nosignals")) {
        ConsoleSignalHander.install("INT", ctx);
    }
    ContactWalker walker = new ContactWalker(ctx);
    ContactAdminWalker adminWalker = new ContactAdminWalker(ctx);
    List<ContactBaseListener> walkers = new ArrayList<ContactBaseListener>();
    walkers.add(walker);
    walkers.add(adminWalker);

    boolean nextLinePrompt = false;

    ANSIBuffer buf = new ANSIBuffer();
    buf.setAnsiEnabled(!commandLine.hasOption("nocolor"));
    buf.blue("Welcome to Riak Contact\n");
    buf.blue("(c) 2013 Dave Parfitt\n");
    System.out.println(buf.toString());

    if (!commandLine.hasOption("noconfig")) {
        String config = null;
        try {
            config = readConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (config != null && !config.trim().isEmpty()) {
            processInput(config, walkers, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
        }
    }

    if (commandLine.hasOption("infile")) {
        String filename = commandLine.getOptionValue("infile");
        readInputFile(filename, walkers, ctx);
        ctx.getActionListener().term();
        System.exit(0);
    }

    StringBuffer lines = new StringBuffer();
    ANSIBuffer ansiprompt = new ANSIBuffer();
    ansiprompt.setAnsiEnabled(true);
    ansiprompt.green("> ");
    String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor"));
    boolean inHereDoc = false;

    while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) {
        out.flush();
        String chunks[] = line.split(" ");
        String consoleCommandCheck = chunks[0].toLowerCase().trim();
        if (consoleOnlyCommands.containsKey(consoleCommandCheck)) {
            consoleOnlyCommands.get(consoleCommandCheck).run(line, reader);
            continue;
        }

        if (line.contains("~%~") && !line.contains("\\~%~")) {
            inHereDoc = !inHereDoc;
        }

        if (!line.trim().endsWith(";")) {
            nextLinePrompt = true;
            lines.append(line);
            lines.append("\n");
        } else if (line.trim().endsWith(";") && !inHereDoc) {
            lines.append(line);
            String input = lines.toString();
            nextLinePrompt = false;
            processInput(input, walkers, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
            lines = new StringBuffer();
        } else if (inHereDoc) {
            lines.append(line);
            lines.append("\n");
        }

    }
    ctx.getActionListener().term();
}

From source file:com.google.oacurl.Login.java

public static void main(String[] args) throws Exception {
    LoginOptions options = new LoginOptions();
    try {/*from  w w  w. j  av a  2s.  c o m*/
        options.parse(args);
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        System.exit(-1);
    }

    if (options.isHelp()) {
        new HelpFormatter().printHelp(" ", options.getOptions());
        System.exit(0);
    }

    if (options.isInsecure()) {
        SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
    }

    LoggingConfig.init(options.isVerbose());
    if (options.isWirelogVerbose()) {
        LoggingConfig.enableWireLog();
    }

    ServiceProviderDao serviceProviderDao = new ServiceProviderDao();
    ConsumerDao consumerDao = new ConsumerDao(options);
    AccessorDao accessorDao = new AccessorDao();

    String serviceProviderFileName = options.getServiceProviderFileName();
    if (serviceProviderFileName == null) {
        if (options.isBuzz()) {
            // Buzz has its own provider because it has a custom authorization URL
            serviceProviderFileName = "BUZZ";
        } else if (options.getVersion() == OAuthVersion.V2) {
            serviceProviderFileName = "GOOGLE_V2";
        } else {
            serviceProviderFileName = "GOOGLE";
        }
    }

    // We have a wee library of service provider properties files bundled into
    // the resources, so we set up the PropertiesProvider to search for them
    // if the file cannot be found.
    OAuthServiceProvider serviceProvider = serviceProviderDao.loadServiceProvider(
            new PropertiesProvider(serviceProviderFileName, ServiceProviderDao.class, "services/").get());
    OAuthConsumer consumer = consumerDao
            .loadConsumer(new PropertiesProvider(options.getConsumerFileName()).get(), serviceProvider);
    OAuthAccessor accessor = accessorDao.newAccessor(consumer);

    OAuthClient client = new OAuthClient(new HttpClient4());

    LoginCallbackServer callbackServer = null;

    boolean launchedBrowser = false;

    try {
        if (!options.isNoServer()) {
            callbackServer = new LoginCallbackServer(options);
            callbackServer.start();
        }

        String callbackUrl;
        if (options.getCallback() != null) {
            callbackUrl = options.getCallback();
        } else if (callbackServer != null) {
            callbackUrl = callbackServer.getCallbackUrl();
        } else {
            callbackUrl = null;
        }

        OAuthEngine engine;
        switch (options.getVersion()) {
        case V1:
            engine = new V1OAuthEngine();
            break;
        case V2:
            engine = new V2OAuthEngine();
            break;
        case WRAP:
            engine = new WrapOAuthEngine();
            break;
        default:
            throw new IllegalArgumentException("Unknown version: " + options.getVersion());
        }

        do {
            String authorizationUrl = engine.getAuthorizationUrl(client, accessor, options, callbackUrl);

            if (!options.isNoServer()) {
                callbackServer.setAuthorizationUrl(authorizationUrl);
            }

            if (!launchedBrowser) {
                String url = options.isDemo() ? callbackServer.getDemoUrl() : authorizationUrl;

                if (options.isNoBrowser()) {
                    System.out.println(url);
                    System.out.flush();
                } else {
                    launchBrowser(options, url);
                }

                launchedBrowser = true;
            }

            accessor.accessToken = null;

            logger.log(Level.INFO, "Waiting for verification token...");
            String verifier;
            if (options.isNoServer()) {
                System.out.print("Verification token: ");
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                verifier = "";
                while (verifier.isEmpty()) {
                    String line = reader.readLine();
                    if (line == null) {
                        System.exit(-1);
                    }
                    verifier = line.trim();
                }
            } else {
                verifier = callbackServer.waitForVerifier(accessor, -1);
                if (verifier == null) {
                    System.err.println("Wait for verifier interrupted");
                    System.exit(-1);
                }
            }
            logger.log(Level.INFO, "Verification token received: " + verifier);

            boolean success = engine.getAccessToken(accessor, client, callbackUrl, verifier);

            if (success) {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.VALID);
                }

                Properties loginProperties = new Properties();
                accessorDao.saveAccessor(accessor, loginProperties);
                consumerDao.saveConsumer(consumer, loginProperties);
                loginProperties.put("oauthVersion", options.getVersion().toString());
                new PropertiesProvider(options.getLoginFileName()).overwrite(loginProperties);
            } else {
                if (callbackServer != null) {
                    callbackServer.setTokenStatus(TokenStatus.INVALID);
                }
            }
        } while (options.isDemo());
    } catch (OAuthProblemException e) {
        OAuthUtil.printOAuthProblemException(e);
    } finally {
        if (callbackServer != null) {
            callbackServer.stop();
        }
    }
}

From source file:eu.fbk.dkm.sectionextractor.pantheon.WikipediaGoodTextExtractor.java

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

    CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger();
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("wikipedia xml dump file").isRequired().withLongOpt("wikipedia-dump").create("d"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("dir").hasArg()
            .withDescription("output directory in which to store output files").isRequired()
            .withLongOpt("output-dir").create("o"));
    commandLineWithLogger//w w w .j a  v  a 2s . c  o m
            .addOption(OptionBuilder.withDescription("use NAF format").withLongOpt("naf").create("n"));
    commandLineWithLogger.addOption(OptionBuilder.withDescription("tokenize and ssplit with Stanford")
            .withLongOpt("stanford").create("s"));

    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Filter file")
            .withLongOpt("filter").create("f"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("ID and category file").withLongOpt("idcat").create("i"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Redirect file")
            .withLongOpt("redirect").create("r"));

    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription(
                    "number of threads (default " + AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER + ")")
            .withLongOpt("num-threads").create("t"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("number of pages to process (default all)").withLongOpt("num-pages").create("p"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("int").hasArg()
            .withDescription("receive notification every n pages (default "
                    + AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT + ")")
            .withLongOpt("notification-point").create("b"));
    commandLineWithLogger.addOption(new Option("n", "NAF format"));

    CommandLine commandLine = null;
    try {
        commandLine = commandLineWithLogger.getCommandLine(args);
        PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps());
    } catch (Exception e) {
        System.exit(1);
    }

    int numThreads = Integer.parseInt(commandLine.getOptionValue("num-threads",
            Integer.toString(AbstractWikipediaXmlDumpParser.DEFAULT_THREADS_NUMBER)));
    int numPages = Integer.parseInt(commandLine.getOptionValue("num-pages",
            Integer.toString(AbstractWikipediaExtractor.DEFAULT_NUM_PAGES)));
    int notificationPoint = Integer.parseInt(commandLine.getOptionValue("notification-point",
            Integer.toString(AbstractWikipediaExtractor.DEFAULT_NOTIFICATION_POINT)));

    boolean nafFormat = commandLine.hasOption("n");
    boolean useStanford = commandLine.hasOption("s");

    HashMap<Integer, String> idCategory = new HashMap<>();
    String idcatFileName = commandLine.getOptionValue("idcat");
    if (idcatFileName != null) {
        logger.info("Loading categories");
        File idcatFile = new File(idcatFileName);
        if (idcatFile.exists()) {
            List<String> lines = Files.readLines(idcatFile, Charsets.UTF_8);
            for (String line : lines) {
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }

                String[] parts = line.split("\\s+");
                if (parts.length < 3) {
                    continue;
                }

                idCategory.put(Integer.parseInt(parts[1]), parts[2]);
            }
        }
    }

    HashMap<String, String> redirects = new HashMap<>();
    String redirectFileName = commandLine.getOptionValue("redirect");
    if (redirectFileName != null) {
        logger.info("Loading redirects");
        File redirectFile = new File(redirectFileName);
        if (redirectFile.exists()) {
            List<String> lines = Files.readLines(redirectFile, Charsets.UTF_8);
            for (String line : lines) {
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }

                String[] parts = line.split("\\t+");
                if (parts.length < 2) {
                    continue;
                }

                redirects.put(parts[0], parts[1]);
            }
        }
    }

    HashSet<String> pagesToConsider = null;
    String filterFileName = commandLine.getOptionValue("filter");
    if (filterFileName != null) {
        logger.info("Loading file list");
        File filterFile = new File(filterFileName);
        if (filterFile.exists()) {
            pagesToConsider = new HashSet<>();
            List<String> lines = Files.readLines(filterFile, Charsets.UTF_8);
            for (String line : lines) {
                line = line.trim();
                if (line.length() == 0) {
                    continue;
                }

                line = line.replaceAll("\\s+", "_");

                pagesToConsider.add(line);

                addRedirects(pagesToConsider, redirects, line, 0);
            }
        }
    }

    ExtractorParameters extractorParameters = new ExtractorParameters(
            commandLine.getOptionValue("wikipedia-dump"), commandLine.getOptionValue("output-dir"));

    File outputFolder = new File(commandLine.getOptionValue("output-dir"));
    if (!outputFolder.exists()) {
        boolean mkdirs = outputFolder.mkdirs();
        if (!mkdirs) {
            throw new IOException("Unable to create folder " + outputFolder.getAbsolutePath());
        }
    }

    WikipediaExtractor wikipediaPageParser = new WikipediaGoodTextExtractor(numThreads, numPages,
            extractorParameters.getLocale(), outputFolder, nafFormat, pagesToConsider, useStanford, idCategory);
    wikipediaPageParser.setNotificationPoint(notificationPoint);
    wikipediaPageParser.start(extractorParameters);

    logger.info("extraction ended " + new Date());

}

From source file:com.adobe.aem.demomachine.Json2Csv.java

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

    String inputFile1 = null;//from www  .  j  av  a2s. c om
    String inputFile2 = null;
    String outputFile = null;

    HashMap<String, String> hmReportSuites = new HashMap<String, String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("c", true, "Filename 1");
    options.addOption("r", true, "Filename 2");
    options.addOption("o", true, "Filename 3");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("c")) {
            inputFile1 = cmd.getOptionValue("c");
        }

        if (cmd.hasOption("r")) {
            inputFile2 = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("o")) {
            outputFile = cmd.getOptionValue("o");
        }

        if (inputFile1 == null || inputFile1 == null || outputFile == null) {
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    // List of customers and report suites for these customers
    String sInputFile1 = readFile(inputFile1, Charset.defaultCharset());
    sInputFile1 = sInputFile1.replaceAll("ObjectId\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

    // Processing the list of report suites for each customer
    try {

        JSONArray jCustomers = new JSONArray(sInputFile1.trim());
        for (int i = 0, size = jCustomers.length(); i < size; i++) {
            JSONObject jCustomer = jCustomers.getJSONObject(i);
            Iterator<?> keys = jCustomer.keys();
            String companyName = null;
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("company")) {
                    companyName = jCustomer.getString(key);
                }
            }
            keys = jCustomer.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();

                if (key.equals("report_suites")) {
                    JSONArray jReportSuites = jCustomer.getJSONArray(key);
                    for (int j = 0, rSize = jReportSuites.length(); j < rSize; j++) {
                        hmReportSuites.put(jReportSuites.getString(j), companyName);
                        System.out.println(jReportSuites.get(j) + " for company " + companyName);
                    }

                }
            }
        }

        // Creating the out put file
        PrintWriter writer = new PrintWriter(outputFile, "UTF-8");
        writer.println("\"" + "Customer" + "\",\"" + "ReportSuite ID" + "\",\"" + "Number of Documents"
                + "\",\"" + "Last Updated" + "\"");

        // Processing the list of SOLR collections
        String sInputFile2 = readFile(inputFile2, Charset.defaultCharset());
        sInputFile2 = sInputFile2.replaceAll("NumberLong\\(\"([0-9a-z]*)\"\\)", "\"$1\"");

        JSONObject jResults = new JSONObject(sInputFile2.trim());
        JSONArray jCollections = jResults.getJSONArray("result");
        for (int i = 0, size = jCollections.length(); i < size; i++) {
            JSONObject jCollection = jCollections.getJSONObject(i);
            String id = null;
            String number = null;
            String lastupdate = null;

            Iterator<?> keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("_id")) {
                    id = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("noOfDocs")) {
                    number = jCollection.getString(key);
                }
            }

            keys = jCollection.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("latestUpdateDate")) {
                    lastupdate = jCollection.getString(key);
                }
            }

            Date d = new Date(Long.parseLong(lastupdate));
            System.out.println(hmReportSuites.get(id) + "," + id + "," + number + "," + lastupdate + ","
                    + new SimpleDateFormat("MM-dd-yyyy").format(d));
            writer.println("\"" + hmReportSuites.get(id) + "\",\"" + id + "\",\"" + number + "\",\""
                    + new SimpleDateFormat("MM-dd-yyyy").format(d) + "\"");

        }

        writer.close();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:edu.cmu.tetrad.cli.search.FgsCli.java

/**
 * @param args the command line arguments
 */// w  w w . j  a  va 2  s. c  o m
public static void main(String[] args) {
    if (args == null || args.length == 0 || Args.hasLongOption(args, "help")) {
        Args.showHelp("fgs", MAIN_OPTIONS);
        return;
    }

    parseArgs(args);

    System.out.println("================================================================================");
    System.out.printf("FGS Discrete (%s)%n", DateTime.printNow());
    System.out.println("================================================================================");

    String argInfo = createArgsInfo();
    System.out.println(argInfo);
    LOGGER.info("=== Starting FGS Discrete: " + Args.toString(args, ' '));
    LOGGER.info(argInfo.trim().replaceAll("\n", ",").replaceAll(" = ", "="));

    Set<String> excludedVariables = (excludedVariableFile == null) ? Collections.EMPTY_SET
            : getExcludedVariables();

    runPreDataValidations(excludedVariables, System.err);
    DataSet dataSet = readInDataSet(excludedVariables);
    runOptionalDataValidations(dataSet, System.err);

    Path outputFile = Paths.get(dirOut.toString(), outputPrefix + ".txt");
    try (PrintStream writer = new PrintStream(
            new BufferedOutputStream(Files.newOutputStream(outputFile, StandardOpenOption.CREATE)))) {
        String runInfo = createOutputRunInfo(excludedVariables, dataSet);
        writer.println(runInfo);
        String[] infos = runInfo.trim().replaceAll("\n\n", ";").split(";");
        for (String s : infos) {
            LOGGER.info(s.trim().replaceAll("\n", ",").replaceAll(":,", ":").replaceAll(" = ", "="));
        }

        Graph graph = runFgs(dataSet, writer);

        writer.println();
        writer.println(graph.toString());
    } catch (IOException exception) {
        LOGGER.error("FGS failed.", exception);
        System.err.printf("%s: FGS failed.%n", DateTime.printNow());
        System.out.println("Please see log file for more information.");
        System.exit(-128);
    }
    System.out.printf("%s: FGS finished!  Please see %s for details.%n", DateTime.printNow(),
            outputFile.getFileName().toString());
    LOGGER.info(
            String.format("FGS finished!  Please see %s for details.", outputFile.getFileName().toString()));
}

From source file:AwsConsoleApp.java

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

    System.out.println("===========================================");
    System.out.println("Welcome to the AWS VPN connection creator");
    System.out.println("===========================================");

    init();//w ww  . ja  v a  2s.  c o  m
    List<String> CIDRblocks = new ArrayList<String>();
    String vpnType = null;
    String vpnGatewayId = null;
    String customerGatewayId = null;
    String customerGatewayInfoPath = null;
    String routes = null;

    options.addOption("h", "help", false, "show help.");
    options.addOption("vt", "vpntype", true, "Set vpn tunnel type e.g. (ipec.1)");
    options.addOption("vgw", "vpnGatewayId", true, "Set AWS VPN Gateway ID e.g. (vgw-eca54d85)");
    options.addOption("cgw", "customerGatewayId", true, "Set AWS Customer Gateway ID e.g. (cgw-c16e87a8)");
    options.addOption("r", "staticroutes", true, "Set static routes e.g. cutomer subnet 10.77.77.0/24");
    options.addOption("vi", "vpninfo", true, "path to vpn info file c:\\temp\\customerGatewayInfo.xml");

    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    // Parse command line options
    try {
        cmd = parser.parse(options, args);

        if (cmd.hasOption("h"))
            help();

        if (cmd.hasOption("vt")) {
            log.log(Level.INFO, "Using cli argument -vt=" + cmd.getOptionValue("vt"));

            vpnType = cmd.getOptionValue("vt");

            // Whatever you want to do with the setting goes here
        } else {
            log.log(Level.SEVERE, "Missing vt option");
            help();
        }

        if (cmd.hasOption("vgw")) {
            log.log(Level.INFO, "Using cli argument -vgw=" + cmd.getOptionValue("vgw"));
            vpnGatewayId = cmd.getOptionValue("vgw");
        } else {
            log.log(Level.SEVERE, "Missing vgw option");
            help();
        }

        if (cmd.hasOption("cgw")) {
            log.log(Level.INFO, "Using cli argument -cgw=" + cmd.getOptionValue("cgw"));
            customerGatewayId = cmd.getOptionValue("cgw");

        } else {
            log.log(Level.SEVERE, "Missing cgw option");
            help();
        }

        if (cmd.hasOption("r")) {
            log.log(Level.INFO, "Using cli argument -r=" + cmd.getOptionValue("r"));
            routes = cmd.getOptionValue("r");

            String[] routeItems = routes.split(",");
            CIDRblocks = Arrays.asList(routeItems);

        } else {
            log.log(Level.SEVERE, "Missing r option");
            help();
        }

        if (cmd.hasOption("vi")) {
            log.log(Level.INFO, "Using cli argument -vi=" + cmd.getOptionValue("vi"));
            customerGatewayInfoPath = cmd.getOptionValue("vi");

        } else {
            log.log(Level.SEVERE, "Missing vi option");
            help();
        }

    } catch (ParseException e) {
        log.log(Level.SEVERE, "Failed to parse comand line properties", e);
        help();
    }

    /*
     * Amazon VPC
     * Create and delete VPN tunnel to customer VPN hardware
     */
    try {

        //String vpnType = "ipsec.1";
        //String vpnGatewayId = "vgw-eca54d85";
        //String customerGatewayId = "cgw-c16e87a8";
        //List<String> CIDRblocks = new ArrayList<String>();
        //CIDRblocks.add("10.77.77.0/24");
        //CIDRblocks.add("172.16.1.0/24");
        //CIDRblocks.add("172.18.1.0/24");
        //CIDRblocks.add("10.66.66.0/24");
        //CIDRblocks.add("10.8.1.0/24");

        //String customerGatewayInfoPath = "c:\\temp\\customerGatewayInfo.xml";

        Boolean staticRoutesOnly = true;

        List<String> connectionIds = new ArrayList<String>();
        List<String> connectionIdList = new ArrayList<String>();

        connectionIdList = vpnExists(connectionIds);

        if (connectionIdList.size() == 0) {
            CreateVpnConnectionRequest vpnReq = new CreateVpnConnectionRequest(vpnType, customerGatewayId,
                    vpnGatewayId);
            CreateVpnConnectionResult vpnRes = new CreateVpnConnectionResult();

            VpnConnectionOptionsSpecification vpnspec = new VpnConnectionOptionsSpecification();
            vpnspec.setStaticRoutesOnly(staticRoutesOnly);
            vpnReq.setOptions(vpnspec);

            System.out.println("Creating VPN connection");
            vpnRes = ec2.createVpnConnection(vpnReq);
            String vpnConnId = vpnRes.getVpnConnection().getVpnConnectionId();
            String customerGatewayInfo = vpnRes.getVpnConnection().getCustomerGatewayConfiguration();

            //System.out.println("Customer Gateway Info:" + customerGatewayInfo);

            // Write Customer Gateway Info to file
            System.out.println("Writing Customer Gateway Info to file:" + customerGatewayInfoPath);
            try (PrintStream out = new PrintStream(new FileOutputStream(customerGatewayInfoPath))) {
                out.print(customerGatewayInfo);
            }

            System.out.println("Creating VPN routes");
            for (String destCIDR : CIDRblocks) {
                CreateVpnConnectionRouteRequest routeReq = new CreateVpnConnectionRouteRequest();
                CreateVpnConnectionRouteResult routeRes = new CreateVpnConnectionRouteResult();

                routeReq.setDestinationCidrBlock(destCIDR);
                routeReq.setVpnConnectionId(vpnConnId);

                routeRes = ec2.createVpnConnectionRoute(routeReq);
            }

            // Parse XML file
            File file = new File(customerGatewayInfoPath);
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document document = db.parse(customerGatewayInfoPath);

            XPathFactory xPathfactory = XPathFactory.newInstance();
            XPath xpath = xPathfactory.newXPath();
            XPathExpression exprGetipAddress = xpath
                    .compile("/vpn_connection/ipsec_tunnel/vpn_gateway/tunnel_outside_address/ip_address");
            NodeList vpnGateway = (NodeList) exprGetipAddress.evaluate(document, XPathConstants.NODESET);
            if (vpnGateway != null) {
                for (int i = 0; i < vpnGateway.getLength(); i++) {
                    String vpnGatewayIP = vpnGateway.item(i).getTextContent();
                    System.out
                            .println("AWS vpnGatewayIP for tunnel " + Integer.toString(i) + " " + vpnGatewayIP);
                }
            }

            System.out.println("==============================================");

            XPathExpression exprGetKey = xpath.compile("/vpn_connection/ipsec_tunnel/ike/pre_shared_key");
            NodeList presharedKeyList = (NodeList) exprGetKey.evaluate(document, XPathConstants.NODESET);
            if (presharedKeyList != null) {
                for (int i = 0; i < presharedKeyList.getLength(); i++) {
                    String pre_shared_key = presharedKeyList.item(i).getTextContent();
                    System.out.println(
                            "AWS pre_shared_key for tunnel " + Integer.toString(i) + " " + pre_shared_key);
                }
            }

            System.out.println("Creating VPN creation completed!");

        } else {
            boolean yn;
            Scanner scan = new Scanner(System.in);
            System.out.println("Enter yes or no to delete VPN connection: ");
            String input = scan.next();
            String answer = input.trim().toLowerCase();
            while (true) {
                if (answer.equals("yes")) {
                    yn = true;
                    break;
                } else if (answer.equals("no")) {
                    yn = false;
                    System.exit(0);
                } else {
                    System.out.println("Sorry, I didn't catch that. Please answer yes/no");
                }
            }

            // Delete all existing VPN connections
            System.out.println("Deleting AWS VPN connection(s)");

            for (String vpnConID : connectionIdList) {
                DeleteVpnConnectionResult delVPNres = new DeleteVpnConnectionResult();
                DeleteVpnConnectionRequest delVPNreq = new DeleteVpnConnectionRequest();
                delVPNreq.setVpnConnectionId(vpnConID);

                delVPNres = ec2.deleteVpnConnection(delVPNreq);
                System.out.println("Successfully deleted AWS VPN conntion: " + vpnConID);

            }

        }

    } catch (AmazonServiceException ase) {
        System.out.println("Caught Exception: " + ase.getMessage());
        System.out.println("Reponse Status Code: " + ase.getStatusCode());
        System.out.println("Error Code: " + ase.getErrorCode());
        System.out.println("Request ID: " + ase.getRequestId());
    }

}

From source file:Whois.java

public static void main(String[] args) {
    String hostname = "";
    String ulist = "";
    if (args.length == 0) {
        System.out.println("usage: whois [%host] query");
        System.exit(1);//from  ww  w . java  2 s.  c o m
    }
    int argn = 0;
    hostname = "whois.networksolutions.com"; // default
    if (args.length > 1 && args[0].charAt(0) == '%') {
        hostname = args[argn].substring(1);
        argn++;
    }
    for (int i = argn; i < args.length; i++)
        ulist += args[i] + " ";
    Whois worker = new Whois();
    try {
        System.out.println(worker.whois(ulist.trim(), hostname));
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.twentyn.patentSearch.DocumentSearch.java

public static void main(String[] args) throws Exception {
    System.out.println("Starting up...");
    System.out.flush();/*from w  ww  .j  a  va  2 s.  com*/
    Options opts = new Options();
    opts.addOption(Option.builder("x").longOpt("index").hasArg().required().desc("Path to index file to read")
            .build());
    opts.addOption(Option.builder("h").longOpt("help").desc("Print this help message and exit").build());
    opts.addOption(Option.builder("v").longOpt("verbose").desc("Print verbose log output").build());

    opts.addOption(Option.builder("f").longOpt("field").hasArg().desc("The indexed field to search").build());
    opts.addOption(
            Option.builder("q").longOpt("query").hasArg().desc("The query to use when searching").build());
    opts.addOption(Option.builder("l").longOpt("list-file").hasArg()
            .desc("A file containing a list of queries to run in sequence").build());
    opts.addOption(
            Option.builder("e").longOpt("enumerate").desc("Enumerate the documents in the index").build());
    opts.addOption(Option.builder("d").longOpt("dump").hasArg()
            .desc("Dump terms in the document index for a specified field").build());
    opts.addOption(
            Option.builder("o").longOpt("output").hasArg().desc("Write results JSON to this file.").build());
    opts.addOption(Option.builder("n").longOpt("inchi-field").hasArg()
            .desc("The index of the InChI field if an input TSV is specified.").build());
    opts.addOption(Option.builder("s").longOpt("synonym-field").hasArg()
            .desc("The index of the chemical synonym field if an input TSV is specified.").build());

    HelpFormatter helpFormatter = new HelpFormatter();
    CommandLineParser cmdLineParser = new DefaultParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = cmdLineParser.parse(opts, args);
    } catch (ParseException e) {
        System.out.println("Caught exception when parsing command line: " + e.getMessage());
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("help")) {
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(0);
    }

    if (!(cmdLine.hasOption("enumerate") || cmdLine.hasOption("dump") || (cmdLine.hasOption("field")
            && (cmdLine.hasOption("query") || cmdLine.hasOption("list-file"))))) {
        System.out.println("Must specify one of 'enumerate', 'dump', or 'field' + {'query', 'list-file'}");
        helpFormatter.printHelp("DocumentIndexer", opts);
        System.exit(1);
    }

    if (cmdLine.hasOption("verbose")) {
        // With help from http://stackoverflow.com/questions/23434252/programmatically-change-log-level-in-log4j2
        LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
        Configuration ctxConfig = ctx.getConfiguration();
        LoggerConfig logConfig = ctxConfig.getLoggerConfig(LogManager.ROOT_LOGGER_NAME);
        logConfig.setLevel(Level.DEBUG);

        ctx.updateLoggers();
        LOGGER.debug("Verbose logging enabled");
    }

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);

    LOGGER.info("Opening index at " + cmdLine.getOptionValue("index"));

    try (Directory indexDir = FSDirectory.open(new File(cmdLine.getOptionValue("index")).toPath());
            IndexReader indexReader = DirectoryReader.open(indexDir);) {
        if (cmdLine.hasOption("enumerate")) {
            /* Enumerate all documents in the index.
             * With help from
             * http://stackoverflow.com/questions/2311845/is-it-possible-to-iterate-through-documents-stored-in-lucene-index
             */
            for (int i = 0; i < indexReader.maxDoc(); i++) {
                Document doc = indexReader.document(i);
                LOGGER.info("Doc " + i + ":");
                LOGGER.info(doc);
            }
        } else if (cmdLine.hasOption("dump")) {
            /* Dump indexed terms for a specific field.
             * With help from http://stackoverflow.com/questions/11148036/find-list-of-terms-indexed-by-lucene */
            Terms terms = SlowCompositeReaderWrapper.wrap(indexReader).terms(cmdLine.getOptionValue("dump"));
            LOGGER.info("Has positions: " + terms.hasPositions());
            LOGGER.info("Has offsets:   " + terms.hasOffsets());
            LOGGER.info("Has freqs:     " + terms.hasFreqs());
            LOGGER.info("Stats:         " + terms.getStats());
            LOGGER.info(terms);
            TermsEnum termsEnum = terms.iterator();
            BytesRef br = null;
            while ((br = termsEnum.next()) != null) {
                LOGGER.info("  " + br.utf8ToString());
            }

        } else {
            IndexSearcher searcher = new IndexSearcher(indexReader);
            String field = cmdLine.getOptionValue("field");

            List<Pair<String, String>> queries = null;
            if (cmdLine.hasOption("query")) {
                queries = Collections.singletonList(Pair.of("", cmdLine.getOptionValue("query")));
            } else if (cmdLine.hasOption("list-file")) {
                if (!(cmdLine.hasOption("inchi-field") && cmdLine.hasOption("synonym-field"))) {
                    LOGGER.error("Must specify both inchi-field and synonym-field when using list-file.");
                    System.exit(1);
                }
                Integer inchiField = Integer.parseInt(cmdLine.getOptionValue("inchi-field"));
                Integer synonymField = Integer.parseInt(cmdLine.getOptionValue("synonym-field"));

                queries = new LinkedList<>();
                BufferedReader r = new BufferedReader(new FileReader(cmdLine.getOptionValue("list-file")));
                String line;
                while ((line = r.readLine()) != null) {
                    line = line.trim();
                    if (!line.isEmpty()) {
                        // TODO: use a proper TSV reader; this is intentionally terrible as is.
                        String[] fields = line.split("\t");
                        queries.add(Pair.of(fields[inchiField].replace("\"", ""), fields[synonymField]));
                    }
                }
                r.close();
            }

            if (queries == null || queries.size() == 0) {
                LOGGER.error("Found no queries to run.");
                return;
            }

            List<SearchResult> searchResults = new ArrayList<>(queries.size());
            for (Pair<String, String> queryPair : queries) {
                String inchi = queryPair.getLeft();
                String rawQueryString = queryPair.getRight();
                /* The Lucene query parser interprets the kind of structural annotations we see in chemical entities
                 * as query directives, which is not what we want at all.  Phrase queries seem to work adequately
                 * with the analyzer we're currently using. */
                String queryString = rawQueryString.trim().toLowerCase();
                String[] parts = queryString.split("\\s+");
                PhraseQuery query = new PhraseQuery();
                for (String p : parts) {
                    query.add(new Term(field, p));
                }
                LOGGER.info("Running query: " + query.toString());

                BooleanQuery bq = new BooleanQuery();
                bq.add(query, BooleanClause.Occur.MUST);
                bq.add(new TermQuery(new Term(field, "yeast")), BooleanClause.Occur.SHOULD);
                bq.add(new TermQuery(new Term(field, "ferment")), BooleanClause.Occur.SHOULD);
                bq.add(new TermQuery(new Term(field, "fermentation")), BooleanClause.Occur.SHOULD);
                bq.add(new TermQuery(new Term(field, "fermentive")), BooleanClause.Occur.SHOULD);
                bq.add(new TermQuery(new Term(field, "saccharomyces")), BooleanClause.Occur.SHOULD);

                LOGGER.info("  Full query: " + bq.toString());

                TopDocs topDocs = searcher.search(bq, 100);
                ScoreDoc[] scoreDocs = topDocs.scoreDocs;
                if (scoreDocs.length == 0) {
                    LOGGER.info("Search returned no results.");
                }
                List<ResultDocument> results = new ArrayList<>(scoreDocs.length);
                for (int i = 0; i < scoreDocs.length; i++) {
                    ScoreDoc scoreDoc = scoreDocs[i];
                    Document doc = indexReader.document(scoreDoc.doc);
                    LOGGER.info("Doc " + i + ": " + scoreDoc.doc + ", score " + scoreDoc.score + ": "
                            + doc.get("id") + ", " + doc.get("title"));
                    results.add(new ResultDocument(scoreDoc.doc, scoreDoc.score, doc.get("title"),
                            doc.get("id"), null));
                }
                LOGGER.info("----- Done with query " + query.toString());
                // TODO: reduce memory usage when not writing results to an output file.
                searchResults.add(new SearchResult(inchi, rawQueryString, bq, results));
            }

            if (cmdLine.hasOption("output")) {
                try (FileWriter writer = new FileWriter(cmdLine.getOptionValue("output"));) {
                    writer.write(objectMapper.writeValueAsString(searchResults));
                }
            }
        }
    }
}

From source file:com.l2jfree.loginserver.tools.L2GameServerRegistrar.java

/**
 * Launches the interactive game server registration.
 * /*from w  ww .j a  v a 2s  .c o m*/
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Game Server Registration");
    _log.info("Please choose:");
    _log.info("list - list registered game servers");
    _log.info("reg - register a game server");
    _log.info("rem - remove a registered game server");
    _log.info("hexid - generate a legacy hexid file");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2GameServerRegistrar reg = new L2GameServerRegistrar();

    String line;
    try {
        RegistrationState next = RegistrationState.INITIAL_CHOICE;
        while ((line = br.readLine()) != null) {
            line = line.trim().toLowerCase();
            switch (reg.getState()) {
            case GAMESERVER_ID:
                try {
                    int id = Integer.parseInt(line);
                    if (id < 1 || id > 127)
                        throw new IllegalArgumentException("ID must be in [1;127].");
                    reg.setId(id);
                    reg.setState(next);
                } catch (RuntimeException e) {
                    _log.info("You must input a number between 1 and 127");
                }

                if (reg.getState() == RegistrationState.ALLOW_BANS) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT allowBans FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();
                        if (rs.next()) {
                            _log.info("A game server is already registered on ID " + reg.getId());
                            reg.setState(RegistrationState.INITIAL_CHOICE);
                        } else
                            _log.info("Allow account bans from this game server? [y/n]:");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                } else if (reg.getState() == RegistrationState.REMOVE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("DELETE FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        int cnt = ps.executeUpdate();
                        if (cnt == 0)
                            _log.info("No game server registered on ID " + reg.getId());
                        else
                            _log.info("Game server removed.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not remove a game server!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (reg.getState() == RegistrationState.GENERATE) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con
                                .prepareStatement("SELECT authData FROM gameserver WHERE id = ?");
                        ps.setInt(1, reg.getId());
                        ResultSet rs = ps.executeQuery();

                        if (rs.next()) {
                            reg.setAuth(rs.getString("authData"));
                            byte[] b = HexUtil.hexStringToBytes(reg.getAuth());

                            Properties pro = new Properties();
                            pro.setProperty("ServerID", String.valueOf(reg.getId()));
                            pro.setProperty("HexID", HexUtil.hexToString(b));

                            BufferedOutputStream os = new BufferedOutputStream(
                                    new FileOutputStream("hexid.txt"));
                            pro.store(os, "the hexID to auth into login");
                            IOUtils.closeQuietly(os);
                            _log.info("hexid.txt has been generated.");
                        } else
                            _log.info("No game server registered on ID " + reg.getId());

                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not generate hexid.txt!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                }
                break;
            case ALLOW_BANS:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        reg.setTrusted(true);
                    else if (line.charAt(0) == 'n')
                        reg.setTrusted(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    byte[] auth = Rnd.nextBytes(new byte[BYTES]);
                    reg.setAuth(HexUtil.bytesToHexString(auth));

                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO gameserver (id, authData, allowBans) VALUES (?, ?, ?)");
                        ps.setInt(1, reg.getId());
                        ps.setString(2, reg.getAuth());
                        ps.setBoolean(3, reg.isTrusted());
                        ps.executeUpdate();
                        ps.close();

                        _log.info("Registered game server on ID " + reg.getId());
                        _log.info("The authorization string is:");
                        _log.info(reg.getAuth());
                        _log.info("Use it when registering this login server.");
                        _log.info("If you need a legacy hexid file, use the 'hexid' command.");
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }

                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            default:
                if (line.equals("list")) {
                    Connection con = null;
                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement("SELECT id, allowBans FROM gameserver");
                        ResultSet rs = ps.executeQuery();
                        while (rs.next())
                            _log.info("ID: " + rs.getInt("id") + ", trusted: " + rs.getBoolean("allowBans"));
                        rs.close();
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register gameserver!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    reg.setState(RegistrationState.INITIAL_CHOICE);
                } else if (line.equals("reg")) {
                    _log.info("Enter the desired ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.ALLOW_BANS;
                } else if (line.equals("rem")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.REMOVE;
                } else if (line.equals("hexid")) {
                    _log.info("Enter game server ID:");
                    reg.setState(RegistrationState.GAMESERVER_ID);
                    next = RegistrationState.GENERATE;
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}