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) 

Source Link

Document

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

Usage

From source file:com.imolinfo.offline.CrossFoldValidation.java

public static void main(String[] args)
        throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {

    Properties p = new Properties();
    p.load(new FileInputStream("runtime.properties"));
    GlobalVariable.getInstance().setProperties(p);
    String classificatorName = Class.forName(p.getProperty("ClassificationModel")).newInstance().toString();

    SparkConf conf = new SparkConf().setAppName("CrossFoldValidation: " + classificatorName);
    final JavaSparkContext jsc = new JavaSparkContext(conf);

    invokePipeline(jsc);//from w  ww.j a  v  a  2  s  .  com
}

From source file:com.vikram.kdtree.ElementalHttpServer.java

public static void main(String[] args) throws Exception {
    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();/*from w  w w.ja  va2 s . c o m*/

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpPostReceiver());

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    Properties properties = new Properties();
    properties.load(new FileInputStream("Config.properties"));

    Thread t = new RequestListenerThread(Integer.valueOf(properties.getProperty("requestPort")), httpService,
            null);
    t.setDaemon(false);
    t.start();
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }/* www  .j  a  v  a  2s.  c  om*/
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:mcnutty.music.get.MusicGet.java

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

    //print out music-get
    System.out.println("                     _                      _   ");
    System.out.println(" _ __ ___  _   _ ___(_) ___       __ _  ___| |_ ");
    System.out.println("| '_ ` _ \\| | | / __| |/ __|____ / _` |/ _ \\ __|");
    System.out.println("| | | | | | |_| \\__ \\ | (_|_____| (_| |  __/ |_ ");
    System.out.println("|_| |_| |_|\\__,_|___/_|\\___|     \\__, |\\___|\\__|");
    System.out.println("                                 |___/          \n");

    //these will always be initialised later (but the compiler doesn't know that)
    String directory = "";
    Properties prop = new Properties();

    try (InputStream input = new FileInputStream("config.properties")) {
        prop.load(input);/*w  w  w  .  j a  v  a  2s  . c  o  m*/
        if (prop.getProperty("directory") != null) {
            directory = prop.getProperty("directory");
        } else {
            System.out.println(
                    "Error reading config property 'directory' - using default value of /tmp/musicserver/\n");
            directory = "/tmp/musicserver/";
        }
        if (prop.getProperty("password") == null) {
            System.out.println("Error reading config property 'password' - no default value, exiting\n");
            System.exit(1);
        }
    } catch (IOException e) {
        System.out.println("Error reading config file");
        System.exit(1);
    }

    //create a queue object
    ProcessQueue process_queue = new ProcessQueue();

    try {
        if (args.length > 0 && args[0].equals("clean")) {
            Files.delete(Paths.get("queue.json"));
        }
        //load an existing queue if possible
        String raw_queue = Files.readAllLines(Paths.get("queue.json")).toString();
        JSONArray queue_state = new JSONArray(raw_queue);
        ConcurrentLinkedQueue<QueueItem> loaded_queue = new ConcurrentLinkedQueue<>();
        JSONArray queue = queue_state.getJSONArray(0);
        for (int i = 0; i < queue.length(); i++) {
            JSONObject item = ((JSONObject) queue.get(i));
            QueueItem loaded_item = new QueueItem();
            loaded_item.ip = item.getString("ip");
            loaded_item.real_name = item.getString("name");
            loaded_item.disk_name = item.getString("guid");
            loaded_queue.add(loaded_item);
        }
        process_queue.bucket_queue = loaded_queue;
        System.out.println("Loaded queue from disk\n");
    } catch (Exception ex) {
        //otherwise clean out the music directory and start a new queue
        try {
            Files.walkFileTree(Paths.get(directory), new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    Files.delete(file);
                    return FileVisitResult.CONTINUE;
                }
            });
            Files.delete(Paths.get(directory));
        } catch (Exception e) {
            e.printStackTrace();
        }
        Files.createDirectory(Paths.get(directory));
        System.out.println("Created a new queue\n");
    }

    //start the web server
    StartServer start_server = new StartServer(process_queue, directory);
    new Thread(start_server).start();

    //wit for the web server to spool up
    Thread.sleep(1000);

    //read items from the queue and play them
    while (true) {
        QueueItem next_item = process_queue.next_item();
        if (!next_item.equals(new QueueItem())) {
            //Check the timeout
            int timeout = 547;
            try (FileInputStream input = new FileInputStream("config.properties")) {
                prop.load(input);
                timeout = Integer.parseInt(prop.getProperty("timeout", "547"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("Playing " + next_item.real_name);
            process_queue.set_played(next_item);
            process_queue.save_queue();
            Process p = Runtime.getRuntime().exec("timeout " + timeout
                    + "s mplayer -fs -quiet -af volnorm=2:0.25 " + directory + next_item.disk_name);

            try {
                p.waitFor(timeout, TimeUnit.SECONDS);
                Files.delete(Paths.get(directory + next_item.disk_name));
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            process_queue.bucket_played.clear();
        }
        Thread.sleep(1000);
    }
}

From source file:uk.ac.kcl.Main.java

public static void main(String[] args) {
    File folder = new File(args[0]);
    File[] listOfFiles = folder.listFiles();
    assert listOfFiles != null;
    for (File listOfFile : listOfFiles) {
        if (listOfFile.isFile()) {
            if (listOfFile.getName().endsWith(".properties")) {
                System.out.println("Properties sile found:" + listOfFile.getName()
                        + ". Attempting to launch application context");
                Properties properties = new Properties();
                InputStream input;
                try {
                    input = new FileInputStream(listOfFile);
                    properties.load(input);
                    if (properties.getProperty("globalSocketTimeout") != null) {
                        TcpHelper.setSocketTimeout(
                                Integer.valueOf(properties.getProperty("globalSocketTimeout")));
                    }//w w  w .j a v  a  2  s . c  o m
                    Map<String, Object> map = new HashMap<>();
                    properties.forEach((k, v) -> {
                        map.put(k.toString(), v);
                    });
                    ConfigurableEnvironment environment = new StandardEnvironment();
                    MutablePropertySources propertySources = environment.getPropertySources();
                    propertySources.addFirst(new MapPropertySource(listOfFile.getName(), map));
                    @SuppressWarnings("resource")
                    AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
                    ctx.registerShutdownHook();
                    ctx.setEnvironment(environment);
                    String scheduling;
                    try {
                        scheduling = properties.getProperty("scheduler.useScheduling");
                        if (scheduling.equalsIgnoreCase("true")) {
                            ctx.register(ScheduledJobLauncher.class);
                            ctx.refresh();
                        } else if (scheduling.equalsIgnoreCase("false")) {
                            ctx.register(SingleJobLauncher.class);
                            ctx.refresh();
                            SingleJobLauncher launcher = ctx.getBean(SingleJobLauncher.class);
                            launcher.launchJob();
                        } else if (scheduling.equalsIgnoreCase("slave")) {
                            ctx.register(JobConfiguration.class);
                            ctx.refresh();
                        } else {
                            throw new RuntimeException(
                                    "useScheduling not configured. Must be true, false or slave");
                        }
                    } catch (NullPointerException ex) {
                        throw new RuntimeException(
                                "useScheduling not configured. Must be true, false or slave");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:example.ConfigurationsExample.java

public static void main(String[] args) {
    String jdbcPropToLoad = "prod.properties";
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("d", "dev", false,
            "Dev tag to launch app in dev mode. Means that app will launch embedded mckoi db.");
    try {//from  ww w. j a  v a 2s.  co m
        CommandLine line = parser.parse(options, args);
        if (line.hasOption("d")) {
            System.err.println("App is in DEV mode");
            jdbcPropToLoad = "dev.properties";
        }
    } catch (ParseException exp) {
        System.err.println("Parsing failed.  Reason: " + exp.getMessage());
    }
    Properties p = new Properties();
    try {
        p.load(ConfigurationsExample.class.getResourceAsStream("/" + jdbcPropToLoad));
    } catch (IOException e) {
        System.err.println("Properties loading failed.  Reason: " + e.getMessage());
    }
    try {
        String clazz = p.getProperty("driver.class");
        Class.forName(clazz);
        System.out.println(" Jdbc driver loaded :" + clazz);
    } catch (ClassNotFoundException e) {
        System.err.println("Jdbc Driver class loading failed.  Reason: " + e.getMessage());
        e.printStackTrace();
    }

}

From source file:azkaban.jobtype.HadoopSecureHiveWrapper.java

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

    String propsFile = System.getenv(ProcessJob.JOB_PROP_ENV);
    Properties prop = new Properties();
    prop.load(new BufferedReader(new FileReader(propsFile)));

    hiveScript = prop.getProperty("hive.script");

    final Configuration conf = new Configuration();

    UserGroupInformation.setConfiguration(conf);
    securityEnabled = UserGroupInformation.isSecurityEnabled();

    if (shouldProxy(prop)) {
        UserGroupInformation proxyUser = null;
        String userToProxy = prop.getProperty("user.to.proxy");
        if (securityEnabled) {
            String filelocation = System.getenv(UserGroupInformation.HADOOP_TOKEN_FILE_LOCATION);
            if (filelocation == null) {
                throw new RuntimeException("hadoop token information not set.");
            }//ww w . j  a  va 2  s .  co m
            if (!new File(filelocation).exists()) {
                throw new RuntimeException("hadoop token file doesn't exist.");
            }

            logger.info("Found token file " + filelocation);

            logger.info("Setting " + HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY + " to "
                    + filelocation);
            System.setProperty(HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY, filelocation);

            UserGroupInformation loginUser = null;

            loginUser = UserGroupInformation.getLoginUser();
            logger.info("Current logged in user is " + loginUser.getUserName());

            logger.info("Creating proxy user.");
            proxyUser = UserGroupInformation.createProxyUser(userToProxy, loginUser);

            for (Token<?> token : loginUser.getTokens()) {
                proxyUser.addToken(token);
            }
        } else {
            proxyUser = UserGroupInformation.createRemoteUser(userToProxy);
        }

        logger.info("Proxied as user " + userToProxy);

        proxyUser.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                runHive(args);
                return null;
            }
        });

    } else {
        logger.info("Not proxying. ");
        runHive(args);
    }
}

From source file:com.welocalize.dispatcherMW.client.Main.java

public static void main(String[] args) throws InterruptedException, IOException {
    if (args.length >= 3) {
        String type = args[0];/*from   w w  w.j a  v a  2 s  .  c  o  m*/
        if (TYPE_TRANSLATE.equalsIgnoreCase(type)) {
            setbasicURl(args[1]);
            doJob(args[2], args[3]);
            return;
        } else if (TYPE_CHECK_STATUS.equalsIgnoreCase(type)) {
            setbasicURl(args[1]);
            checkJobStaus(args[2]);
            return;
        } else if (TYPE_DOWNLOAD.equalsIgnoreCase(type)) {
            setbasicURl(args[1]);
            downloadJob(args[2], args[3]);
            return;
        }
    } else if (args.length == 1) {
        Properties properties = new Properties();
        properties.load(new FileInputStream(args[0]));
        String type = properties.getProperty("type");
        setbasicURl(properties.getProperty("URL"));
        String securityCode = properties.getProperty(JSONPN_SECURITY_CODE);
        String filePath = properties.getProperty("filePath");
        String jobID = properties.getProperty(JSONPN_JOBID);
        if (TYPE_TRANSLATE.equalsIgnoreCase(type)) {
            doJob(securityCode, filePath);
            return;
        } else if (TYPE_CHECK_STATUS.equalsIgnoreCase(type)) {
            String status = checkJobStaus(jobID);
            System.out.println("The Status of Job:" + jobID + " is " + status + ". ");
            return;
        } else if (TYPE_DOWNLOAD.equalsIgnoreCase(type)) {
            downloadJob(jobID, securityCode);
            System.out.println("Download Job:" + jobID);
            return;
        }
    }

    // Print Help Message
    StringBuffer msg = new StringBuffer();
    msg.append("The Input is incorrect.").append("\n");
    msg.append("If you want to translate the XLF file, use this command:").append("\n");
    msg.append(" translate $URL $securityCode $filePath").append("\n");
    msg.append("If you only want to check job status, use this command:").append("\n");
    msg.append(" checkStatus $URL $jobID").append("\n");
    msg.append("If you only want to download the job file, use this command:").append("\n");
    msg.append(" download $URL $jobID $securityCode").append("\n");
    System.out.println(msg.toString());
}

From source file:net.ontopia.persistence.rdbms.DDLExecuter.java

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

    // Initialize logging
    CmdlineUtils.initializeLogging();/*from w  w w  . j  av  a 2s . c  o m*/

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("DDLExecuter", argv);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 2) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String schema = args[0];
    String dbprops = args[1];
    String action = args[2];

    if (!("create".equals(action) || "drop".equals(action) || "recreate".equals(action))) {
        System.err.println("Error: unknown action: " + action);
        usage();
        System.exit(1);
    }

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Get database properties from property file
    String[] platforms = StringUtils.split(props.getProperty("net.ontopia.topicmaps.impl.rdbms.Platforms"),
            ",");

    Project project = DatabaseProjectReader.loadProject(schema);

    //! //! if (dbtype.equals("generic"))
    //! //!   producer = new GenericSQLProducer(project, StringUtils.split(dbtype, ","));
    //! //! else
    //! if (dbtype.equals("mysql"))
    //!   producer = new MySqlSQLProducer(project);
    //! else if (dbtype.equals("oracle"))
    //!   producer = new OracleSQLProducer(project);
    //! else {
    //!   producer = new GenericSQLProducer(project, StringUtils.split(dbtype, ","));
    //!   //! System.err.println("Error: unknown database type: " + dbtype);
    //!   //! usage();
    //!   //! System.exit(1);
    //! }

    // Create SQL producer
    GenericSQLProducer producer = getSQLProducer(project, platforms);
    log.debug("Using SQL producer: " + producer);

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false);
    Connection conn = cfactory.requestConnection();

    // Execute statements
    try {
        if ("create".equals(action))
            producer.executeCreate(conn);
        else if ("drop".equals(action))
            producer.executeDrop(conn);
        else if ("recreate".equals(action)) {
            producer.executeDrop(conn);
            producer.executeCreate(conn);
        }
        conn.commit();
    } finally {
        if (conn != null)
            conn.close();
    }
}

From source file:PropDemo.java

public static void main(String args[]) {
    Properties capitals = new Properties();

    capitals.put("Illinois", "Springfield");
    capitals.put("Missouri", "Jefferson City");
    capitals.put("Washington", "Olympia");
    capitals.put("California", "Sacramento");
    capitals.put("Indiana", "Indianapolis");

    Set states = capitals.keySet();

    for (Object name : states)
        System.out.println(name + " / " + capitals.getProperty((String) name));

    String str = capitals.getProperty("Florida", "Not Found");
    System.out.println("The capital of Florida is " + str + ".");
}