Example usage for java.util Properties Properties

List of usage examples for java.util Properties Properties

Introduction

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

Prototype

public Properties() 

Source Link

Document

Creates an empty property list with no default values.

Usage

From source file:com.wso2.rfid.Main.java

public static void main(String[] args) throws IOException {
    Properties configs = new Properties();
    configs.load(//from  ww w.  j  av a 2 s .  c o m
            new FileInputStream(System.getProperty("rpi.agent.home") + File.separator + "config.properties"));

    Server server = new Server(InetSocketAddress.createUnresolved("127.0.0.1", 8084));
    ServletHandler handler = new ServletHandler();
    server.setHandler(handler);
    handler.addServletWithMapping(RFIDReaderServlet.class, "/rfid");
    String controlCenterURL = configs.getProperty("control.center.url");
    System.out.println("Using RPi Control Center: " + controlCenterURL);
    String tokenEndpoint = configs.getProperty("token.endpoint");
    System.out.println("Using token endpoint: " + tokenEndpoint);
    APICall.setTokenEndpoint(tokenEndpoint);
    String primaryNwInterface = configs.getProperty("primary.nw.interface");
    String userRegEndpoint = configs.getProperty("user.registration.endpoint");
    System.out.println("Using user registration endpoint: " + userRegEndpoint);
    APICall.setUserRegistrationEndpoint(userRegEndpoint);
    scheduler.scheduleWithFixedDelay(new MonitoringTask(controlCenterURL, primaryNwInterface), 0, 10,
            TimeUnit.SECONDS);

    try {
        server.start();
        server.join();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.databata.engine.util.PropagatorRecreateDatabaseTool.java

public static void main(String[] args) {
    ClassLoader classLoader = PropagatorRecreateDatabaseTool.class.getClassLoader();
    InputStream resourceAsStream = classLoader.getResourceAsStream("databata.properties");
    Properties propagatorProperties = new Properties();
    try {//from   w  w w  .ja  v  a 2 s  .c o m
        propagatorProperties.load(resourceAsStream);
    } catch (FileNotFoundException e) {
        LOG.error("Sepecified file 'databata.properties' not found");
    } catch (IOException e) {
        LOG.error("Sepecified file 'databata.properties' cannot be loaded");
    }

    SingleConnectionDataSource dataSource = new SingleConnectionDataSource();
    dataSource.setDriverClassName(propagatorProperties.getProperty("db.propagation.driver"));
    dataSource.setUrl(propagatorProperties.getProperty("db.propagation.dba.connection-url"));
    dataSource.setUsername(propagatorProperties.getProperty("db.propagation.dba.user"));
    dataSource.setPassword(propagatorProperties.getProperty("db.propagation.dba.password"));
    dataSource.setSuppressClose(true);

    String databaseName = "undefined";
    try {
        databaseName = dataSource.getConnection().getMetaData().getDatabaseProductName();
    } catch (SQLException e) {
        LOG.error("Cannot get connection by specified url", e);
    }
    String databaseCode = PropagationUtils.getDatabaseCode(databaseName);
    LOG.info("Database with code '" + databaseCode + "' is identified.");

    String submitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.sql";
    String fileContent = "";
    try {
        fileContent = getFileContent(classLoader, submitFileName);
    } catch (IOException e) {
        LOG.info("File with name '" + submitFileName
                + "' cannot be read from classpath. Trying to load default submit file.");
    }
    if (fileContent == null || "".equals(fileContent)) {
        String defaultSubmitFileName = "META-INF/databata/" + databaseCode + "_recreate_database.default.sql";
        try {
            fileContent = getFileContent(classLoader, defaultSubmitFileName);
        } catch (IOException e) {
            LOG.info("File with name '" + defaultSubmitFileName
                    + "' cannot be read from classpath. Trying to load default submit file.");
        }
    }

    if (fileContent == null) {
        LOG.info("File content is empty. Stopping process.");
        return;
    }

    fileContent = replacePlaceholders(fileContent, propagatorProperties);

    SqlFile sqlFile = null;
    try {
        sqlFile = new SqlFile(fileContent, null, submitFileName, new SqlExecutionCallback() {

            @Override
            public void handleExecuteSuccess(String sql, int arg1, double arg2) {
                LOG.info("Sql is sucessfully executed \n ======== \n" + sql + "\n ======== \n");
            }

            @Override
            public void handleException(SQLException arg0, String sql) throws SQLException {
                LOG.info("Sql returned error \n ======== \n" + sql + "\n ======== \n");
            }
        }, null);
    } catch (IOException e) {
        LOG.error("Error when initializing SqlTool", e);
    }
    try {
        sqlFile.setConnection(dataSource.getConnection());
    } catch (SQLException e) {
        LOG.error("Error is occured when setting connection", e);
    }

    try {
        sqlFile.execute();
    } catch (SqlToolError e) {
        LOG.error("Error when creating user", e);
    } catch (SQLException e) {
        LOG.error("Error when creating user", e);
    }
}

From source file:com.github.fhuss.kafka.streams.cep.demo.CEPStockKStreamsDemo.java

public static void main(String[] args) {

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-cep");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, StockEventSerDe.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, StockEventSerDe.class);

    // setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    // build query
    final Pattern<Object, StockEvent> pattern = new QueryBuilder<Object, StockEvent>().select()
            .where((k, v, ts, store) -> v.volume > 1000).<Long>fold("avg", (k, v, curr) -> v.price).then()
            .select().zeroOrMore().skipTillNextMatch()
            .where((k, v, ts, state) -> v.price > (long) state.get("avg"))
            .<Long>fold("avg", (k, v, curr) -> (curr + v.price) / 2)
            .<Long>fold("volume", (k, v, curr) -> v.volume).then().select().skipTillNextMatch()
            .where((k, v, ts, state) -> v.volume < 0.8 * state.getOrElse("volume", 0L))
            .within(1, TimeUnit.HOURS).build();

    KStreamBuilder builder = new KStreamBuilder();

    CEPStream<Object, StockEvent> stream = new CEPStream<>(builder.stream("StockEvents"));

    KStream<Object, Sequence<Object, StockEvent>> stocks = stream.query("Stocks", pattern);

    stocks.mapValues(seq -> {//  w w  w . j a v a  2 s . c o m
        JSONObject json = new JSONObject();
        seq.asMap().forEach((k, v) -> {
            JSONArray events = new JSONArray();
            json.put(k, events);
            List<String> collect = v.stream().map(e -> e.value.name).collect(Collectors.toList());
            Collections.reverse(collect);
            collect.forEach(e -> events.add(e));
        });
        return json.toJSONString();
    }).through(null, Serdes.String(), "Matches").print();

    //Use the topologyBuilder and streamingConfig to start the kafka streams process
    KafkaStreams streaming = new KafkaStreams(builder, props);
    //streaming.cleanUp();
    streaming.start();
}

From source file:com.sun.labs.aura.grid.ec2.Ec2Sample.java

public static void main(String[] args) throws Exception {
    Properties props = new Properties();
    props.load(Ec2Sample.class.getResourceAsStream("aws.properties"));
    Jec2 ec2 = new Jec2(props.getProperty("aws.accessId"), props.getProperty("aws.secretKey"));

    List<String> params = new ArrayList<String>();
    List<ImageDescription> images = ec2.describeImages(params);
    System.out.println(String.format("%d available images", images.size()));
    for (ImageDescription img : images) {
        if (img.getImageState().equals("available")) {
            System.out.println(img.getImageId() + "\t" + img.getImageLocation() + "\t" + img.getImageOwnerId());
        }// www.j a  va  2s.c  o  m
    }

    // describe instances
    params = new ArrayList<String>();
    List<ReservationDescription> instances = ec2.describeInstances(params);
    System.out.println(String.format("%d instances", instances.size()));
    String instanceId = null;
    for (ReservationDescription res : instances) {
        System.out.println(res.getOwner() + "\t" + res.getReservationId());
        if (res.getInstances() != null) {
            for (Instance inst : res.getInstances()) {
                System.out.println("\t" + inst.getImageId() + "\t" + inst.getDnsName() + "\t" + inst.getState()
                        + "\t" + inst.getKeyName());
                instanceId = inst.getInstanceId();
            }
        }
    }

    // test console output
    if (instanceId != null) {
        ConsoleOutput consOutput = ec2.getConsoleOutput(instanceId);
        System.out.println("Console Output:");
        System.out.println(consOutput.getOutput());
    }

    // show keypairs
    List<KeyPairInfo> info = ec2.describeKeyPairs(new String[] {});
    System.out.println("keypair list");
    for (KeyPairInfo i : info) {
        System.out.println("keypair : " + i.getKeyName() + ", " + i.getKeyFingerprint());
    }
}

From source file:com.openx.oauthdemo.Demo.java

/** 
 * Main class. OX3 with OAuth demo/*w ww . j  a v a2 s  .  c  o m*/
 * @param args 
 */
public static void main(String[] args) {
    String apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl, accessTokenUrl,
            realm, authorizeUrl;
    String propertiesFile = "default.properties";

    // load params from the properties file
    Properties defaultProps = new Properties();
    InputStream in = null;
    try {
        ClassLoader cl = ClassLoader.getSystemClassLoader();
        in = cl.getResourceAsStream(propertiesFile);
        if (in != null) {
            defaultProps.load(in);
        }
    } catch (IOException ex) {
        System.out.println("The properties file was not found!");
        return;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                System.out.println("IO Error closing the properties file");
                return;
            }
        }
    }

    if (defaultProps.isEmpty()) {
        System.out.println("The properties file was not loaded!");
        return;
    }

    apiKey = defaultProps.getProperty("apiKey");
    apiSecret = defaultProps.getProperty("apiSecret");
    loginUrl = defaultProps.getProperty("loginUrl");
    username = defaultProps.getProperty("username");
    password = defaultProps.getProperty("password");
    domain = defaultProps.getProperty("domain");
    path = defaultProps.getProperty("path");
    requestTokenUrl = defaultProps.getProperty("requestTokenUrl");
    accessTokenUrl = defaultProps.getProperty("accessTokenUrl");
    realm = defaultProps.getProperty("realm");
    authorizeUrl = defaultProps.getProperty("authorizeUrl");

    // log in to the server
    Client cl = new Client(apiKey, apiSecret, loginUrl, username, password, domain, path, requestTokenUrl,
            accessTokenUrl, realm, authorizeUrl);
    try {
        // connect to the server
        cl.OX3OAuth();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "UTF-8 support needed for OAuth", ex);
    } catch (IOException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "IO file reading error", ex);
    } catch (Exception ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, "API issue", ex);
    }

    // now lets make a call to the api to check 
    String json;
    try {
        json = cl.getHelper().callOX3Api(domain, path, "account");
    } catch (IOException ex) {
        System.out.println("There was an error calling the API");
        return;
    }

    System.out.println("JSON response: " + json);

    Gson gson = new Gson();
    int[] accounts = gson.fromJson(json, int[].class);

    if (accounts.length > 0) {
        // let's get a single account
        try {
            json = cl.getHelper().callOX3Api(domain, path, "account", accounts[0]);
        } catch (IOException ex) {
            System.out.println("There was an error calling the API");
            return;
        }

        System.out.println("JSON response: " + json);

        OX3Account account = gson.fromJson(json, OX3Account.class);

        System.out.println("Account id: " + account.getId() + " name: " + account.getName());
    }
}

