Example usage for java.util Properties load

List of usage examples for java.util Properties load

Introduction

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

Prototype

public synchronized void load(InputStream inStream) throws IOException 

Source Link

Document

Reads a property list (key and element pairs) from the input byte stream.

Usage

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

public static void main(String[] args) {
    try {//  ww w  . j av a  2  s . c o 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:com.joliciel.talismane.terminology.TalismaneTermExtractorMain.java

public static void main(String[] args) throws Exception {
    String termFilePath = null;//from   w w w. j a v  a  2  s. co m
    String outFilePath = null;
    Command command = Command.extract;
    int depth = -1;
    String databasePropertiesPath = null;
    String projectCode = null;
    String terminologyPropertiesPath = null;

    Map<String, String> argMap = StringUtils.convertArgs(args);

    String logConfigPath = argMap.get("logConfigFile");
    if (logConfigPath != null) {
        argMap.remove("logConfigFile");
        Properties props = new Properties();
        props.load(new FileInputStream(logConfigPath));
        PropertyConfigurator.configure(props);
    }

    Map<String, String> innerArgs = new HashMap<String, String>();
    for (Entry<String, String> argEntry : argMap.entrySet()) {
        String argName = argEntry.getKey();
        String argValue = argEntry.getValue();

        if (argName.equals("command"))
            command = Command.valueOf(argValue);
        else if (argName.equals("termFile"))
            termFilePath = argValue;
        else if (argName.equals("outFile"))
            outFilePath = argValue;
        else if (argName.equals("depth"))
            depth = Integer.parseInt(argValue);
        else if (argName.equals("databaseProperties"))
            databasePropertiesPath = argValue;
        else if (argName.equals("terminologyProperties"))
            terminologyPropertiesPath = argValue;
        else if (argName.equals("projectCode"))
            projectCode = argValue;
        else
            innerArgs.put(argName, argValue);
    }
    if (termFilePath == null && databasePropertiesPath == null)
        throw new TalismaneException("Required argument: termFile or databasePropertiesPath");

    if (termFilePath != null) {
        String currentDirPath = System.getProperty("user.dir");
        File termFileDir = new File(currentDirPath);
        if (termFilePath.lastIndexOf("/") >= 0) {
            String termFileDirPath = termFilePath.substring(0, termFilePath.lastIndexOf("/"));
            termFileDir = new File(termFileDirPath);
            termFileDir.mkdirs();
        }
    }

    long startTime = new Date().getTime();
    try {
        if (command.equals(Command.analyse)) {
            innerArgs.put("command", "analyse");
        } else {
            innerArgs.put("command", "process");
        }

        String sessionId = "";
        TalismaneServiceLocator locator = TalismaneServiceLocator.getInstance(sessionId);
        TalismaneService talismaneService = locator.getTalismaneService();

        TalismaneConfig config = talismaneService.getTalismaneConfig(innerArgs, sessionId);

        TerminologyServiceLocator terminologyServiceLocator = TerminologyServiceLocator.getInstance(locator);
        TerminologyService terminologyService = terminologyServiceLocator.getTerminologyService();
        TerminologyBase terminologyBase = null;

        if (projectCode == null)
            throw new TalismaneException("Required argument: projectCode");

        File file = new File(databasePropertiesPath);
        FileInputStream fis = new FileInputStream(file);
        Properties dataSourceProperties = new Properties();
        dataSourceProperties.load(fis);
        terminologyBase = terminologyService.getPostGresTerminologyBase(projectCode, dataSourceProperties);

        TalismaneSession talismaneSession = talismaneService.getTalismaneSession();

        if (command.equals(Command.analyse) || command.equals(Command.extract)) {
            Locale locale = talismaneSession.getLocale();
            Map<TerminologyProperty, String> terminologyProperties = new HashMap<TerminologyProperty, String>();
            if (terminologyPropertiesPath != null) {
                Map<String, String> terminologyPropertiesStr = StringUtils.getArgMap(terminologyPropertiesPath);
                for (String key : terminologyPropertiesStr.keySet()) {
                    try {
                        TerminologyProperty property = TerminologyProperty.valueOf(key);
                        terminologyProperties.put(property, terminologyPropertiesStr.get(key));
                    } catch (IllegalArgumentException e) {
                        throw new TalismaneException("Unknown terminology property: " + key);
                    }
                }
            } else {
                terminologyProperties = getDefaultTerminologyProperties(locale);
            }
            if (depth <= 0 && !terminologyProperties.containsKey(TerminologyProperty.maxDepth))
                throw new TalismaneException("Required argument: depth");

            InputStream regexInputStream = getInputStreamFromResource(
                    "parser_conll_with_location_input_regex.txt");
            Scanner regexScanner = new Scanner(regexInputStream, "UTF-8");
            String inputRegex = regexScanner.nextLine();
            regexScanner.close();
            config.setInputRegex(inputRegex);

            Charset outputCharset = config.getOutputCharset();

            TermExtractor termExtractor = terminologyService.getTermExtractor(terminologyBase,
                    terminologyProperties);
            if (depth > 0)
                termExtractor.setMaxDepth(depth);
            termExtractor.setOutFilePath(termFilePath);

            if (outFilePath != null) {
                if (outFilePath.lastIndexOf("/") >= 0) {
                    String outFileDirPath = outFilePath.substring(0, outFilePath.lastIndexOf("/"));
                    File outFileDir = new File(outFileDirPath);
                    outFileDir.mkdirs();
                }
                File outFile = new File(outFilePath);
                outFile.delete();
                outFile.createNewFile();

                Writer writer = new BufferedWriter(
                        new OutputStreamWriter(new FileOutputStream(outFilePath), outputCharset));
                TermAnalysisWriter termAnalysisWriter = new TermAnalysisWriter(writer);
                termExtractor.addTermObserver(termAnalysisWriter);
            }

            Talismane talismane = config.getTalismane();
            talismane.setParseConfigurationProcessor(termExtractor);
            talismane.process();
        } else if (command.equals(Command.list)) {

            List<Term> terms = terminologyBase.findTerms(2, null, 0, null, null);
            for (Term term : terms) {
                LOG.debug("Term: " + term.getText());
                LOG.debug("Frequency: " + term.getFrequency());
                LOG.debug("Heads: " + term.getHeads());
                LOG.debug("Expansions: " + term.getExpansions());
                LOG.debug("Contexts: " + term.getContexts());
            }
        }
    } finally {
        long endTime = new Date().getTime();
        long totalTime = endTime - startTime;
        LOG.info("Total time: " + totalTime);
    }
}

From source file:com.mmounirou.spotirss.SpotiRss.java

/**
 * @param args//from  w w w . ja v a 2 s. c o  m
 * @throws IOException 
 * @throws ClassNotFoundException 
 * @throws IllegalAccessException 
 * @throws InstantiationException 
 * @throws SpotifyClientException 
 * @throws ChartRssException 
 * @throws SpotifyException 
 */
public static void main(String[] args) throws IOException, InstantiationException, IllegalAccessException,
        ClassNotFoundException, SpotifyClientException {
    if (args.length == 0) {
        System.err.println("usage : java -jar spotiboard.jar <charts-folder>");
        return;
    }

    Properties connProperties = new Properties();
    InputStream inStream = SpotiRss.class.getResourceAsStream("/spotify-server.properties");
    try {
        connProperties.load(inStream);
    } finally {
        IOUtils.closeQuietly(inStream);
    }

    String host = connProperties.getProperty("host");
    int port = Integer.parseInt(connProperties.getProperty("port"));
    String user = connProperties.getProperty("user");

    final SpotifyClient spotifyClient = new SpotifyClient(host, port, user);
    final Map<String, Playlist> playlistsByTitle = getPlaylistsByTitle(spotifyClient);

    final File outputDir = new File(args[0]);
    outputDir.mkdirs();
    TrackCache cache = new TrackCache();
    try {

        for (String strProvider : PROVIDERS) {
            String providerClassName = EntryToTrackConverter.class.getPackage().getName() + "."
                    + StringUtils.capitalize(strProvider);
            final EntryToTrackConverter converter = (EntryToTrackConverter) SpotiRss.class.getClassLoader()
                    .loadClass(providerClassName).newInstance();
            Iterable<String> chartsRss = getCharts(strProvider);
            final File resultDir = new File(outputDir, strProvider);
            resultDir.mkdir();

            final SpotifyHrefQuery hrefQuery = new SpotifyHrefQuery(cache);
            Iterable<String> results = FluentIterable.from(chartsRss).transform(new Function<String, String>() {

                @Override
                @Nullable
                public String apply(@Nullable String chartRss) {

                    try {

                        long begin = System.currentTimeMillis();
                        ChartRss bilboardChartRss = ChartRss.getInstance(chartRss, converter);
                        Map<Track, String> trackHrefs = hrefQuery.getTrackHrefs(bilboardChartRss.getSongs());

                        String strTitle = bilboardChartRss.getTitle();
                        File resultFile = new File(resultDir, strTitle);
                        List<String> lines = Lists.newLinkedList(FluentIterable.from(trackHrefs.keySet())
                                .transform(Functions.toStringFunction()));
                        lines.addAll(trackHrefs.values());
                        FileUtils.writeLines(resultFile, Charsets.UTF_8.displayName(), lines);

                        Playlist playlist = playlistsByTitle.get(strTitle);
                        if (playlist != null) {
                            playlist.getTracks().clear();
                            playlist.getTracks().addAll(trackHrefs.values());
                            spotifyClient.patch(playlist);
                            LOGGER.info(String.format("%s chart exported patched", strTitle));
                        }

                        LOGGER.info(String.format("%s chart exported in %s in %d s", strTitle,
                                resultFile.getAbsolutePath(),
                                (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - begin)));

                    } catch (Exception e) {
                        LOGGER.error(String.format("fail to export %s charts", chartRss), e);
                    }

                    return "";
                }
            });

            // consume iterables
            Iterables.size(results);

        }

    } finally {
        cache.close();
    }

}

From source file:com.simple.sftpfetch.App.java

public static void main(String[] args) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    Options options = getOptions();/*from   www .  j a v  a  2 s .c o  m*/

    List<String> requiredProperties = asList("c");

    CommandLineParser parser = new PosixParser();
    try {
        CommandLine commandLine = parser.parse(options, args);
        if (commandLine.hasOption("h")) {
            printUsage(options);
            System.exit(0);
        }

        for (String opt : requiredProperties) {
            if (!commandLine.hasOption(opt)) {
                System.err.println("The option: " + opt + " is required.");
                printUsage(options);
                System.exit(1);
            }
        }

        Pattern pattern;
        if (commandLine.hasOption("p")) {
            pattern = Pattern.compile(commandLine.getOptionValue("p"));
        } else {
            pattern = MATCH_EVERYTHING;
        }

        String filename = commandLine.getOptionValue("c");
        Properties properties = new Properties();
        try {
            InputStream stream = new FileInputStream(new File(filename));
            properties.load(stream);
        } catch (IOException ioe) {
            System.err.println("Unable to read properties from: " + filename);
            System.exit(2);
        }

        String routingKey = "";
        if (commandLine.hasOption("r")) {
            routingKey = commandLine.getOptionValue("r");
        } else if (properties.containsKey("rabbit.routingkey")) {
            routingKey = properties.getProperty("rabbit.routingkey");
        }

        int daysToFetch;
        if (commandLine.hasOption("d")) {
            daysToFetch = Integer.valueOf(commandLine.getOptionValue("d"));
        } else {
            daysToFetch = Integer.valueOf(properties.getProperty(FETCH_DAYS));
        }

        FileDecrypter decrypter = null;
        if (properties.containsKey("decryption.key.path")) {
            decrypter = new PGPFileDecrypter(new File(properties.getProperty("decryption.key.path")));
        } else {
            decrypter = new NoopDecrypter();
        }

        SftpClient sftpClient = new SftpClient(new JSch(), new SftpConnectionInfo(properties));
        try {
            App app = new App(sftpClient, s3FromProperties(properties),
                    new RabbitClient(new ConnectionFactory(), new RabbitConnectionInfo(properties)), decrypter,
                    System.out);
            app.run(routingKey, daysToFetch, pattern, commandLine.hasOption("n"), commandLine.hasOption("o"));
        } finally {
            sftpClient.close();
        }
        System.exit(0);
    } catch (UnrecognizedOptionException uoe) {
        System.err.println(uoe.getMessage());
        printUsage(options);
        System.exit(10);
    }
}

From source file:com.yahoo.pulsar.testclient.PerformanceConsumer.java

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-consumer");

    try {/*  ww  w  .  j  a va 2 s .co  m*/
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }

    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }

    if (arguments.topic.size() != 1) {
        System.out.println("Only one destination name is allowed");
        jc.usage();
        System.exit(-1);
    }

    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }

        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }

        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }

        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
    }

    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar performance consumer with config: {}", w.writeValueAsString(arguments));

    final DestinationName prefixDestinationName = DestinationName.get(arguments.topic.get(0));

    final RateLimiter limiter = arguments.rate > 0 ? RateLimiter.create(arguments.rate) : null;

    MessageListener listener = new MessageListener() {
        public void received(Consumer consumer, Message msg) {
            messagesReceived.increment();
            bytesReceived.add(msg.getData().length);

            if (limiter != null) {
                limiter.acquire();
            }

            consumer.acknowledgeAsync(msg);
        }
    };

    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2,
                new DefaultThreadFactory("pulsar-perf-consumer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-consumer"));
    }

    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }
    PulsarClient pulsarClient = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);

    List<Future<Consumer>> futures = Lists.newArrayList();
    ConsumerConfiguration consumerConfig = new ConsumerConfiguration();
    consumerConfig.setMessageListener(listener);
    consumerConfig.setReceiverQueueSize(arguments.receiverQueueSize);

    for (int i = 0; i < arguments.numDestinations; i++) {
        final DestinationName destinationName = (arguments.numDestinations == 1) ? prefixDestinationName
                : DestinationName.get(String.format("%s-%d", prefixDestinationName, i));
        log.info("Adding {} consumers on destination {}", arguments.numConsumers, destinationName);

        for (int j = 0; j < arguments.numConsumers; j++) {
            String subscriberName;
            if (arguments.numConsumers > 1) {
                subscriberName = String.format("%s-%d", arguments.subscriberName, j);
            } else {
                subscriberName = arguments.subscriberName;
            }

            futures.add(
                    pulsarClient.subscribeAsync(destinationName.toString(), subscriberName, consumerConfig));
        }
    }

    for (Future<Consumer> future : futures) {
        future.get();
    }

    log.info("Start receiving from {} consumers on {} destinations", arguments.numConsumers,
            arguments.numDestinations);

    long oldTime = System.nanoTime();

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }

        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;
        double rate = messagesReceived.sumThenReset() / elapsed;
        double throughput = bytesReceived.sumThenReset() / elapsed * 8 / 1024 / 1024;

        log.info("Throughput received: {}  msg/s -- {} Mbit/s", dec.format(rate), dec.format(throughput));
        oldTime = now;
    }

    pulsarClient.close();
}

