Example usage for java.util Properties getProperty

List of usage examples for java.util Properties getProperty

Introduction

In this page you can find the example usage for java.util Properties getProperty.

Prototype

public String getProperty(String key, String defaultValue) 

Source Link

Document

Searches for the property with the specified key in this property list.

Usage

From source file:BookRank.java

/** Grab the sales rank off the web page and log it. */
public static void main(String[] args) throws Exception {

    Properties p = new Properties();
    String title = p.getProperty("title", "NO TITLE IN PROPERTIES");
    // The url must have the "isbn=" at the very end, or otherwise
    // be amenable to being string-catted to, like the default.
    String url = p.getProperty("url", "http://test.ing/test.cgi?isbn=");
    // The 10-digit ISBN for the book.
    String isbn = p.getProperty("isbn", "0000000000");
    // The RE pattern (MUST have ONE capture group for the number)
    String pattern = p.getProperty("pattern", "Rank: (\\d+)");

    // Looking for something like this in the input:
    //    <b>QuickBookShop.web Sales Rank: </b>
    //    26,252/* w ww . j  a v a2s .c  o m*/
    //    </font><br>

    Pattern r = Pattern.compile(pattern);

    // Open the URL and get a Reader from it.
    BufferedReader is = new BufferedReader(new InputStreamReader(new URL(url + isbn).openStream()));
    // Read the URL looking for the rank information, as
    // a single long string, so can match RE across multi-lines.
    String input = "input from console";
    // System.out.println(input);

    // If found, append to sales data file.
    Matcher m = r.matcher(input);
    if (m.find()) {
        PrintWriter pw = new PrintWriter(new FileWriter(DATA_FILE, true));
        String date = // `date +'%m %d %H %M %S %Y'`;
                new SimpleDateFormat("MM dd hh mm ss yyyy ").format(new Date());
        // Paren 1 is the digits (and maybe ','s) that matched; remove comma
        Matcher noComma = Pattern.compile(",").matcher(m.group(1));
        pw.println(date + noComma.replaceAll(""));
        pw.close();
    } else {
        System.err.println("WARNING: pattern `" + pattern + "' did not match in `" + url + isbn + "'!");
    }

    // Whether current data found or not, draw the graph, using
    // external plotting program against all historical data.
    // Could use gnuplot, R, any other math/graph program.
    // Better yet: use one of the Java plotting APIs.

    String gnuplot_cmd = "set term png\n" + "set output \"" + GRAPH_FILE + "\"\n" + "set xdata time\n"
            + "set ylabel \"Book sales rank\"\n" + "set bmargin 3\n" + "set logscale y\n"
            + "set yrange [1:60000] reverse\n" + "set timefmt \"%m %d %H %M %S %Y\"\n" + "plot \"" + DATA_FILE
            + "\" using 1:7 title \"" + title + "\" with lines\n";

    Process proc = Runtime.getRuntime().exec("/usr/local/bin/gnuplot");
    PrintWriter gp = new PrintWriter(proc.getOutputStream());
    gp.print(gnuplot_cmd);
    gp.close();
}

From source file:com.gvmax.web.WebMain.java

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    try {/*ww w.  j a  v a  2  s  .c  o m*/
        MetricRegistry registry = MetricsUtil.getRegistry();
        Properties props = new Properties();
        props.load(new ClassPathResource("/web.properties").getInputStream());

        int httpPort = Integer.parseInt(props.getProperty("web.http.port", "19080"));
        int httpsPort = Integer.parseInt(props.getProperty("web.https.port", "19443"));
        logger.info("Starting server: " + httpPort + " :: " + httpsPort);

        Server server = new Server(httpPort);
        ThreadPool threadPool = new InstrumentedQueuedThreadPool(registry);
        server.setThreadPool(threadPool);

        // Setup HTTPS
        if (new File("gvmax.jks").exists()) {
            SslSocketConnector connector = new SslSocketConnector();
            connector.setPort(httpsPort);
            connector.setKeyPassword(props.getProperty("web.keystore.password"));
            connector.setKeystore("gvmax.jks");
            server.addConnector(connector);
        } else {
            logger.warn("keystore gvmax.jks not found, ssl disabled");
        }

        // Setup WEBAPP
        URL warUrl = WebMain.class.getClassLoader().getResource("webapp");
        String warUrlString = warUrl.toExternalForm();
        WebAppContext ctx = new WebAppContext(warUrlString, "/");
        ctx.setAttribute(MetricsServlet.METRICS_REGISTRY, registry);
        InstrumentedHandler handler = new InstrumentedHandler(registry, ctx);
        server.setHandler(handler);
        server.start();
        server.join();
    } catch (Exception e) {
        logger.error(e);
        System.exit(0);
    }
}