From source file:com.ipcglobal.awscdh.config.ManageCluster.java

/**
 * The main method./*from ww w.  j  av a 2s .c  o m*/
 *
 * @param args the arguments
 * @throws Exception the exception
 */
public static void main(String[] args) throws Exception {
    try {
        long before = System.currentTimeMillis();
        LogTool.initConsole();
        if (args.length <= 1)
            throw new Exception(
                    "Action and Properties file name are required parameter - format: start|stop example.properties");
        String action = args[0];
        log.info("Begin: action=" + action);
        Properties properties = new Properties();
        properties.load(new FileInputStream(args[1]));
        ManageEc2 manageEc2 = new ManageEc2(properties);
        ManageCdh manageCdh = new ManageCdh(properties);

        if ("start".equals(action)) {
            manageEc2.start();
            manageCdh.start();
        } else if ("stop".equals(action)) {
            manageCdh.stop();
            manageEc2.stop();
        } else
            throw new Exception("Invalid action: " + action + ", must be start or stop");

        log.info("Complete: action=" + action + ", elapsed "
                + Utils.convertMSecsToHMmSs(System.currentTimeMillis() - before));

    } catch (Exception e) {
        log.error(e);
        e.printStackTrace();
    }
}

From source file:com.mobius.software.mqtt.performance.controller.ControllerRunner.java