From source file:io.personium.recovery.Recovery.java

/**
 * main./*from   w w  w  .ja va  2s . c o  m*/
 * @param args 
 */
public static void main(String[] args) {
    loadProperties();
    Option optIndex = new Option("i", "index", true, "?");
    Option optProp = new Option("p", "prop", true, "");
    // t??????????????????????
    Option optType = new Option("t", "type", true, "??type");
    Option optClear = new Option("c", "clear", false,
            "???elasticsearch?");
    Option optReplicas = new Option("r", "replicas", true, "??");
    Option optVersion = new Option("v", "version", false, "??");
    // 
    // optIndex.setRequired(true);
    //        optProp.setRequired(true);
    Options options = new Options();
    options.addOption(optIndex);
    options.addOption(optProp);
    options.addOption(optType);
    options.addOption(optClear);
    options.addOption(optReplicas);
    options.addOption(optVersion);
    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    try {
        commandLine = parser.parse(options, args, true);
    } catch (ParseException e) {
        (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options);
        log.warn("Recovery failure");
        System.exit(1);
    }

    if (commandLine.hasOption("v")) {
        log.info("Version:" + versionNumber);
        System.exit(0);
    }
    if (!commandLine.hasOption("p")) {
        (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options);
        log.warn("Recovery failure");
        System.exit(1);
    }
    if (commandLine.hasOption("t")) {
        log.info("Command line option \"t\" or \"type\" is deprecated. Option ignored.");
    }
    if (!commandLine.hasOption("r")) {
        (new HelpFormatter()).printHelp("io.personium.recovery.Recovery", options);
        log.warn("Command line option \"r\" is required.");
        System.exit(1);
    }

    RecoveryManager recoveryManager = new RecoveryManager();
    // ??index
    recoveryManager.setIndexNames(commandLine.getOptionValue("i"));
    // elasticsearch
    recoveryManager.setClear(commandLine.hasOption("c"));

    // ??
    // 0 ?ES??????????int???????
    try {
        int replicas = Integer.parseInt(commandLine.getOptionValue("r"));
        if (replicas < 0) {
            log.warn("Command line option \"r\"'s value is not integer.");
            System.exit(1);
        }
        recoveryManager.setReplicas(replicas);
    } catch (NumberFormatException e) {
        log.warn("Command line option \"r\"'s value is not integer.");
        System.exit(1);
    }

    try {
        // Properties?
        Properties properties = new Properties();
        // ?
        properties.load(new FileInputStream(commandLine.getOptionValue("p")));
        if ((!properties.containsKey(ES_HOSTS)) || (!properties.containsKey(ES_CLUSTER_NAME))
                || (!properties.containsKey(ADS_JDBC_URL)) || (!properties.containsKey(ADS_JDBC_USER))
                || (!properties.containsKey(ADS_JDBC_PASSWORD)) || (!properties.containsKey(ES_ROUTING_FLAG))) {
            log.warn("properties file error");
            log.warn("Recovery failure");
            System.exit(1);
        } else {
            recoveryManager.setEsHosts(properties.getProperty(ES_HOSTS));
            recoveryManager.setEsClusetrName(properties.getProperty(ES_CLUSTER_NAME));
            recoveryManager.setAdsJdbcUrl(properties.getProperty(ADS_JDBC_URL));
            recoveryManager.setAdsUser(properties.getProperty(ADS_JDBC_USER));
            recoveryManager.setAdsPassword(properties.getProperty(ADS_JDBC_PASSWORD));
            recoveryManager.setExecuteCnt(properties.getProperty(EXECUTE_COUNT));
            recoveryManager.setCheckCount(properties.getProperty(CHECK_COUNT));
            recoveryManager.setUnitPrefix(properties.getProperty(UNIT_PREFIX));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        log.warn("properties file error");
        log.warn("Recovery failure");
        System.exit(1);
    } catch (IOException e) {
        e.printStackTrace();
        log.warn("properties file error");
        log.warn("Recovery failure");
        System.exit(1);
    }

    String[] indexList = recoveryManager.getIndexNames();
    boolean isClear = recoveryManager.isClear();
    if (isClear && (indexList != null && null != indexList[0])) {
        String ad = recoveryManager.getUnitPrefix() + "_" + EsIndex.CATEGORY_AD;
        if (Arrays.asList(indexList).contains(ad)) {
            log.warn("Cannot specify both -c and -i " + recoveryManager.getUnitPrefix() + "_ad option.");
            log.warn("Recovery failure");
            System.exit(1);
        }
    }

    // ??????
    try {
        LockUtility.lock();
    } catch (AlreadyStartedException e) {
        log.info("Recovery has already started");
        log.info("Recovery failure");
        return;
    } catch (Exception e) {
        log.error("Failed to get lock for the double start control");
        e.printStackTrace();
        LockUtility.release();
        log.error("Recovery failure");
        System.exit(1);
    }

    // ??
    try {
        recoveryManager.recovery();
    } catch (Exception e) {
        LockUtility.release();
        log.error("Recovery failure");
        System.exit(1);
    }
    LockUtility.release();
    log.info("Recovery Success");
    return;
}

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

/** 
 * Main class. OX3 with OAuth demo//from   www. j  ava  2 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.mirth.connect.server.launcher.MirthLauncher.java

public static void main(String[] args) {
    try {//w ww .ja  v  a 2s.  c o  m
        try {
            uninstallPendingExtensions();
            installPendingExtensions();
        } catch (Exception e) {
            logger.error("Error uninstalling or installing pending extensions.", e);
        }

        Properties mirthProperties = new Properties();
        String includeCustomLib = null;

        try {
            mirthProperties.load(new FileInputStream(new File(MIRTH_PROPERTIES_FILE)));
            includeCustomLib = mirthProperties.getProperty(PROPERTY_INCLUDE_CUSTOM_LIB);
            createAppdataDir(mirthProperties);
        } catch (Exception e) {
            logger.error("Error creating the appdata directory.", e);
        }

        ManifestFile mirthServerJar = new ManifestFile("server-lib/mirth-server.jar");
        ManifestFile mirthClientCoreJar = new ManifestFile("server-lib/mirth-client-core.jar");
        ManifestDirectory serverLibDir = new ManifestDirectory("server-lib");
        serverLibDir.setExcludes(new String[] { "mirth-client-core.jar" });

        List<ManifestEntry> manifestList = new ArrayList<ManifestEntry>();
        manifestList.add(mirthServerJar);
        manifestList.add(mirthClientCoreJar);
        manifestList.add(serverLibDir);

        // We want to include custom-lib if the property isn't found, or if it equals "true"
        if (includeCustomLib == null || Boolean.valueOf(includeCustomLib)) {
            manifestList.add(new ManifestDirectory("custom-lib"));
        }

        ManifestEntry[] manifest = manifestList.toArray(new ManifestEntry[manifestList.size()]);

        // Get the current server version
        JarFile mirthClientCoreJarFile = new JarFile(mirthClientCoreJar.getName());
        Properties versionProperties = new Properties();
        versionProperties.load(mirthClientCoreJarFile
                .getInputStream(mirthClientCoreJarFile.getJarEntry("version.properties")));
        String currentVersion = versionProperties.getProperty("mirth.version");

        List<URL> classpathUrls = new ArrayList<URL>();
        addManifestToClasspath(manifest, classpathUrls);
        addExtensionsToClasspath(classpathUrls, currentVersion);
        URLClassLoader classLoader = new URLClassLoader(classpathUrls.toArray(new URL[classpathUrls.size()]));
        Class<?> mirthClass = classLoader.loadClass("com.mirth.connect.server.Mirth");
        Thread mirthThread = (Thread) mirthClass.newInstance();
        mirthThread.setContextClassLoader(classLoader);
        mirthThread.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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(/*  www  .  jav a 2s. co 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.widen.valet.importer.ImportZone.java

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

    InputStream stream = ImportZone.class.getResourceAsStream("importdns.properties");

    if (stream == null) {
        throw new RuntimeException("File importdns.properties not found!");
    }/*from   ww  w .j  a v  a2  s.  c  o m*/

    properties.load(stream);

    new ImportZone(properties).run();
}