From source file:Main.java

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

    prop.put("Chapter Count", "200");
    prop.put("Tutorial Count", "150");
    prop.put("tutorial", "java2s.com");
    prop.put("Runnable", "true");

    // get two properties and print them
    System.out.println(prop.getProperty("Runnable", "false"));
    System.out.println(prop.getProperty("Tutorial Count", "150"));

}

From source file:mecard.MetroService.java

public static void main(String[] args) {
    // First get the valid options
    Options options = new Options();
    // add t option c to config directory true=arg required.
    options.addOption("c", true,
            "configuration file directory path, include all sys dependant dir seperators like '/'.");
    // add t option c to config directory true=arg required.
    options.addOption("v", false, "Metro server version information.");
    try {// ww  w . j  ava  2 s  . c o  m
        // parse the command line.
        CommandLineParser parser = new BasicParser();
        CommandLine cmd;
        cmd = parser.parse(options, args);
        if (cmd.hasOption("v")) {
            System.out.println("Metro (MeCard) server version " + PropertyReader.VERSION);
        }
        // get c option value
        String configDirectory = cmd.getOptionValue("c");
        PropertyReader.setConfigDirectory(configDirectory);
    } catch (ParseException ex) {
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, null, ex);
        System.out.println(
                new Date() + "Unable to parse command line option. Please check your service configuration.");
        System.exit(799);
    }

    Properties properties = PropertyReader.getProperties(ConfigFileTypes.ENVIRONMENT);
    String portString = properties.getProperty(LibraryPropertyTypes.METRO_PORT.toString(), defaultPort);

    try {
        int port = Integer.parseInt(portString);
        serverSocket = new ServerSocket(port);
    } catch (IOException ex) {
        String msg = " Could not listen on port: " + portString;
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    } catch (NumberFormatException ex) {
        String msg = "Could not parse port number defined in configuration file.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg + ex.getMessage());
    }

    while (listening) {
        try {
            new SocketThread(serverSocket.accept()).start();
        } catch (IOException ex) {
            String msg = "unable to start server socket; either accept or start failed.";
            //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
            System.out.println(new Date() + msg);
        }
    }
    try {
        serverSocket.close();
    } catch (IOException ex) {
        String msg = "failed to close the server socket.";
        //            Logger.getLogger(MetroService.class.getName()).log(Level.SEVERE, msg, ex);
        System.out.println(new Date() + msg);
    }
}

From source file:com.bt.aloha.batchtest.WeekendBatchTest.java

public static void main(String[] args) throws Exception {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("batchTestApplicationContext.xml");
    BatchTest batchTest = (BatchTest) ctx.getBean("batchTestBean");
    batchTest.setApplicationContext(ctx);
    batchTest.init();/* ww w  . ja  va 2s  .  c  o m*/
    batchTest.assignNewCollectionsToBeans();

    while (true) {
        configure(batchTest);
        if (stop)
            break;
        batchTest.run();
        logStatistics(log, batchTest);
        batchTest.reset();
        if (sleepTime > 0) {
            log.info(String.format("sleeping for %d minutes", sleepTime / 60 / 1000));
            Thread.sleep(sleepTime);
        }
    }
    // wait until all things in collection should be ready for housekeeping
    Properties batchProps = new Properties();
    InputStream is = batchTest.getClass().getResourceAsStream("/batchrun.sip.properties");
    batchProps.load(is);
    is.close();
    Thread.sleep(Long.parseLong(batchProps.getProperty("dialog.max.time.to.live", "900000"))
            + Long.parseLong(batchProps.getProperty("housekeeping.interval", "300000")));
    // housekeeping should have happend
    // log out all things still left
    logCollections(batchTest);

    batchTest.destroy();
}