public static void main(String[] args) {
    try {/*from   w w w.  j  a v  a2  s.c o  m*/
        /*URI baseURI = URI.create(args[0].replace("-baseURI=", ""));
        configFile = args[1].replace("-configFile=", "");*/
        String userDir = System.getProperty("user.dir");
        System.out.println("user.dir: " + userDir);
        setConfigFilePath(userDir + "/config.properties");
        Properties prop = new Properties();
        prop.load(new FileInputStream(configFile));
        System.out.println("properties loaded...");

        String hostname = prop.getProperty("hostname");
        Integer port = Integer.parseInt(prop.getProperty("port"));
        URI baseURI = new URI(null, null, hostname, port, null, null, null);

        configureConsoleLogger();
        System.out.println("starting http server...");
        JerseyServer server = new JerseyServer(baseURI);
        System.out.println("http server started");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("press any key to stop: ");
        br.readLine();
        server.terminate();
    } catch (Throwable e) {
        logger.error("AN ERROR OCCURED: " + e.getMessage());
        e.printStackTrace();
    } finally {
        System.exit(0);
    }
}

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 {//ww  w  .ja v  a 2  s . com
        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:cht.Parser.java

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

    // TODO get from google drive
    boolean isUnicode = false;
    boolean isRemoveInputFileOnComplete = false;
    int rowNum;/*from  w  ww. j a va2 s  . c  om*/
    int colNum;
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Properties prop = new Properties();

    try {
        prop.load(new FileInputStream("config.txt"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    String inputFilePath = prop.getProperty("inputFile");
    String outputDirectory = prop.getProperty("outputDirectory");
    System.out.println(outputDirectory);
    // optional
    String unicode = prop.getProperty("unicode");
    String removeInputFileOnComplete = prop.getProperty("removeInputFileOnComplete");

    inputFilePath = inputFilePath.trim();
    outputDirectory = outputDirectory.trim();

    if (unicode != null) {
        isUnicode = Boolean.parseBoolean(unicode.trim());
    }
    if (removeInputFileOnComplete != null) {
        isRemoveInputFileOnComplete = Boolean.parseBoolean(removeInputFileOnComplete.trim());
    }

    Writer out = null;
    FileInputStream in = null;
    final String newLine = System.getProperty("line.separator").toString();
    final String separator = File.separator;
    try {
        in = new FileInputStream(inputFilePath);

        Workbook workbook = new XSSFWorkbook(in);

        Sheet sheet = workbook.getSheetAt(0);

        rowNum = sheet.getLastRowNum() + 1;
        colNum = sheet.getRow(0).getPhysicalNumberOfCells();

        for (int j = 1; j < colNum; ++j) {
            String outputFilename = sheet.getRow(0).getCell(j).getStringCellValue();
            // guess directory
            int slash = outputFilename.indexOf('/');
            if (slash != -1) { // has directory
                outputFilename = outputFilename.substring(0, slash) + separator
                        + outputFilename.substring(slash + 1);
            }

            String outputPath = FilenameUtils.concat(outputDirectory, outputFilename);
            System.out.println("--Writing " + outputPath);
            out = new OutputStreamWriter(new FileOutputStream(outputPath), "UTF-8");
            TreeMap<String, Object> map = new TreeMap<String, Object>();
            for (int i = 1; i < rowNum; i++) {
                try {
                    String key = sheet.getRow(i).getCell(0).getStringCellValue();
                    //String value = "";
                    Cell tmp = sheet.getRow(i).getCell(j);
                    if (tmp != null) {
                        // not empty string!
                        value = sheet.getRow(i).getCell(j).getStringCellValue();
                    }
                    if (!key.equals("") && !key.startsWith("#") && !key.startsWith(".")) {
                        value = isUnicode ? StringEscapeUtils.escapeJava(value) : value;

                        int firstdot = key.indexOf(".");
                        String keyName, keyAttribute;
                        if (firstdot > 0) {// a.b.c.d 
                            keyName = key.substring(0, firstdot); // a
                            keyAttribute = key.substring(firstdot + 1); // b.c.d
                            TreeMap oldhash = null;
                            Object old = null;
                            if (map.get(keyName) != null) {
                                old = map.get(keyName);
                                if (old instanceof TreeMap == false) {
                                    System.out.println("different type of key:" + key);
                                    continue;
                                }
                                oldhash = (TreeMap) old;
                            } else {
                                oldhash = new TreeMap();
                            }

                            int firstdot2 = keyAttribute.indexOf(".");
                            String rootName, childName;
                            if (firstdot2 > 0) {// c, d.f --> d, f
                                rootName = keyAttribute.substring(0, firstdot2);
                                childName = keyAttribute.substring(firstdot2 + 1);
                            } else {// c, d  -> d, null
                                rootName = keyAttribute;
                                childName = null;
                            }

                            TreeMap<String, Object> object = myPut(oldhash, rootName, childName);
                            map.put(keyName, object);

                        } else {// c, d  -> d, null
                            keyName = key;
                            keyAttribute = null;
                            // simple string mode
                            map.put(key, value);
                        }

                    }

                } catch (Exception e) {
                    // just ingore empty rows
                }

            }
            String json = gson.toJson(map);
            // output json
            out.write(json + newLine);
            out.close();
        }
        in.close();

        System.out.println("\n---Complete!---");
        System.out.println("Read input file from " + inputFilePath);
        System.out.println(colNum - 1 + " output files ate generated at " + outputDirectory);
        System.out.println(rowNum + " records are generated for each output file.");
        System.out.println("output file is ecoded as unicode? " + (isUnicode ? "yes" : "no"));
        if (isRemoveInputFileOnComplete) {
            File input = new File(inputFilePath);
            input.deleteOnExit();
            System.out.println("Deleted " + inputFilePath);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            in.close();
        }
    }

}

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 w w.j  a  v  a  2  s . c o m
}