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.github.jcustenborder.kafka.connect.spooldir.SchemaGenerator.java

public static void main(String... args) throws Exception {
    ArgumentParser parser = ArgumentParsers.newArgumentParser("CsvSchemaGenerator").defaultHelp(true)
            .description("Generate a schema based on a file.");
    parser.addArgument("-t", "--type").required(true).choices("csv", "json")
            .help("The type of generator to use.");
    parser.addArgument("-c", "--config").type(File.class);
    parser.addArgument("-f", "--file").type(File.class).required(true)
            .help("The data file to generate the schema from.");
    parser.addArgument("-i", "--id").nargs("*").help("Field(s) to use as an identifier.");
    parser.addArgument("-o", "--output").type(File.class)
            .help("Output location to write the configuration to. Stdout is default.");

    Namespace ns = null;/*from www. j a v a 2 s  . c o  m*/

    try {
        ns = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
        parser.handleError(ex);
        System.exit(1);
    }

    File inputFile = ns.get("file");
    List<String> ids = ns.getList("id");
    if (null == ids) {
        ids = ImmutableList.of();
    }

    Map<String, Object> settings = new LinkedHashMap<>();

    File inputPropertiesFile = ns.get("config");
    if (null != inputPropertiesFile) {
        Properties inputProperties = new Properties();

        try (FileInputStream inputStream = new FileInputStream(inputPropertiesFile)) {
            inputProperties.load(inputStream);
        }
        for (String s : inputProperties.stringPropertyNames()) {
            Object v = inputProperties.getProperty(s);
            settings.put(s, v);
        }
    }

    final SchemaGenerator generator;
    final String type = ns.getString("type");

    if ("csv".equalsIgnoreCase(type)) {
        generator = new CsvSchemaGenerator(settings);
    } else if ("json".equalsIgnoreCase(type)) {
        generator = new JsonSchemaGenerator(settings);
    } else {
        throw new UnsupportedOperationException(
                String.format("'%s' is not a supported schema generator type", type));
    }

    Map.Entry<Schema, Schema> kvp = generator.generate(inputFile, ids);

    Properties properties = new Properties();
    properties.putAll(settings);
    properties.setProperty(SpoolDirSourceConnectorConfig.KEY_SCHEMA_CONF,
            ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getKey()));
    properties.setProperty(SpoolDirSourceConnectorConfig.VALUE_SCHEMA_CONF,
            ObjectMapperFactory.INSTANCE.writeValueAsString(kvp.getValue()));

    String output = ns.getString("output");
    final String comment = "Configuration was dynamically generated. Please verify before submitting.";

    if (Strings.isNullOrEmpty(output)) {
        properties.store(System.out, comment);
    } else {
        try (FileOutputStream outputStream = new FileOutputStream(output)) {
            properties.store(outputStream, comment);
        }
    }
}

From source file:com.mockey.runner.JettyRunner.java