From source file:edu.indiana.d2i.htrc.corpus.analysis.LDAAnalysisDriver.java

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

    GenericOptionsParser parser = new GenericOptionsParser(new Configuration(), args);

    CommandLine commandLine = parser.getCommandLine();

    Option[] options = commandLine.getOptions();

    /**//from w  ww. j  av a  2 s .  c om
     * appArgs[0] = <path/to/input/directory> (where sequence files reside)
     * appArgs[1] = <path/to/output/directory/prefix> (where LDA state file
     * should go) appArgs[2] = <path/local/property/file>
     * 
     * Note: the passed in <path/to/output/directory/prefix> is only a
     * prefix, we automatically append the iteration number suffix
     */
    String[] appArgs = parser.getRemainingArgs();

    // load property file
    Properties prop = new Properties();
    prop.load(new FileInputStream(appArgs[2]));

    int maxIterationNum = Integer.parseInt(
            prop.getProperty(Constants.LDA_ANALYSIS_MAX_ITER, Constants.LDA_ANALYSIS_DEFAULT_MAX_ITER));

    int iterationCount = 0;

    /**
     * in the first iteration (iteration 0), there is no LDA state
     */
    String[] arguments = generateArgs(options, new String[0], appArgs[0],
            appArgs[1] + "-iter-" + iterationCount);

    /**
     * iterate until convergence or maximum iteration number reached
     */
    while (true) {

        int exitCode = ToolRunner.run(new LDAAnalysisDriver(), arguments);

        System.out.println(String.format("LDA analysis finished iteration %d, with exitCode = %d",
                iterationCount, exitCode));

        /**
         * LDA state is the output (sequence file) from current iteration
         * and is used to initialize the words-topics table and
         * topics-documents table for the next iteration
         */
        String ldaStateFilePath = appArgs[1] + "-iter-" + iterationCount + File.separator + "part-r-00000";

        /**
         * load LDA state to check whether it is converged
         */
        if (isAnalysisConverged(ldaStateFilePath)) {
            System.out.println(String.format("LDA analysis converged at iteration %d", iterationCount));
            break;
        }

        if ((iterationCount + 1) >= maxIterationNum) {
            System.out.println(String.format(
                    "LDA analysis reached the maximum iteration number %d, going to stop", maxIterationNum));
            break;
        }

        String[] otherOps = { "-D", "user.args.lda.state.filepath=" + ldaStateFilePath };

        /**
         * generate arguments for the next iteration and increase iteration
         * count
         */
        arguments = generateArgs(options, otherOps, appArgs[0], appArgs[1] + "-iter-" + ++iterationCount);
    }

}

From source file:com.msd.gin.halyard.tools.HalyardUpdate.java

/**
 * Main of the HalyardUpdate/*from ww  w  . ja  v  a  2  s .c  om*/
 * @param args String command line arguments
 * @throws Exception throws Exception in case of any problem
 */
public static void main(final String args[]) throws Exception {
    if (conf == null)
        conf = new Configuration();
    Options options = new Options();
    options.addOption(newOption("h", null, "Prints this help"));
    options.addOption(newOption("v", null, "Prints version"));
    options.addOption(newOption("s", "source_htable", "Source HBase table with Halyard RDF store"));
    options.addOption(
            newOption("q", "sparql_query", "SPARQL tuple or graph query executed to export the data"));
    try {
        CommandLine cmd = new PosixParser().parse(options, args);
        if (args.length == 0 || cmd.hasOption('h')) {
            printHelp(options);
            return;
        }
        if (cmd.hasOption('v')) {
            Properties p = new Properties();
            try (InputStream in = HalyardUpdate.class
                    .getResourceAsStream("/META-INF/maven/com.msd.gin.halyard/hbasesail/pom.properties")) {
                if (in != null)
                    p.load(in);
            }
            System.out.println("Halyard Update version " + p.getProperty("version", "unknown"));
            return;
        }
        if (!cmd.getArgList().isEmpty())
            throw new ParseException("Unknown arguments: " + cmd.getArgList().toString());
        for (char c : "sq".toCharArray()) {
            if (!cmd.hasOption(c))
                throw new ParseException("Missing mandatory option: " + c);
        }
        for (char c : "sq".toCharArray()) {
            String s[] = cmd.getOptionValues(c);
            if (s != null && s.length > 1)
                throw new ParseException("Multiple values for option: " + c);
        }

        SailRepository rep = new SailRepository(
                new HBaseSail(conf, cmd.getOptionValue('s'), false, 0, true, 0, null));
        rep.initialize();
        try {
            Update u = rep.getConnection().prepareUpdate(QueryLanguage.SPARQL, cmd.getOptionValue('q'));
            LOG.info("Update execution started");
            u.execute();
            LOG.info("Update finished");
        } finally {
            rep.shutDown();
        }

    } catch (Exception exp) {
        System.out.println(exp.getMessage());
        printHelp(options);
        throw exp;
    }
}