public static void main(String[] args) throws Exception {
    if (args == null)
        args = new String[0];

    // Initialize the argument parser
    SimpleJSAP jsap = new SimpleJSAP("java -jar Mockey.jar", "Starts a Jetty server running Mockey");
    jsap.registerParameter(new FlaggedOption(ARG_PORT, JSAP.INTEGER_PARSER, "8080", JSAP.NOT_REQUIRED, 'p',
            ARG_PORT, "port to run Jetty on"));
    jsap.registerParameter(new FlaggedOption(BSC.FILE, JSAP.STRING_PARSER,
            MockeyXmlFileManager.MOCK_SERVICE_DEFINITION, JSAP.NOT_REQUIRED, 'f', BSC.FILE,
            "Relative path to a mockey-definitions file to initialize Mockey, relative to where you're starting Mockey"));

    jsap.registerParameter(new FlaggedOption(BSC.URL, JSAP.STRING_PARSER, "", JSAP.NOT_REQUIRED, 'u', BSC.URL,
            "URL to a mockey-definitions file to initialize Mockey"));

    jsap.registerParameter(new FlaggedOption(BSC.TRANSIENT, JSAP.BOOLEAN_PARSER, "true", JSAP.NOT_REQUIRED, 't',
            BSC.TRANSIENT, "Read only mode if set to true, no updates are made to the file system."));

    jsap.registerParameter(new FlaggedOption(BSC.FILTERTAG, JSAP.STRING_PARSER, "", JSAP.NOT_REQUIRED, 'F',
            BSC.FILTERTAG,/*  ww w .  j  a  v a  2  s  .c  o m*/
            "Filter tag for services and scenarios, useful for 'only use information with this tag'. "));
    jsap.registerParameter(
            new Switch(ARG_QUIET, 'q', "quiet", "Runs in quiet mode and does not loads the browser"));

    jsap.registerParameter(new FlaggedOption(BSC.HEADLESS, JSAP.BOOLEAN_PARSER, "false", JSAP.NOT_REQUIRED, 'H',
            BSC.HEADLESS,
            "Headless flag. Default is 'false'. Set to 'true' if you do not want Mockey to spawn a browser thread upon startup."));

    // parse the command line options
    JSAPResult config = jsap.parse(args);

    // Bail out if they asked for the --help
    if (jsap.messagePrinted()) {
        System.exit(1);
    }

    // Construct the new arguments for jetty-runner
    int port = config.getInt(ARG_PORT);
    boolean transientState = true;
    // We can add more things to the quite mode. For now we are just not launching browser
    boolean isQuiteMode = false;

    try {
        transientState = config.getBoolean(BSC.TRANSIENT);
        isQuiteMode = config.getBoolean(ARG_QUIET);
    } catch (Exception e) {
        //
    }

    // Initialize Log4J file roller appender.
    StartUpServlet.getDebugFile();
    InputStream log4jInputStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("WEB-INF/log4j.properties");
    Properties log4JProperties = new Properties();
    log4JProperties.load(log4jInputStream);
    PropertyConfigurator.configure(log4JProperties);

    Server server = new Server(port);

    WebAppContext webapp = new WebAppContext();
    webapp.setContextPath("/");
    webapp.setConfigurations(new Configuration[] { new PreCompiledJspConfiguration() });

    ClassPathResourceHandler resourceHandler = new ClassPathResourceHandler();
    resourceHandler.setContextPath("/");

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.addHandler(resourceHandler);

    contexts.addHandler(webapp);

    server.setHandler(contexts);

    server.start();
    // Construct the arguments for Mockey
    String file = String.valueOf(config.getString(BSC.FILE));
    String url = String.valueOf(config.getString(BSC.URL));
    String filterTag = config.getString(BSC.FILTERTAG);
    String fTagParam = "";
    boolean headless = config.getBoolean(BSC.HEADLESS);
    if (filterTag != null) {
        fTagParam = "&" + BSC.FILTERTAG + "=" + URLEncoder.encode(filterTag, "UTF-8");
    }

    // Startup displays a big message and URL redirects after x seconds.
    // Snazzy.
    String initUrl = HOMEURL;
    // BUT...if a file is defined, (which it *should*),
    // then let's initialize with it instead.
    if (url != null && url.trim().length() > 0) {
        URLEncoder.encode(initUrl, "UTF-8");
        initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&"
                + BSC.URL + "=" + URLEncoder.encode(url, "UTF-8") + fTagParam;
    } else if (file != null && file.trim().length() > 0) {
        URLEncoder.encode(initUrl, "UTF-8");
        initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&"
                + BSC.FILE + "=" + URLEncoder.encode(file, "UTF-8") + fTagParam;
    } else {
        initUrl = HOMEURL + "?" + BSC.ACTION + "=" + BSC.INIT + "&" + BSC.TRANSIENT + "=" + transientState + "&"
                + BSC.FILE + "=" + URLEncoder.encode(MockeyXmlFileManager.MOCK_SERVICE_DEFINITION, "UTF-8")
                + fTagParam;

    }

    if (!(headless || isQuiteMode)) {
        new Thread(new BrowserThread("http://127.0.0.1", String.valueOf(port), initUrl, 0)).start();
        server.join();
    } else {
        initializeMockey(new URL("http://127.0.0.1" + ":" + String.valueOf(port) + initUrl));
    }
}

From source file:com.bah.applefox.main.Ingest.java

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

    if (args.length == 1 && args[0].equals("--help")) {
        System.out.println("Not enough arguments");
        System.out.println("Arguments should be in the format <properties file> <command>");
        System.out.println("Valid commands:");
        System.out.println("\tpr: Calculates Page Rank");
        System.out.println("\timageload: Loads Images from URLs");
        System.out.println("\tload: Loads Full Text Data");
        System.out.println("\tingest: Ingests URLs from given seed");
        System.out.println("\tftsample: Creates a Full Text Index Sample HashMap");
        System.out.println("\timagesample: Creates an Image Hash and Image Tag Sample HashMap");
    }//from   w ww  .  j  a va2 s  . com
    if (args.length > 2) {
        System.out.println("2 Arguments expected, " + args.length + " given.");
    }

    if (args.length < 2) {
        System.out.println("Not enough arguments");
        System.out.println("Arguments should be in the format <properties file> <command>");
        System.out.println("Valid commands:");
        System.out.println("\tpr: Calculates Page Rank");
        System.out.println("\timageload: Loads Images from URLs");
        System.out.println("\tload: Loads Full Text Data");
        System.out.println("\tingest: Ingests URLs from given seed");
        System.out.println("\tftsample: Creates a Full Text Index Sample HashMap");
        System.out.println("\timagesample: Creates an Image Hash and Image Tag Sample HashMap");
    }
    injector = Guice.createInjector(new IngesterModule());

    // The properties object to read from the configuration file
    Properties properties = new Properties();

    try {
        // Load configuration file from the command line
        properties.load(new FileInputStream(args[0]));
    } catch (Exception e) {
        log.error("ABORT: File not found or could not read from file ->" + e.getMessage());
        log.error("Enter the location of the configuration file");
        System.exit(1);
    }

    // Initialize variables from configuration file

    // Accumulo Variables
    INSTANCE_NAME = properties.getProperty("INSTANCE_NAME");
    ZK_SERVERS = properties.getProperty("ZK_SERVERS");
    USERNAME = properties.getProperty("USERNAME");
    PASSWORD = properties.getProperty("PASSWORD");
    SPLIT_SIZE = properties.getProperty("SPLIT_SIZE");
    NUM_ITERATIONS = Integer.parseInt(properties.getProperty("NUM_ITERATIONS"));
    NUM_NODES = Integer.parseInt(properties.getProperty("NUM_NODES"));

    // General Search Variables
    MAX_NGRAMS = Integer.parseInt(properties.getProperty("MAX_NGRAMS"));
    GENERAL_STOP = properties.getProperty("GENERAL_STOP");

    // Full Text Variables
    FT_DATA_TABLE = properties.getProperty("FT_DATA_TABLE");
    FT_SAMPLE = properties.getProperty("FT_SAMPLE");
    FT_CHECKED_TABLE = properties.getProperty("FT_CHECKED_TABLE");
    FT_DIVS_FILE = properties.getProperty("FT_DIVS_FILE");
    FT_SPLIT_SIZE = properties.getProperty("FT_SPLIT_SIZE");

    // Web Crawler Variables
    URL_TABLE = properties.getProperty("URL_TABLE");
    SEED = properties.getProperty("SEED");
    USER_AGENT = properties.getProperty("USER_AGENT");
    URL_SPLIT_SIZE = properties.getProperty("URL_SPLIT_SIZE");

    // Page Rank Variables
    PR_TABLE_PREFIX = properties.getProperty("PR_TABLE_PREFIX");
    PR_URL_MAP_TABLE_PREFIX = properties.getProperty("PR_URL_MAP_TABLE_PREFIX");
    PR_OUT_LINKS_COUNT_TABLE = properties.getProperty("PR_OUT_LINKS_COUNT_TABLE");
    PR_FILE = properties.getProperty("PR_FILE");
    PR_DAMPENING_FACTOR = Double.parseDouble(properties.getProperty("PR_DAMPENING_FACTOR"));
    PR_ITERATIONS = Integer.parseInt(properties.getProperty("PR_ITERATIONS"));
    PR_SPLIT_SIZE = properties.getProperty("PR_SPLIT_SIZE");

    // Image Variables
    IMG_HASH_TABLE = properties.getProperty("IMG_HASH_TABLE");
    IMG_CHECKED_TABLE = properties.getProperty("IMG_CHECKED_TABLE");
    IMG_TAG_TABLE = properties.getProperty("IMG_TAG_TABLE");
    IMG_HASH_SAMPLE_TABLE = properties.getProperty("IMG_HASH_SAMPLE_TABLE");
    IMG_TAG_SAMPLE_TABLE = properties.getProperty("IMG_TAG_SAMPLE_TABLE");
    IMG_SPLIT_SIZE = properties.getProperty("IMG_SPLIT_SIZE");

    // Future Use:
    // Work Directory in HDFS
    WORK_DIR = properties.getProperty("WORK_DIR");

    // Initialize variable from command line
    RUN = args[1].toLowerCase();

    // Set the instance information for AccumuloUtils
    AccumuloUtils.setInstanceName(INSTANCE_NAME);
    AccumuloUtils.setInstancePassword(PASSWORD);
    AccumuloUtils.setUser(USERNAME);
    AccumuloUtils.setZooserver(ZK_SERVERS);
    AccumuloUtils.setSplitSize(SPLIT_SIZE);

    String[] temp = new String[25];

    // Accumulo Variables
    temp[0] = INSTANCE_NAME;
    temp[1] = ZK_SERVERS;
    temp[2] = USERNAME;
    temp[3] = PASSWORD;

    // Number of Map Tasks
    temp[4] = Integer.toString((int) Math.ceil(1.75 * NUM_NODES * 2));

    // Web Crawler Variables
    temp[5] = URL_TABLE;
    temp[6] = USER_AGENT;

    // Future Use
    temp[7] = WORK_DIR;

    // General Search
    temp[8] = GENERAL_STOP;
    temp[9] = Integer.toString(MAX_NGRAMS);

    // Full Text Variables
    temp[10] = FT_DATA_TABLE;
    temp[11] = FT_CHECKED_TABLE;

    // Page Rank Variables
    temp[12] = PR_URL_MAP_TABLE_PREFIX;
    temp[13] = PR_TABLE_PREFIX;
    temp[14] = Double.toString(PR_DAMPENING_FACTOR);
    temp[15] = PR_OUT_LINKS_COUNT_TABLE;
    temp[16] = PR_FILE;

    // Image Variables
    temp[17] = IMG_HASH_TABLE;
    temp[18] = IMG_CHECKED_TABLE;
    temp[19] = IMG_TAG_TABLE;

    temp[20] = FT_DIVS_FILE;

    // Table Split Sizes
    temp[21] = FT_SPLIT_SIZE;
    temp[22] = IMG_SPLIT_SIZE;
    temp[23] = URL_SPLIT_SIZE;
    temp[24] = PR_SPLIT_SIZE;

    if (RUN.equals("pr")) {
        // Run PR_ITERATIONS number of iterations for page ranking
        PageRank.createPageRank(temp, PR_ITERATIONS, URL_SPLIT_SIZE);
    } else if (RUN.equals("imageload")) {
        // Load image index
        AccumuloUtils.setSplitSize(URL_SPLIT_SIZE);
        ToolRunner.run(new ImageLoader(), temp);
    } else if (RUN.equals("ingest")) {
        // Ingest
        System.out.println("Ingesting");
        // Set table split size
        AccumuloUtils.setSplitSize(URL_SPLIT_SIZE);
        // Write the seed value to the table
        BatchWriter w;
        Value v = new Value();
        v.set("0".getBytes());
        Mutation m = new Mutation(SEED);
        m.put("0", "0", v);
        w = AccumuloUtils.connectBatchWrite(URL_TABLE);
        w.addMutation(m);

        for (int i = 0; i < NUM_ITERATIONS; i++) {
            // Run the ToolRunner for NUM_ITERATIONS iterations
            ToolRunner.run(CachedConfiguration.getInstance(), injector.getInstance(Ingester.class), temp);
        }
    } else if (RUN.equals("load")) {
        // Parse the URLs and add to the data table
        AccumuloUtils.setSplitSize(URL_SPLIT_SIZE);
        BatchWriter w = AccumuloUtils.connectBatchWrite(FT_CHECKED_TABLE);
        w.close();

        AccumuloUtils.setSplitSize(FT_SPLIT_SIZE);
        w = AccumuloUtils.connectBatchWrite(FT_DATA_TABLE);
        w.close();
        ToolRunner.run(CachedConfiguration.getInstance(), injector.getInstance(Loader.class), temp);
    } else if (RUN.equals("ftsample")) {
        // Create a sample table for full text index
        FTAccumuloSampler ftSampler = new FTAccumuloSampler(FT_SAMPLE, FT_DATA_TABLE, FT_CHECKED_TABLE);
        ftSampler.createSample();

    } else if (RUN.equals("imagesample")) {
        // Create a sample table for images
        ImageAccumuloSampler imgHashSampler = new ImageAccumuloSampler(IMG_HASH_SAMPLE_TABLE, IMG_HASH_TABLE,
                IMG_CHECKED_TABLE);
        imgHashSampler.createSample();

        ImageAccumuloSampler imgTagSampler = new ImageAccumuloSampler(IMG_TAG_SAMPLE_TABLE, IMG_TAG_TABLE,
                IMG_CHECKED_TABLE);
        imgTagSampler.createSample();
    } else {
        System.out.println("Invalid argument " + RUN + ".");
        System.out.println("Valid Arguments:");
        System.out.println("\tpr: Calculates Page Rank");
        System.out.println("\timageload: Loads Images from URLs");
        System.out.println("\tload: Loads Full Text Data");
        System.out.println("\tingest: Ingests URLs from given seed");
        System.out.println("\tftsample: Creates a Full Text Index Sample HashMap");
        System.out.println("\timagesample: Creates an Image Hash and Image Tag Sample HashMap");
    }

}