From source file:com.ibm.watson.developer_cloud.conversation_tone_analyzer_integration.v1.ToneConversationIntegrationV1.java

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

    // load the properties file
    Properties props = new Properties();
    props.load(FileUtils.openInputStream(new File("tone_conversation_integration.properties")));

    // instantiate the conversation service
    ConversationService conversationService = new ConversationService(
            ConversationService.VERSION_DATE_2016_07_11);
    conversationService.setUsernameAndPassword(
            props.getProperty("CONVERSATION_USERNAME", "<conversation_username>"),
            props.getProperty("CONVERSATION_PASSWORD", "<conversation_password>"));

    // instantiate the tone analyzer service
    ToneAnalyzer toneService = new ToneAnalyzer(ToneAnalyzer.VERSION_DATE_2016_05_19);
    toneService.setUsernameAndPassword(props.getProperty("TONE_ANALYZER_USERNAME", "<tone_analyzer_username>"),
            props.getProperty("TONE_ANALYZER_PASSWORD", "<tone_analyzer_password>"));

    // workspace id
    final String workspaceId = props.getProperty("WORKSPACE_ID", "<workspace_id>");

    // maintain history in the context variable - will add a history variable to
    // each of the emotion, social and language tones
    final Boolean maintainHistory = false;

    /**/*from   w w w .  j  a v a  2s. c  o  m*/
     * Input for the conversation service: input (String): an input string (the user's conversation turn) and context
     * (Map<String,Object>: any context that needs to be maintained - either added by the client app or passed in the
     * response from the conversation service on the previous conversation turn.
     */
    final String input = "I am happy";
    final Map<String, Object> context = new HashMap<String, Object>();

    // UPDATE CONTEXT HERE IF CONTINUING AN ONGOING CONVERSATION
    // set local context variable to the context from the last response from the
    // Conversation Service
    // (see the getContext() method of the MessageResponse class in
    // com.ibm.watson.developer_cloud.conversation.v1.model)

    // async call to Tone Analyzer
    toneService.getTone(input, null).enqueue(new ServiceCallback<ToneAnalysis>() {
        @Override
        public void onResponse(ToneAnalysis toneResponsePayload) {

            // update context with the tone data returned by the Tone Analyzer
            ToneDetection.updateUserTone(context, toneResponsePayload, maintainHistory);

            // call Conversation Service with the input and tone-aware context
            MessageRequest newMessage = new MessageRequest.Builder().inputText(input).context(context).build();
            conversationService.message(workspaceId, newMessage)
                    .enqueue(new ServiceCallback<MessageResponse>() {
                        @Override
                        public void onResponse(MessageResponse response) {
                            System.out.println(response);
                        }

                        @Override
                        public void onFailure(Exception e) {
                        }
                    });
        }

        @Override
        public void onFailure(Exception e) {
        }
    });
}

From source file:es.eucm.ead.exporter.ExporterMain.java

@SuppressWarnings("all")
public static void main(String args[]) {

    Options options = new Options();

    Option help = new Option("h", "help", false, "print this message");
    Option quiet = new Option("q", "quiet", false, "be extra quiet");
    Option verbose = new Option("v", "verbose", false, "be extra verbose");

    Option legacy = OptionBuilder.withArgName("s> <t").hasArgs(3)
            .withDescription(/* ww w .j  ava2 s .  c o m*/
                    "source is a version 1.x game; must specify\n" + "<simplify> if 'true', simplifies result\n"
                            + "<translate> if 'true', enables translation")
            .withLongOpt("import").create("i");

    Option war = OptionBuilder.withArgName("web-base").hasArg()
            .withDescription("WAR packaging (web app); " + "must specify\n<web-base> the base WAR directory")
            .withLongOpt("war").create("w");

    Option jar = OptionBuilder.withDescription("JAR packaging (desktop)").withLongOpt("jar").create("j");

    Option apk = OptionBuilder.withArgName("props> <adk> <d").hasArgs(3)
            .withDescription("APK packaging (android); must specify \n" + "<props> (a properties file) \n"
                    + "<adk> (location of the ADK to use) \n" + "<deploy> ('true' to install & deploy)")
            .withLongOpt("apk").create("a");

    // EAD option
    Option ead = OptionBuilder.withDescription("EAD packaging (eAdventure)").withLongOpt("ead").create("e");

    options.addOption(legacy);
    options.addOption(help);
    options.addOption(quiet);
    options.addOption(verbose);
    options.addOption(jar);
    options.addOption(war);
    options.addOption(apk);
    options.addOption(ead);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd;
    try {
        cmd = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println("Error parsing command-line: " + pe.getMessage());
        showHelp(options);
        return;
    }

    // general options

    String[] extras = cmd.getArgs();

    if (cmd.hasOption(help.getOpt()) || extras.length < 2) {
        showHelp(options);
        return;
    }
    if (cmd.hasOption(verbose.getOpt())) {
        verbosity = Verbose;
    }
    if (cmd.hasOption(quiet.getOpt())) {
        verbosity = Quiet;
    }

    // import

    String source = extras[0];

    // optional import step
    if (cmd.hasOption(legacy.getOpt())) {
        String[] values = cmd.getOptionValues(legacy.getOpt());

        AdventureConverter converter = new AdventureConverter();
        if (values.length > 0 && values[0].equalsIgnoreCase("true")) {
            converter.setEnableSimplifications(true);
        }
        if (values.length > 1 && values[1].equalsIgnoreCase("true")) {
            converter.setEnableTranslations(true);
        }

        // set source for next steps to import-target
        source = converter.convert(source, null);
    }

    if (cmd.hasOption(jar.getOpt())) {
        if (checkFilesExist(cmd, options, source)) {
            JarExporter e = new JarExporter();
            e.export(source, extras[1], verbosity.equals(Quiet) ? new QuietStream() : System.err);
        }
    } else if (cmd.hasOption(apk.getOpt())) {
        String[] values = cmd.getOptionValues(apk.getOpt());
        if (checkFilesExist(cmd, options, values[0], values[1], source)) {
            AndroidExporter e = new AndroidExporter();
            Properties props = new Properties();
            File propsFile = new File(values[0]);
            try {
                props.load(new FileReader(propsFile));
                props.setProperty(AndroidExporter.SDK_HOME,
                        props.getProperty(AndroidExporter.SDK_HOME, values[1]));
            } catch (IOException ioe) {
                System.err.println("Could not load properties from " + propsFile.getAbsolutePath());
                return;
            }
            e.export(source, extras[1], props, values.length > 2 && values[2].equalsIgnoreCase("true"));
        }
    } else if (cmd.hasOption(war.getOpt())) {
        if (checkFilesExist(cmd, options, extras[0])) {
            WarExporter e = new WarExporter();
            e.setWarPath(cmd.getOptionValue(war.getOpt()));
            e.export(source, extras[1]);
        }
    } else if (cmd.hasOption(ead.getOpt())) {
        String destiny = extras[1];
        if (!destiny.endsWith(".ead")) {
            destiny += ".ead";
        }
        FileUtils.zip(new File(destiny), new File(source));
    } else {
        showHelp(options);
    }
}

From source file:com.alibaba.otter.manager.deployer.OtterManagerLauncher.java

public static void main(String[] args) throws Throwable {
    try {/*from  w ww.j a  v  a  2s .c om*/
        String conf = System.getProperty("otter.conf", "classpath:otter.properties");
        Properties properties = new Properties();
        if (conf.startsWith(CLASSPATH_URL_PREFIX)) {
            conf = StringUtils.substringAfter(conf, CLASSPATH_URL_PREFIX);
            properties.load(OtterManagerLauncher.class.getClassLoader().getResourceAsStream(conf));
        } else {
            properties.load(new FileInputStream(conf));
        }

        // ??system?
        mergeProps(properties);

        logger.info("## start the manager server.");
        final JettyEmbedServer server = new JettyEmbedServer(
                properties.getProperty("otter.jetty", "jetty.xml"));
        server.start();
        logger.info("## the manager server is running now ......");
        Runtime.getRuntime().addShutdownHook(new Thread() {

            public void run() {
                try {
                    logger.info("## stop the manager server");
                    server.join();
                } catch (Throwable e) {
                    logger.warn("##something goes wrong when stopping manager Server:\n{}",
                            ExceptionUtils.getFullStackTrace(e));
                } finally {
                    logger.info("## manager server is down.");
                }
            }

        });
    } catch (Throwable e) {
        logger.error("## Something goes wrong when starting up the manager Server:\n{}",
                ExceptionUtils.getFullStackTrace(e));
        System.exit(0);
    }
}