From source file:kellinwood.zipsigner.cmdline.Main.java

public static void main(String[] args) {
    try {//from w w w  . j  ava  2s .  co m

        Options options = new Options();
        CommandLine cmdLine = null;
        Option helpOption = new Option("h", "help", false, "Display usage information");

        Option modeOption = new Option("m", "keymode", false,
                "Keymode one of: auto, auto-testkey, auto-none, media, platform, shared, testkey, none");
        modeOption.setArgs(1);

        Option keyOption = new Option("k", "key", false, "PCKS#8 encoded private key file");
        keyOption.setArgs(1);

        Option pwOption = new Option("p", "keypass", false, "Private key password");
        pwOption.setArgs(1);

        Option certOption = new Option("c", "cert", false, "X.509 public key certificate file");
        certOption.setArgs(1);

        Option sbtOption = new Option("t", "template", false, "Signature block template file");
        sbtOption.setArgs(1);

        Option keystoreOption = new Option("s", "keystore", false, "Keystore file");
        keystoreOption.setArgs(1);

        Option aliasOption = new Option("a", "alias", false, "Alias for key/cert in the keystore");
        aliasOption.setArgs(1);

        options.addOption(helpOption);
        options.addOption(modeOption);
        options.addOption(keyOption);
        options.addOption(certOption);
        options.addOption(sbtOption);
        options.addOption(pwOption);
        options.addOption(keystoreOption);
        options.addOption(aliasOption);

        Parser parser = new BasicParser();

        try {
            cmdLine = parser.parse(options, args);
        } catch (MissingOptionException x) {
            System.out.println("One or more required options are missing: " + x.getMessage());
            usage(options);
        } catch (ParseException x) {
            System.out.println(x.getClass().getName() + ": " + x.getMessage());
            usage(options);
        }

        if (cmdLine.hasOption(helpOption.getOpt()))
            usage(options);

        Properties log4jProperties = new Properties();
        log4jProperties.load(new FileReader("log4j.properties"));
        PropertyConfigurator.configure(log4jProperties);
        LoggerManager.setLoggerFactory(new Log4jLoggerFactory());

        List<String> argList = cmdLine.getArgList();
        if (argList.size() != 2)
            usage(options);

        ZipSigner signer = new ZipSigner();

        signer.addAutoKeyObserver(new Observer() {
            @Override
            public void update(Observable observable, Object o) {
                System.out.println("Signing with key: " + o);
            }
        });

        Class bcProviderClass = Class.forName("org.bouncycastle.jce.provider.BouncyCastleProvider");
        Provider bcProvider = (Provider) bcProviderClass.newInstance();

        KeyStoreFileManager.setProvider(bcProvider);

        signer.loadProvider("org.spongycastle.jce.provider.BouncyCastleProvider");

        PrivateKey privateKey = null;
        if (cmdLine.hasOption(keyOption.getOpt())) {
            if (!cmdLine.hasOption(certOption.getOpt())) {
                System.out.println("Certificate file is required when specifying a private key");
                usage(options);
            }

            String keypw = null;
            if (cmdLine.hasOption(pwOption.getOpt()))
                keypw = pwOption.getValue();
            else {
                keypw = new String(readPassword("Key password"));
                if (keypw.equals(""))
                    keypw = null;
            }
            URL privateKeyUrl = new File(keyOption.getValue()).toURI().toURL();

            privateKey = signer.readPrivateKey(privateKeyUrl, keypw);
        }

        X509Certificate cert = null;
        if (cmdLine.hasOption(certOption.getOpt())) {

            if (!cmdLine.hasOption(keyOption.getOpt())) {
                System.out.println("Private key file is required when specifying a certificate");
                usage(options);
            }

            URL certUrl = new File(certOption.getValue()).toURI().toURL();
            cert = signer.readPublicKey(certUrl);
        }

        byte[] sigBlockTemplate = null;
        if (cmdLine.hasOption(sbtOption.getOpt())) {
            URL sbtUrl = new File(sbtOption.getValue()).toURI().toURL();
            sigBlockTemplate = signer.readContentAsBytes(sbtUrl);
        }

        if (cmdLine.hasOption(keyOption.getOpt())) {
            signer.setKeys("custom", cert, privateKey, sigBlockTemplate);
            signer.signZip(argList.get(0), argList.get(1));
        } else if (cmdLine.hasOption(modeOption.getOpt())) {
            signer.setKeymode(modeOption.getValue());
            signer.signZip(argList.get(0), argList.get(1));
        } else if (cmdLine.hasOption((keystoreOption.getOpt()))) {
            String alias = null;

            if (!cmdLine.hasOption(aliasOption.getOpt())) {

                KeyStore keyStore = KeyStoreFileManager.loadKeyStore(keystoreOption.getValue(), (char[]) null);
                for (Enumeration<String> e = keyStore.aliases(); e.hasMoreElements();) {
                    alias = e.nextElement();
                    System.out.println("Signing with key: " + alias);
                    break;
                }
            } else
                alias = aliasOption.getValue();

            String keypw = null;
            if (cmdLine.hasOption(pwOption.getOpt()))
                keypw = pwOption.getValue();
            else {
                keypw = new String(readPassword("Key password"));
                if (keypw.equals(""))
                    keypw = null;
            }

            CustomKeySigner.signZip(signer, keystoreOption.getValue(), null, alias, keypw.toCharArray(),
                    "SHA1withRSA", argList.get(0), argList.get(1));
        } else {
            signer.setKeymode("auto-testkey");
            signer.signZip(argList.get(0), argList.get(1));
        }

    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:PropertiesUtil.java

public static void main(String args[]) {
    try {/*w  w  w .  j  av  a2  s .  c om*/
        System.out.println(load(new Properties(),
                "C:/data/ccm_wa/dordev/Countrywide~csdrzs/Countrywide/src/com/javelin/util/test.properties"));
        System.out.println(load(new Properties(), new File(
                "C:/data/ccm_wa/dordev/Countrywide~csdrzs/Countrywide/src/com/javelin/util/test.properties")));
        System.out.println(load(new Properties(), new URL(
                "file:///C:/data/ccm_wa/dordev/Countrywide~csdrzs/Countrywide/src/com/javelin/util/test.properties")));
        System.out.println(load(new Properties(), PropertiesUtil.class, "test.properties"));
        Properties properties = new Properties();
        properties.put("1", "2");
        properties.put("2", "2");
        properties.put("3", "3");
        store(properties,
                "C:/data/ccm_wa/dordev/Countrywide~csdrzs/Countrywide/src/com/javelin/util/test1.properties");
        store(properties, new File(
                "C:/data/ccm_wa/dordev/Countrywide~csdrzs/Countrywide/src/com/javelin/util/test2.properties"));
        store(properties, PropertiesUtil.class, "test4.properties");
        System.out.println(getByValue(properties, "2"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.opengamma.batch.BatchJobRunner.java

/**
 * Creates an runs a batch job based on a properties file and configuration.
 *///from ww w . ja  va  2 s  .  c  o m
public static void main(String[] args) throws Exception { // CSIGNORE
    if (args.length == 0) {
        usage();
        System.exit(-1);
    }

    CommandLine line = null;
    Properties configProperties = null;

    final String propertyFile = "batchJob.properties";

    String configPropertyFile = null;

    if (System.getProperty(propertyFile) != null) {
        configPropertyFile = System.getProperty(propertyFile);
        try {
            FileInputStream fis = new FileInputStream(configPropertyFile);
            configProperties = new Properties();
            configProperties.load(fis);
            fis.close();
        } catch (FileNotFoundException e) {
            s_logger.error("The system cannot find " + configPropertyFile);
            System.exit(-1);
        }
    } else {
        try {
            FileInputStream fis = new FileInputStream(propertyFile);
            configProperties = new Properties();
            configProperties.load(fis);
            fis.close();
            configPropertyFile = propertyFile;
        } catch (FileNotFoundException e) {
            // there is no config file so we expect command line arguments
            try {
                CommandLineParser parser = new PosixParser();
                line = parser.parse(getOptions(), args);
            } catch (ParseException e2) {
                usage();
                System.exit(-1);
            }
        }
    }

    RunCreationMode runCreationMode = getRunCreationMode(line, configProperties, configPropertyFile);
    if (runCreationMode == null) {
        // default
        runCreationMode = RunCreationMode.AUTO;
    }

    String engineURI = getProperty("engineURI", line, configProperties, configPropertyFile);

    String brokerURL = getProperty("brokerURL", line, configProperties, configPropertyFile);

    Instant valuationTime = getValuationTime(line, configProperties, configPropertyFile);
    LocalDate observationDate = getObservationDate(line, configProperties, configPropertyFile);

    UniqueId viewDefinitionUniqueId = getViewDefinitionUniqueId(line, configProperties);

    URI vpBase;
    try {
        vpBase = new URI(engineURI);
    } catch (URISyntaxException ex) {
        throw new OpenGammaRuntimeException("Invalid URI", ex);
    }

    ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(brokerURL);
    activeMQConnectionFactory.setWatchTopicAdvisories(false);

    JmsConnectorFactoryBean jmsConnectorFactoryBean = new JmsConnectorFactoryBean();
    jmsConnectorFactoryBean.setConnectionFactory(activeMQConnectionFactory);
    jmsConnectorFactoryBean.setName("Masters");

    JmsConnector jmsConnector = jmsConnectorFactoryBean.getObjectCreating();
    ScheduledExecutorService heartbeatScheduler = Executors.newSingleThreadScheduledExecutor();
    try {
        ViewProcessor vp = new RemoteViewProcessor(vpBase, jmsConnector, heartbeatScheduler);
        ViewClient vc = vp.createViewClient(UserPrincipal.getLocalUser());

        HistoricalMarketDataSpecification marketDataSpecification = MarketData.historical(observationDate,
                null);

        ViewExecutionOptions executionOptions = ExecutionOptions.batch(valuationTime, marketDataSpecification,
                null);

        vc.attachToViewProcess(viewDefinitionUniqueId, executionOptions);
        vc.waitForCompletion();
    } finally {
        heartbeatScheduler.shutdown();
    }
}

From source file:io.s4.MainApp.java

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

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(//from w ww. ja  va 2s .  c  om
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:org.ensembl.gti.seqstore.server.MetaDataServer.java

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

    final Logger log = LoggerFactory.getLogger(MetaDataServer.class);

    Properties properties = new Properties();
    properties.load(new ClassPathResource("metadata_server.properties").getInputStream());

    MetaDataServerOptions opts = new MetaDataServerOptions(properties);

    new JCommander(opts, args);

    log.info("Starting ENA submission handler");
    EnaCramSubmissionHandler enaHandler = new EnaCramSubmissionHandler(opts.getFtpUri(), opts.getSubmitUri(),
            opts.getCentre(), opts.getSubmitUser(), opts.getSubmitPass());

    log.info("Starting server on " + opts.getPort());
    new MetaDataServer(opts.getPort(), buildDataSource(opts.getDbUri(), opts.getDbUser(), opts.getDbPass()),
            enaHandler).run();//from  w  w w.  j a v a  2s .c  om

}

From source file:com.cisco.dvbu.ps.common.adapters.core.CisWsClient.java

public static void main(String[] args) throws Exception {
    if (args.length < 8) {
        System.err.println(/*from w  ww .  j ava 2s  .  co  m*/
                "usage: java com.cisco.dvbu.ps.common.adapters.core.CisWsClient endpointName endpointMethod configXml requestXml host port user password <domain>");
        System.exit(1);
    }
    org.apache.log4j.BasicConfigurator.configure();
    // DEBUG, INFO, ERROR
    org.apache.log4j.Logger.getRootLogger().setLevel(org.apache.log4j.Level.DEBUG);
    String endpointName = args[0]; // "server"
    String endpointMethod = args[1]; // "getServerAttributes"
    String adapterConfigPath = args[2]; // E:\dev\Workspaces\PDToolGitTest\PDTool_poc\resources\config\6.2.0\cis_adapter_config.xml
    String requestXMLPath = args[3]; // path to request xml

    Properties props = new Properties();
    props.setProperty(AdapterConstants.ADAPTER_HOST, args[4]);
    props.setProperty(AdapterConstants.ADAPTER_PORT, args[5]);
    props.setProperty(AdapterConstants.ADAPTER_USER, args[6]);
    props.setProperty(AdapterConstants.ADAPTER_PSWD, args[7]);
    if (args.length == 9)
        props.setProperty(AdapterConstants.ADAPTER_DOMAIN, args[8]);

    // Read the request xml file
    FileInputStream input = new FileInputStream(requestXMLPath);
    byte[] fileData = new byte[input.available()];
    input.read(fileData);
    input.close();
    String requestXml = new String(fileData, "UTF-8");

    // Execute the CIS Web Service Client for an adapter configuration
    CisWsClient cisclient = new CisWsClient(props, adapterConfigPath);

    System.out.println("Request: " + requestXml);
    // String requestXml = "<?xml version=\"1.0\"?> <p1:ServerAttributeModule xmlns:p1=\"http://www.dvbu.cisco.com/ps/deploytool/modules\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.dvbu.cisco.com/ps/deploytool/modules file:///e:/dev/Workspaces/PDToolGitTest/PDToolModules/schema/PDToolModules.xsd\">     <!--Element serverAttribute, maxOccurs=unbounded-->     <serverAttribute>         <id>sa1</id>         <name>/server/event/generation/sessions/sessionLoginFail</name>         <type>UNKNOWN</type>         <!--Element value is optional-->         <value>string</value>         <!--Element valueArray is optional-->         <valueArray>             <!--Element item is optional, maxOccurs=unbounded-->             <item>string</item>             <item>string</item>             <item>string</item>         </valueArray>         <!--Element valueList is optional-->         <valueList>             <!--Element item is optional, maxOccurs=unbounded-->             <item>                 <!--Element type is optional-->                 <type>UNKNOWN</type>                 <!--Element value is optional-->                 <value>string</value>             </item>             <item>                 <!--Element type is optional-->                 <type>UNKNOWN</type>                 <!--Element value is optional-->                 <value>string</value>             </item>             <item>                 <!--Element type is optional-->                 <type>UNKNOWN</type>                 <!--Element value is optional-->                 <value>string</value>             </item>         </valueList>         <!--Element valueMap is optional-->         <valueMap>             <!--Element entry is optional, maxOccurs=unbounded-->             <entry>                 <!--Element key is optional-->                 <key>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </key>                 <!--Element value is optional-->                 <value>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </value>             </entry>             <entry>                 <!--Element key is optional-->                 <key>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </key>                 <!--Element value is optional-->                 <value>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </value>             </entry>             <entry>                 <!--Element key is optional-->                 <key>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </key>                 <!--Element value is optional-->                 <value>                     <!--Element type is optional-->                     <type>UNKNOWN</type>                     <!--Element value is optional-->                     <value>string</value>                 </value>             </entry>         </valueMap>     </serverAttribute> </p1:ServerAttributeModule>";
    String response = cisclient.sendRequest(endpointName, endpointMethod, requestXml);
    System.out.println("Response: " + response);
}

From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java

/**
 * Main method used for creating initial key file.
 * /*w ww  . j ava  2  s  .c  o m*/
 * @param args
 *            - not used
 */
public static void main(String[] args) {
    final String keyFile = "./howto.key";
    final String pwdFile = "./howto.properties";

    CryptoUtilImpl cryptoUtils = new CryptoUtilImpl();
    cryptoUtils.setKeyFile(new File(keyFile));

    String clearPwd = "my_cleartext_pwd";

    Properties p1 = new Properties();
    Writer w = null;
    try {
        p1.put("user", "liferay");
        String encryptedPwd = cryptoUtils.encrypt(clearPwd);
        p1.put("pwd", encryptedPwd);
        w = new FileWriter(pwdFile);
        p1.store(w, "");
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (w != null) {
            try {
                w.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // ==================
    Properties p2 = new Properties();
    Reader r = null;
    try {
        r = new FileReader(pwdFile);
        p2.load(r);
        String encryptedPwd = p2.getProperty("pwd");
        System.out.println(encryptedPwd);
        System.out.println(cryptoUtils.decrypt(encryptedPwd));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } finally {
        if (r != null) {
            try {
                r.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}