Example usage for java.util Properties put

List of usage examples for java.util Properties put

Introduction

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

Prototype

@Override
    public synchronized Object put(Object key, Object value) 

Source Link

Usage

From source file:kafka.benchmark.AdvertisingTopology.java

public static void main(final String[] args) throws Exception {
    Options opts = new Options();
    opts.addOption("conf", true, "Path to the config file.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(opts, args);
    String configPath = cmd.getOptionValue("conf");
    Map<?, ?> conf = Utils.findAndReadConfigFile(configPath, true);

    Map<String, ?> benchmarkParams = getKafkaConfs(conf);

    LOG.info("conf: {}", conf);
    LOG.info("Parameters used: {}", benchmarkParams);

    KStreamBuilder builder = new KStreamBuilder();
    //        builder.addStateStore(
    //                Stores.create("config-params")
    //                .withStringKeys().withStringValues()
    //                .inMemory().maxEntries(10).build(), "redis");

    String topicsArr[] = { (String) benchmarkParams.get("topic") };
    KStream<String, ?> source1 = builder.stream(topicsArr);

    Properties props = new Properties();
    props.putAll(benchmarkParams);/*  ww  w .  j a  va2  s .c om*/
    //        props.put(StreamsConfig.APPLICATION_ID_CONFIG, "kafka-benchmarks");
    //        props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    ////        props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, Serdes.String().getClass().getName());

    // 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");

    source1
            // Parse the String as JSON
            .mapValues(input -> {
                JSONObject obj = new JSONObject(input.toString());
                //System.out.println(obj.toString());
                String[] tuple = { obj.getString("user_id"), obj.getString("page_id"), obj.getString("ad_id"),
                        obj.getString("ad_type"), obj.getString("event_type"), obj.getString("event_time"),
                        obj.getString("ip_address") };
                return tuple;
            })

            // Filter the records if event type is "view"
            .filter(new Predicate<String, String[]>() {
                @Override
                public boolean test(String key, String[] value) {
                    return value[4].equals("view"); // "event_type"
                }
            })

            // project the event
            .mapValues(input -> {
                String[] arr = (String[]) input;
                return new String[] { arr[2], arr[5] }; // "ad_id" and "event_time"
            })

            // perform join with redis data
            .transformValues(new RedisJoinBolt(benchmarkParams)).filter((key, value) -> value != null)

            // create key from value
            .map((key, value) -> {
                String[] arr = (String[]) value;
                return new KeyValue<String, String[]>(arr[0], arr);
            })

            // process campaign
            .aggregateByKey(new Initializer<List<String[]>>() {
                @Override
                public List<String[]> apply() {
                    return new ArrayList<String[]>();
                }
            }, new Aggregator<String, String[], List<String[]>>() {
                @Override
                public List<String[]> apply(String aggKey, String[] value, List<String[]> aggregate) {
                    aggregate.add(value);
                    return aggregate;
                }
            },
                    // UnlimitedWindows.of("kafka-test-unlim"),
                    // HoppingWindows.of("kafka-test-hopping").with(12L).every(5L),
                    TumblingWindows.of("kafka-test-tumbling").with(WINDOW_SIZE), strSerde, arrSerde)
            .toStream().process(new CampaignProcessor(benchmarkParams));

    KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
}

From source file:com.anjlab.sat3.Program.java

public static void main(String[] args) throws Exception {
    System.out.println("Reference Implementation of Romanov's Polynomial Algorithm for 3-SAT Problem"
            + "\nCopyright (c) 2010 AnjLab" + "\nThis program comes with ABSOLUTELY NO WARRANTY."
            + "\nThis is free software, and you are welcome to redistribute it under certain conditions."
            + "\nSee LICENSE.txt file or visit <http://www.gnu.org/copyleft/lesser.html> for details.");

    LOGGER.debug("Reading version number from manifest");
    String implementationVersion = Helper.getImplementationVersionFromManifest("3-SAT Core RI");
    System.out.println("Version: " + implementationVersion + "\n");

    Options options = getCommandLineOptions();

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine = parser.parse(options, args);

    if (commandLine.getArgs().length != 1 || commandLine.hasOption(HELP_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(Program.class.getName() + " [OPTIONS] <input-file-name>"
                + "\nWhere <input-file-name> is a path to file containing k-SAT formula instance in DIMACS CNF or Romanov SKT file format.",
                options);//from  w w  w. ja  v a 2  s  .c o  m
        System.exit(0);
    }

    String formulaFile = commandLine.getArgs()[0];

    Helper.UsePrettyPrint = commandLine.hasOption(USE_PRETTY_PRINT_OPTION);
    Helper.EnableAssertions = !commandLine.hasOption(DISABLE_ASSERTIONS_OPTION);
    Helper.UseUniversalVarNames = !commandLine.hasOption(USE_ABC_VAR_NAMES_OPTION);

    Properties statistics = new Properties();
    StopWatch stopWatch = new StopWatch();

    try {
        statistics.put(Helper.IMPLEMENTATION_VERSION, implementationVersion);

        stopWatch.start("Load formula");
        ITabularFormula formula = Helper.loadFromFile(formulaFile);
        long timeElapsed = stopWatch.stop();

        statistics.put(Helper.INITIAL_FORMULA_LOAD_TIME, String.valueOf(timeElapsed));

        if (commandLine.hasOption(GENERATE_3SAT_OPTION)) {
            String generated3SatFilename = formulaFile + "-3sat.cnf";

            LOGGER.info("Saving 3-SAT formula to {}...", generated3SatFilename);
            Helper.saveToDIMACSFileFormat(formula, generated3SatFilename);
        }

        if (formula.getVarCount() > 26) {
            LOGGER.info("Variables count > 26 => force using universal names for variables.");
            Helper.UseUniversalVarNames = true;
        }

        statistics.put(Helper.INITIAL_FORMULA_VAR_COUNT, String.valueOf(formula.getVarCount()));
        statistics.put(Helper.INITIAL_FORMULA_CLAUSES_COUNT, String.valueOf(formula.getClausesCount()));

        Helper.prettyPrint(formula);
        stopWatch.printElapsed();

        if (commandLine.hasOption(FIND_HSS_ROUTE_OPTION)) {
            String hssPath = commandLine.getOptionValue(FIND_HSS_ROUTE_OPTION);

            stopWatch.start("Load HSS from " + hssPath);
            ObjectArrayList hss = Helper.loadHSS(hssPath);
            stopWatch.stop();
            stopWatch.printElapsed();

            findHSSRoute(commandLine, formulaFile, statistics, stopWatch, formula, null, null, hss, hssPath);

            return;
        }

        if (commandLine.hasOption(EVALUATE_OPTION)) {
            String resultsFilename = commandLine.getOptionValue(EVALUATE_OPTION);
            boolean satisfiable = evaluateFormula(stopWatch, formula, resultsFilename);
            if (satisfiable) {
                System.out.println("Formula evaluated as SAT");
            } else {
                System.out.println("Formula evaluated as UNSAT");
            }
            //  Only evaluate formula value
            return;
        }

        //  Find if formula is SAT

        //  Clone initial formula to verify formula satisfiability later
        ITabularFormula formulaClone = null;
        if (Helper.EnableAssertions) {
            stopWatch.start("Clone initial formula");
            formulaClone = formula.clone();
            stopWatch.stop();
            stopWatch.printElapsed();
        }

        stopWatch.start("Create CTF");
        ObjectArrayList ct = Helper.createCTF(formula);
        timeElapsed = stopWatch.stop();
        printFormulas(ct);
        stopWatch.printElapsed();

        statistics.put(Helper.CTF_CREATION_TIME, String.valueOf(timeElapsed));
        statistics.put(Helper.CTF_COUNT, String.valueOf(ct.size()));

        LOGGER.info("CTF count: {}", ct.size());

        if (Helper.EnableAssertions) {
            assertNoTripletsLost(formula, ct);
        }

        //  Clone CTF to verify formula satisfiability against it later
        ObjectArrayList ctfClone = null;

        if (Helper.EnableAssertions) {
            ctfClone = Helper.cloneStructures(ct);
        }

        stopWatch.start("Create CTS");
        Helper.completeToCTS(ct, formula.getPermutation());
        timeElapsed = stopWatch.stop();
        printFormulas(ct);
        stopWatch.printElapsed();

        statistics.put(Helper.CTS_CREATION_TIME, String.valueOf(timeElapsed));

        if (commandLine.hasOption(CREATE_SKT_OPTION)) {
            String sktFilename = formulaFile + ".skt";
            stopWatch.start("Convert CTS to " + sktFilename);
            Helper.convertCTStructuresToRomanovSKTFileFormat(ct, sktFilename);
            stopWatch.stop();
            stopWatch.printElapsed();

            return;
        }

        ObjectArrayList hss = unifyAndCreateHSS(statistics, stopWatch, ct);

        String hssPath = formulaFile + "-hss";
        stopWatch.start("Save HSS to " + hssPath + "...");
        Helper.saveHSS(hssPath, hss);
        stopWatch.stop();
        stopWatch.printElapsed();

        findHSSRoute(commandLine, formulaFile, statistics, stopWatch, formula, formulaClone, ctfClone, hss,
                hssPath);
    } catch (EmptyStructureException e) {
        stopWatch.stop();
        stopWatch.printElapsed();

        LOGGER.info("One of the structures was built empty", e);

        String resultsFilename = getResultsFilename(commandLine, formulaFile);
        stopWatch.start("Saving current statictics of calculations to " + resultsFilename);
        writeUnsatToFile(resultsFilename, statistics);
        stopWatch.stop();
        stopWatch.printElapsed();

        System.out.println("Formula not satisfiable");
    } finally {
        System.out.println("Program completed");
    }
}

From source file:edu.indiana.d2i.sloan.internal.StopVMSimulator.java

public static void main(String[] args) {
    StopVMSimulator simulator = new StopVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {/*from   w  w  w  .java  2s  .  c om*/
        CommandLine line = simulator.parseCommandLine(parser, args);
        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot stop VM when it is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform stop when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // stop VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM status file, i.e. set state to shutdown
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);

    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }

}

From source file:de.unileipzig.ub.indexer.App.java

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

    // create Options object
    Options options = new Options();

    options.addOption("h", "help", false, "display this help");

    options.addOption("f", "filename", true, "name of the JSON file whose content should be indexed");
    options.addOption("i", "index", true, "the name of the target index");
    options.addOption("d", "doctype", true, "the name of the doctype (title, local, ...)");

    options.addOption("t", "host", true, "elasticsearch hostname (default: 0.0.0.0)");
    options.addOption("p", "port", true, "transport port (that's NOT the http port, default: 9300)");
    options.addOption("c", "cluster", true, "cluster name (default: elasticsearch_mdma)");

    options.addOption("b", "bulksize", true, "number of docs sent in one request (default: 3000)");
    options.addOption("v", "verbose", false, "show processing speed while indexing");
    options.addOption("s", "status", false, "only show status of index for file");

    options.addOption("r", "repair", false, "attempt to repair recoverable inconsistencies on the go");
    options.addOption("e", "debug", false, "set logging level to debug");
    options.addOption("l", "logfile", true, "logfile - in not specified only log to stdout");

    options.addOption("m", "memcached", true, "host and port of memcached (default: localhost:11211)");
    options.addOption("z", "latest-flag-on", true,
            "enable latest flag according to field (within content, e.g. 001)");
    options.addOption("a", "flat", false, "flat-mode: do not check for inconsistencies");

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;/*from w w  w  .ja v a 2 s  . co  m*/

    try {
        cmd = parser.parse(options, args);
    } catch (ParseException ex) {
        logger.error(ex);
        System.exit(1);
    }

    // setup logging
    Properties systemProperties = System.getProperties();
    systemProperties.put("net.spy.log.LoggerImpl", "net.spy.memcached.compat.log.Log4JLogger");
    System.setProperties(systemProperties);
    Logger.getLogger("net.spy.memcached").setLevel(Level.ERROR);

    Properties props = new Properties();
    props.load(props.getClass().getResourceAsStream("/log4j.properties"));

    if (cmd.hasOption("debug")) {
        props.setProperty("log4j.logger.de.unileipzig", "DEBUG");
    }

    if (cmd.hasOption("logfile")) {
        props.setProperty("log4j.rootLogger", "INFO, stdout, F");
        props.setProperty("log4j.appender.F", "org.apache.log4j.FileAppender");
        props.setProperty("log4j.appender.F.File", cmd.getOptionValue("logfile"));
        props.setProperty("log4j.appender.F.layout", "org.apache.log4j.PatternLayout");
        props.setProperty("log4j.appender.F.layout.ConversionPattern", "%5p | %d | %F | %L | %m%n");
    }

    PropertyConfigurator.configure(props);

    InetAddress addr = InetAddress.getLocalHost();
    String memcachedHostAndPort = addr.getHostAddress() + ":11211";
    if (cmd.hasOption("m")) {
        memcachedHostAndPort = cmd.getOptionValue("m");
    }

    // setup caching
    try {
        if (memcachedClient == null) {
            memcachedClient = new MemcachedClient(
                    new ConnectionFactoryBuilder().setFailureMode(FailureMode.Cancel).build(),
                    AddrUtil.getAddresses("0.0.0.0:11211"));
            try {
                // give client and server 500ms
                Thread.sleep(300);
            } catch (InterruptedException ex) {
            }

            Collection availableServers = memcachedClient.getAvailableServers();
            logger.info(availableServers);
            if (availableServers.size() == 0) {
                logger.info("no memcached servers found");
                memcachedClient.shutdown();
                memcachedClient = null;
            } else {
                logger.info(availableServers.size() + " memcached server(s) detected, fine.");
            }
        }
    } catch (IOException ex) {
        logger.warn("couldn't create a connection, bailing out: " + ex.getMessage());
    }

    // process options

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("indexer", options, true);
        quit(0);
    }

    boolean verbose = false;
    if (cmd.hasOption("verbose")) {
        verbose = true;
    }

    // ES options
    String[] hosts = new String[] { "0.0.0.0" };
    int port = 9300;
    String clusterName = "elasticsearch_mdma";
    int bulkSize = 3000;

    if (cmd.hasOption("host")) {
        hosts = cmd.getOptionValues("host");
    }
    if (cmd.hasOption("port")) {
        port = Integer.parseInt(cmd.getOptionValue("port"));
    }
    if (cmd.hasOption("cluster")) {
        clusterName = cmd.getOptionValue("cluster");
    }
    if (cmd.hasOption("bulksize")) {
        bulkSize = Integer.parseInt(cmd.getOptionValue("bulksize"));
        if (bulkSize < 1 || bulkSize > 100000) {
            logger.error("bulksize must be between 1 and 100,000");
            quit(1);
        }
    }

    // ES Client
    final Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "elasticsearch_mdma")
            .build();
    final TransportClient client = new TransportClient(settings);
    for (String host : hosts) {
        client.addTransportAddress(new InetSocketTransportAddress(host, port));
    }

    if (cmd.hasOption("filename") && cmd.hasOption("index") && cmd.hasOption("doctype")) {

        final String filename = cmd.getOptionValue("filename");

        final File _file = new File(filename);
        if (_file.length() == 0) {
            logger.info(_file.getAbsolutePath() + " is empty, skipping");
            quit(0); // file is empty
        }

        // for flat mode: leave a stampfile beside the json to 
        // indicate previous successful processing
        File directory = new File(filename).getParentFile();
        File stampfile = new File(directory, DigestUtils.shaHex(filename) + ".indexed");

        long start = System.currentTimeMillis();
        long lineCount = 0;

        final String indexName = cmd.getOptionValue("index");
        final String docType = cmd.getOptionValue("doctype");
        BulkRequestBuilder bulkRequest = client.prepareBulk();

        try {
            if (cmd.hasOption("flat")) {
                // flat mode
                // .........
                if (stampfile.exists()) {
                    logger.info("SKIPPING, since it seems this file has already " + "been imported (found: "
                            + stampfile.getAbsolutePath() + ")");
                    quit(0);
                }
            } else {

                final String srcSHA1 = extractSrcSHA1(filename);

                logger.debug(filename + " srcsha1: " + srcSHA1);

                long docsInIndex = getIndexedRecordCount(client, indexName, srcSHA1);
                logger.debug(filename + " indexed: " + docsInIndex);

                long docsInFile = getLineCount(filename);
                logger.debug(filename + " lines: " + docsInFile);

                // in non-flat-mode, indexing would take care
                // of inconsistencies
                if (docsInIndex == docsInFile) {
                    logger.info("UP-TO DATE: " + filename + " (" + docsInIndex + ", " + srcSHA1 + ")");
                    client.close();
                    quit(0);
                }

                if (docsInIndex > 0) {
                    logger.warn("INCONSISTENCY DETECTED: " + filename + ": indexed:" + docsInIndex + " lines:"
                            + docsInFile);

                    if (!cmd.hasOption("r")) {
                        logger.warn(
                                "Please re-run indexer with --repair flag or delete residues first with: $ curl -XDELETE "
                                        + hosts[0] + ":9200/" + indexName
                                        + "/_query -d ' {\"term\" : { \"meta.srcsha1\" : \"" + srcSHA1
                                        + "\" }}'");
                        client.close();
                        quit(1);
                    } else {
                        logger.info("Attempting to clear residues...");
                        // attempt to repair once
                        DeleteByQueryResponse dbqr = client.prepareDeleteByQuery(indexName)
                                .setQuery(termQuery("meta.srcsha1", srcSHA1)).execute().actionGet();

                        Iterator<IndexDeleteByQueryResponse> it = dbqr.iterator();
                        long deletions = 0;
                        while (it.hasNext()) {
                            IndexDeleteByQueryResponse response = it.next();
                            deletions += 1;
                        }
                        logger.info("Deleted residues of " + filename);
                        logger.info("Refreshing [" + indexName + "]");
                        RefreshResponse refreshResponse = client.admin().indices()
                                .refresh(new RefreshRequest(indexName)).actionGet();

                        long indexedAfterDelete = getIndexedRecordCount(client, indexName, srcSHA1);
                        logger.info(indexedAfterDelete + " docs remained");
                        if (indexedAfterDelete > 0) {
                            logger.warn("Not all residues cleaned. Try to fix this manually: $ curl -XDELETE "
                                    + hosts[0] + ":9200/" + indexName
                                    + "/_query -d ' {\"term\" : { \"meta.srcsha1\" : \"" + srcSHA1 + "\" }}'");
                            quit(1);
                        } else {
                            logger.info("Residues are gone. Now trying to reindex: " + filename);
                        }
                    }
                }
            }

            logger.info("INDEXING-REQUIRED: " + filename);
            if (cmd.hasOption("status")) {
                quit(0);
            }

            HashSet idsInBatch = new HashSet();

            String idField = null;
            if (cmd.hasOption("z")) {
                idField = cmd.getOptionValue("z");
            }

            final FileReader fr = new FileReader(filename);
            final BufferedReader br = new BufferedReader(fr);

            String line;
            // one line is one document
            while ((line = br.readLine()) != null) {

                // "Latest-Flag" machine
                // This gets obsolete with a "flat" index
                if (cmd.hasOption("z")) {
                    // flag that indicates, whether the document
                    // about to be indexed will be the latest
                    boolean willBeLatest = true;

                    // check if there is a previous (lower meta.timestamp) document with 
                    // the same identifier (whatever that may be - queried under "content")
                    final String contentIdentifier = getContentIdentifier(line, idField);
                    idsInBatch.add(contentIdentifier);

                    // assumed in meta.timestamp
                    final Long timestamp = Long.parseLong(getTimestamp(line));

                    logger.debug("Checking whether record is latest (line: " + lineCount + ")");
                    logger.debug(contentIdentifier + ", " + timestamp);

                    // get all docs, which match the contentIdentifier
                    // by filter, which doesn't score
                    final TermFilterBuilder idFilter = new TermFilterBuilder("content." + idField,
                            contentIdentifier);
                    final TermFilterBuilder kindFilter = new TermFilterBuilder("meta.kind", docType);
                    final AndFilterBuilder afb = new AndFilterBuilder();
                    afb.add(idFilter).add(kindFilter);
                    final FilteredQueryBuilder fb = filteredQuery(matchAllQuery(), afb);

                    final SearchResponse searchResponse = client.prepareSearch(indexName)
                            .setSearchType(SearchType.DFS_QUERY_THEN_FETCH).setQuery(fb).setFrom(0)
                            .setSize(1200) // 3 years and 105 days assuming daily updates at the most
                            .setExplain(false).execute().actionGet();

                    final SearchHits searchHits = searchResponse.getHits();

                    logger.debug("docs with this id in the index: " + searchHits.getTotalHits());

                    for (final SearchHit hit : searchHits.getHits()) {
                        final String docId = hit.id();
                        final Map<String, Object> source = hit.sourceAsMap();
                        final Map meta = (Map) source.get("meta");
                        final Long docTimestamp = Long.parseLong(meta.get("timestamp").toString());
                        // if the indexed doc timestamp is lower the the current one, 
                        // remove any latest flag
                        if (timestamp >= docTimestamp) {
                            source.remove("latest");
                            final ObjectMapper mapper = new ObjectMapper();
                            // put the updated doc back
                            // IndexResponse response = 
                            client.prepareIndex(indexName, docType).setCreate(false).setId(docId)
                                    .setSource(mapper.writeValueAsBytes(source))
                                    .execute(new ActionListener<IndexResponse>() {
                                        public void onResponse(IndexResponse rspns) {
                                            logger.debug("Removed latest flag from " + contentIdentifier + ", "
                                                    + docTimestamp + ", " + hit.id() + " since (" + timestamp
                                                    + " > " + docTimestamp + ")");
                                        }

                                        public void onFailure(Throwable thrwbl) {
                                            logger.error("Could not remove flag from " + hit.id() + ", "
                                                    + contentIdentifier);
                                        }
                                    });
                            // .execute()
                            //.actionGet();
                        } else {
                            logger.debug("Doc " + hit.id() + " is newer (" + docTimestamp + ")");
                            willBeLatest = false;
                        }
                    }

                    if (willBeLatest) {
                        line = setLatestFlag(line);
                        logger.info("Setting latest flag on " + contentIdentifier + ", " + timestamp);
                    }

                    // end of latest-flag machine
                    // beware - this will be correct as long as there
                    // are no dups within one bulk!
                }

                bulkRequest.add(client.prepareIndex(indexName, docType).setSource(line));
                lineCount++;
                logger.debug("Added line " + lineCount + " to BULK");
                logger.debug(line);

                if (lineCount % bulkSize == 0) {

                    if (idsInBatch.size() != bulkSize && cmd.hasOption("z")) {
                        logger.error(
                                "This batch has duplications in the ID. That's not bad for the index, just makes the latest flag fuzzy");
                        logger.error(
                                "Bulk size was: " + bulkSize + ", but " + idsInBatch.size() + " IDs (only)");
                    }
                    idsInBatch.clear();

                    logger.debug("Issuing BULK request");

                    final long actionCount = bulkRequest.numberOfActions();
                    final BulkResponse bulkResponse = bulkRequest.execute().actionGet();
                    final long tookInMillis = bulkResponse.getTookInMillis();

                    if (bulkResponse.hasFailures()) {
                        logger.fatal("FAILED, bulk not indexed. exiting now.");
                        Iterator<BulkItemResponse> it = bulkResponse.iterator();
                        while (it.hasNext()) {
                            BulkItemResponse bir = it.next();
                            if (bir.isFailed()) {
                                Failure failure = bir.getFailure();
                                logger.fatal("id: " + failure.getId() + ", message: " + failure.getMessage()
                                        + ", type: " + failure.getType() + ", index: " + failure.getIndex());
                            }
                        }
                        quit(1);
                    } else {
                        if (verbose) {
                            final double elapsed = System.currentTimeMillis() - start;
                            final double speed = (lineCount / elapsed * 1000);
                            logger.info("OK (" + filename + ") " + lineCount + " docs indexed (" + actionCount
                                    + "/" + tookInMillis + "ms" + "/" + String.format("%.2f", speed) + "r/s)");
                        }
                    }
                    bulkRequest = client.prepareBulk();
                }
            }

            // handle the remaining items
            final long actionCount = bulkRequest.numberOfActions();
            if (actionCount > 0) {
                final BulkResponse bulkResponse = bulkRequest.execute().actionGet();
                final long tookInMillis = bulkResponse.getTookInMillis();

                if (bulkResponse.hasFailures()) {
                    logger.fatal("FAILED, bulk not indexed. exiting now.");
                    Iterator<BulkItemResponse> it = bulkResponse.iterator();
                    while (it.hasNext()) {
                        BulkItemResponse bir = it.next();
                        if (bir.isFailed()) {
                            Failure failure = bir.getFailure();
                            logger.fatal("id: " + failure.getId() + ", message: " + failure.getMessage()
                                    + ", type: " + failure.getType() + ", index: " + failure.getIndex());
                        }
                    }
                    quit(1);
                } else {

                    // trigger update now
                    RefreshResponse refreshResponse = client.admin().indices()
                            .refresh(new RefreshRequest(indexName)).actionGet();

                    if (verbose) {
                        final double elapsed = System.currentTimeMillis() - start;
                        final double speed = (lineCount / elapsed * 1000);
                        logger.info("OK (" + filename + ") " + lineCount + " docs indexed (" + actionCount + "/"
                                + tookInMillis + "ms" + "/" + String.format("%.2f", speed) + "r/s)");
                    }

                }

            }

            br.close();
            client.close();
            final double elapsed = (System.currentTimeMillis() - start) / 1000;
            final double speed = (lineCount / elapsed);
            logger.info("indexing (" + filename + ") " + lineCount + " docs took " + elapsed + "s (speed: "
                    + String.format("%.2f", speed) + "r/s)");
            if (cmd.hasOption("flat")) {
                try {
                    FileUtils.touch(stampfile);
                } catch (IOException ioe) {
                    logger.warn(".indexed files not created. Will reindex everything everytime.");
                }
            }
        } catch (IOException e) {
            client.close();
            logger.error(e);
            quit(1);
        } finally {
            client.close();
        }
    }
    quit(0);
}

From source file:edu.indiana.d2i.sloan.internal.LaunchVMSimulator.java

/**
 * @param args/* w  w w.j a va  2 s  . co m*/
 */
public static void main(String[] args) {
    LaunchVMSimulator simulator = new LaunchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode vmmode = HypervisorCmdSimulator.getVMMode(mode);

        if (vmmode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM status info
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // can only launch VM when it is in shutdown state
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.SHUTDOWN)) {
            logger.error(String.format("Can only launch VM when it is in %s state, current VM state is %s",
                    VMState.SHUTDOWN.toString(), currentState.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_SHUTDOWN));
        }
        // launch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update VM state file

        // set following properties
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), vmmode.toString());

        // set VM state to running
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.RUNNING.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:com.marklogic.client.tutorial.util.Bootstrapper.java

/**
 * Command-line invocation.//from   ww w  . j a v a 2s.c  om
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args)
        throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Command-line invocation.//ww  w  .  j a v a 2s. co  m
 * @param args   command-line arguments specifying the configuration and REST server
 */
public static void main(String[] args) throws ClientProtocolException, IOException, FactoryConfigurationError {
    Properties properties = new Properties();
    for (int i = 0; i < args.length; i++) {
        String name = args[i];
        if (name.startsWith("-") && name.length() > 1 && ++i < args.length) {
            name = name.substring(1);
            if ("properties".equals(name)) {
                InputStream propsStream = Bootstrapper.class.getClassLoader().getResourceAsStream(name);
                if (propsStream == null)
                    throw new IOException("Could not read bootstrapper properties");
                Properties props = new Properties();
                props.load(propsStream);
                props.putAll(properties);
                properties = props;
            } else {
                properties.put(name, args[i]);
            }
        } else {
            System.err.println("invalid argument: " + name);
            System.err.println(getUsage());
            System.exit(1);
        }
    }

    String invalid = joinList(listInvalidKeys(properties));
    if (invalid != null && invalid.length() > 0) {
        System.err.println("invalid arguments: " + invalid);
        System.err.println(getUsage());
        System.exit(1);
    }

    // TODO: catch invalid argument exceptions and provide feedback
    new Bootstrapper().makeServer(properties);

    System.out.println("Created " + properties.getProperty("restserver") + " server on "
            + properties.getProperty("restport") + " port for " + properties.getProperty("restdb")
            + " database");
}

From source file:Gen.java

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

    try {//from   w w  w  .j  ava2s  . c  o m

        File[] files = null;
        if (System.getProperty("dir") != null && !System.getProperty("dir").equals("")) {
            files = new File(System.getProperty("dir")).listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.toUpperCase().endsWith(".XML");
                };
            });
        } else {
            String fileName = System.getProperty("file") != null && !System.getProperty("file").equals("")
                    ? System.getProperty("file")
                    : "rjmap.xml";
            files = new File[] { new File(fileName) };
        }

        log.info("files : " + Arrays.toString(files));

        if (files == null || files.length == 0) {
            log.info("no files to parse");
            System.exit(0);
        }

        boolean formatsource = true;
        if (System.getProperty("formatsource") != null && !System.getProperty("formatsource").equals("")
                && System.getProperty("formatsource").equalsIgnoreCase("false")) {
            formatsource = false;
        }

        GEN_ROOT = System.getProperty("outputdir");

        if (GEN_ROOT == null || GEN_ROOT.equals("")) {
            GEN_ROOT = new File(files[0].getAbsolutePath()).getParent() + FILE_SEPARATOR + "distrib";
        }

        GEN_ROOT = new File(GEN_ROOT).getAbsolutePath().replace('\\', '/');
        if (GEN_ROOT.endsWith("/"))
            GEN_ROOT = GEN_ROOT.substring(0, GEN_ROOT.length() - 1);

        System.out.println("GEN ROOT:" + GEN_ROOT);

        MAPPING_JAR_NAME = System.getProperty("mappingjar") != null
                && !System.getProperty("mappingjar").equals("") ? System.getProperty("mappingjar")
                        : "mapping.jar";
        if (!MAPPING_JAR_NAME.endsWith(".jar"))
            MAPPING_JAR_NAME += ".jar";

        GEN_ROOT_SRC = GEN_ROOT + FILE_SEPARATOR + "src";
        GEN_ROOT_LIB = GEN_ROOT + FILE_SEPARATOR + "";

        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setNamespaceAware(true);
        domFactory.setValidating(false);
        DocumentBuilder documentBuilder = domFactory.newDocumentBuilder();

        for (int f = 0; f < files.length; ++f) {
            log.info("parsing file : " + files[f]);
            Document document = documentBuilder.parse(files[f]);

            Vector<Node> initNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "initScript",
                    initNodes);
            for (int i = 0; i < initNodes.size(); ++i) {
                NamedNodeMap attrs = initNodes.elementAt(i).getAttributes();
                boolean embed = attrs.getNamedItem("embed") != null
                        && attrs.getNamedItem("embed").getNodeValue().equalsIgnoreCase("true");
                StringBuffer vbuffer = new StringBuffer();
                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue());
                    vbuffer.append('\n');
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    vbuffer.append(Utils.getFileAsStringBuffer(fname));
                }
                initScriptBuffer.append(vbuffer);
                if (embed)
                    embedScriptBuffer.append(vbuffer);
            }

            Vector<Node> packageInitNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "scripts"), "packageScript",
                    packageInitNodes);
            for (int i = 0; i < packageInitNodes.size(); ++i) {
                NamedNodeMap attrs = packageInitNodes.elementAt(i).getAttributes();
                String packageName = attrs.getNamedItem("package").getNodeValue();

                if (packageName.equals(""))
                    packageName = "rGlobalEnv";

                if (!packageName.endsWith("Function"))
                    packageName += "Function";
                if (packageEmbedScriptHashMap.get(packageName) == null) {
                    packageEmbedScriptHashMap.put(packageName, new StringBuffer());
                }
                StringBuffer vbuffer = packageEmbedScriptHashMap.get(packageName);

                // if (!packageName.equals("rGlobalEnvFunction")) {
                // vbuffer.append("library("+packageName.substring(0,packageName.lastIndexOf("Function"))+")\n");
                // }

                if (attrs.getNamedItem("inline") != null) {
                    vbuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                    initScriptBuffer.append(attrs.getNamedItem("inline").getNodeValue() + "\n");
                } else {
                    String fname = attrs.getNamedItem("name").getNodeValue();
                    if (!fname.startsWith("\\") && !fname.startsWith("/") && fname.toCharArray()[1] != ':') {
                        String path = files[f].getAbsolutePath();
                        path = path.substring(0, path.lastIndexOf(FILE_SEPARATOR));
                        fname = new File(path + FILE_SEPARATOR + fname).getCanonicalPath();
                    }
                    StringBuffer fileBuffer = Utils.getFileAsStringBuffer(fname);
                    vbuffer.append(fileBuffer);
                    initScriptBuffer.append(fileBuffer);
                }
            }

            Vector<Node> functionsNodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "functions"), "function",
                    functionsNodes);
            for (int i = 0; i < functionsNodes.size(); ++i) {
                NamedNodeMap attrs = functionsNodes.elementAt(i).getAttributes();
                String functionName = attrs.getNamedItem("name").getNodeValue();

                boolean forWeb = attrs.getNamedItem("forWeb") != null
                        && attrs.getNamedItem("forWeb").getNodeValue().equalsIgnoreCase("true");

                String signature = (attrs.getNamedItem("signature") == null ? ""
                        : attrs.getNamedItem("signature").getNodeValue() + ",");
                String renameTo = (attrs.getNamedItem("renameTo") == null ? null
                        : attrs.getNamedItem("renameTo").getNodeValue());

                HashMap<String, FAttributes> sigMap = Globals._functionsToPublish.get(functionName);

                if (sigMap == null) {
                    sigMap = new HashMap<String, FAttributes>();
                    Globals._functionsToPublish.put(functionName, sigMap);

                    if (attrs.getNamedItem("returnType") == null) {
                        _functionsVector.add(new String[] { functionName });
                    } else {
                        _functionsVector.add(
                                new String[] { functionName, attrs.getNamedItem("returnType").getNodeValue() });
                    }

                }

                sigMap.put(signature, new FAttributes(renameTo, forWeb));

                if (forWeb)
                    _webPublishingEnabled = true;

            }

            if (System.getProperty("targetjdk") != null && !System.getProperty("targetjdk").equals("")
                    && System.getProperty("targetjdk").compareTo("1.5") < 0) {
                if (_webPublishingEnabled || (System.getProperty("ws.r.api") != null
                        && System.getProperty("ws.r.api").equalsIgnoreCase("true"))) {
                    log.info("be careful, web publishing disabled beacuse target JDK<1.5");
                }
                _webPublishingEnabled = false;
            } else {

                if (System.getProperty("ws.r.api") == null || System.getProperty("ws.r.api").equals("")
                        || !System.getProperty("ws.r.api").equalsIgnoreCase("false")) {
                    _webPublishingEnabled = true;
                }

                if (_webPublishingEnabled && System.getProperty("java.version").compareTo("1.5") < 0) {
                    log.info("be careful, web publishing disabled beacuse a JDK<1.5 is in use");
                    _webPublishingEnabled = false;
                }
            }

            Vector<Node> s4Nodes = new Vector<Node>();
            Utils.catchNodes(Utils.catchNode(document.getDocumentElement(), "s4classes"), "class", s4Nodes);

            if (s4Nodes.size() > 0) {
                String formalArgs = "";
                String signature = "";
                for (int i = 0; i < s4Nodes.size(); ++i) {
                    NamedNodeMap attrs = s4Nodes.elementAt(i).getAttributes();
                    String s4Name = attrs.getNamedItem("name").getNodeValue();
                    formalArgs += "p" + i + (i == s4Nodes.size() - 1 ? "" : ",");
                    signature += "'" + s4Name + "'" + (i == s4Nodes.size() - 1 ? "" : ",");
                }
                String genBeansScriptlet = "setGeneric('" + PUBLISH_S4_HEADER + "', function(" + formalArgs
                        + ") standardGeneric('" + PUBLISH_S4_HEADER + "'));" + "setMethod('" + PUBLISH_S4_HEADER
                        + "', signature(" + signature + ") , function(" + formalArgs + ") {   })";
                initScriptBuffer.append(genBeansScriptlet);
                _functionsVector.add(new String[] { PUBLISH_S4_HEADER, "numeric" });
            }

        }

        if (!new File(GEN_ROOT_LIB).exists())
            regenerateDir(GEN_ROOT_LIB);
        else {
            clean(GEN_ROOT_LIB, true);
        }

        for (int i = 0; i < rwebservicesScripts.length; ++i)
            DirectJNI.getInstance().getRServices().sourceFromResource(rwebservicesScripts[i]);

        String lastStatus = DirectJNI.getInstance().runR(new ExecutionUnit() {
            public void run(Rengine e) {
                DirectJNI.getInstance().toggleMarker();
                DirectJNI.getInstance().sourceFromBuffer(initScriptBuffer.toString());
                log.info(" init  script status : " + DirectJNI.getInstance().cutStatusSinceMarker());

                for (int i = 0; i < _functionsVector.size(); ++i) {

                    String[] functionPair = _functionsVector.elementAt(i);
                    log.info("dealing with : " + functionPair[0]);

                    regenerateDir(GEN_ROOT_SRC);

                    String createMapStr = "createMap(";
                    boolean isGeneric = e.rniGetBoolArrayI(
                            e.rniEval(e.rniParse("isGeneric(\"" + functionPair[0] + "\")", 1), 0))[0] == 1;

                    log.info("is Generic : " + isGeneric);
                    if (isGeneric) {
                        createMapStr += functionPair[0];
                    } else {
                        createMapStr += "\"" + functionPair[0] + "\"";
                    }
                    createMapStr += ", outputDirectory=\"" + GEN_ROOT_SRC
                            .substring(0, GEN_ROOT_SRC.length() - "/src".length()).replace('\\', '/') + "\"";
                    createMapStr += ", typeMode=\"robject\"";
                    createMapStr += (functionPair.length == 1 || functionPair[1] == null
                            || functionPair[1].trim().equals("") ? ""
                                    : ", S4DefaultTypedSig=TypedSignature(returnType=\"" + functionPair[1]
                                            + "\")");
                    createMapStr += ")";

                    log.info("------------------------------------------");
                    log.info("-- createMapStr=" + createMapStr);
                    DirectJNI.getInstance().toggleMarker();
                    e.rniEval(e.rniParse(createMapStr, 1), 0);
                    String createMapStatus = DirectJNI.getInstance().cutStatusSinceMarker();
                    log.info(" createMap status : " + createMapStatus);
                    log.info("------------------------------------------");

                    deleteDir(GEN_ROOT_SRC + "/org/kchine/r/rserviceJms");
                    compile(GEN_ROOT_SRC);
                    jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", null);

                    URL url = null;
                    try {
                        url = new URL(
                                "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar")
                                        .replace('\\', '/') + "!/");
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                    DirectJNI.generateMaps(url, true);
                }

            }
        });

        log.info(lastStatus);

        log.info(DirectJNI._rPackageInterfacesHash);
        regenerateDir(GEN_ROOT_SRC);
        for (int i = 0; i < _functionsVector.size(); ++i) {
            unjar(GEN_ROOT_LIB + FILE_SEPARATOR + TEMP_JARS_PREFIX + i + ".jar", GEN_ROOT_SRC);
        }

        regenerateRPackageClass(true);

        generateS4BeanRef();

        if (formatsource)
            applyJalopy(GEN_ROOT_SRC);

        compile(GEN_ROOT_SRC);

        for (String k : DirectJNI._rPackageInterfacesHash.keySet()) {
            Rmic rmicTask = new Rmic();
            rmicTask.setProject(_project);
            rmicTask.setTaskName("rmic_packages");
            rmicTask.setClasspath(new Path(_project, GEN_ROOT_SRC));
            rmicTask.setBase(new File(GEN_ROOT_SRC));
            rmicTask.setClassname(k + "ImplRemote");
            rmicTask.init();
            rmicTask.execute();
        }

        // DirectJNI._rPackageInterfacesHash=new HashMap<String,
        // Vector<Class<?>>>();
        // DirectJNI._rPackageInterfacesHash.put("org.bioconductor.packages.rGlobalEnv.rGlobalEnvFunction",new
        // Vector<Class<?>>());

        if (_webPublishingEnabled) {

            jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar", null);
            URL url = new URL(
                    "jar:file:" + (GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").replace('\\', '/') + "!/");
            ClassLoader cl = new URLClassLoader(new URL[] { url }, Globals.class.getClassLoader());

            for (String className : DirectJNI._rPackageInterfacesHash.keySet()) {
                if (cl.loadClass(className + "Web").getDeclaredMethods().length == 0)
                    continue;
                log.info("######## " + className);

                WsGen wsgenTask = new WsGen();
                wsgenTask.setProject(_project);
                wsgenTask.setTaskName("wsgen");

                FileSet rjb_fileSet = new FileSet();
                rjb_fileSet.setProject(_project);
                rjb_fileSet.setDir(new File("."));
                rjb_fileSet.setIncludes("RJB.jar");

                DirSet src_dirSet = new DirSet();
                src_dirSet.setDir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                Path classPath = new Path(_project);
                classPath.addFileset(rjb_fileSet);
                classPath.addDirset(src_dirSet);
                wsgenTask.setClasspath(classPath);
                wsgenTask.setKeep(true);
                wsgenTask.setDestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setResourcedestdir(new File(GEN_ROOT_LIB + FILE_SEPARATOR + "src/"));
                wsgenTask.setSei(className + "Web");

                wsgenTask.init();
                wsgenTask.execute();
            }

            new File(GEN_ROOT_LIB + FILE_SEPARATOR + "__temp.jar").delete();

        }

        embedRScripts();

        HashMap<String, String> marker = new HashMap<String, String>();
        marker.put("RJBMAPPINGJAR", "TRUE");

        Properties props = new Properties();
        props.put("PACKAGE_NAMES", PoolUtils.objectToHex(DirectJNI._packageNames));
        props.put("S4BEANS_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMapping));
        props.put("S4BEANS_REVERT_MAP", PoolUtils.objectToHex(DirectJNI._s4BeansMappingRevert));
        props.put("FACTORIES_MAPPING", PoolUtils.objectToHex(DirectJNI._factoriesMapping));
        props.put("S4BEANS_HASH", PoolUtils.objectToHex(DirectJNI._s4BeansHash));
        props.put("R_PACKAGE_INTERFACES_HASH", PoolUtils.objectToHex(DirectJNI._rPackageInterfacesHash));
        props.put("ABSTRACT_FACTORIES", PoolUtils.objectToHex(DirectJNI._abstractFactories));
        new File(GEN_ROOT_SRC + "/" + "maps").mkdirs();
        FileOutputStream fos = new FileOutputStream(GEN_ROOT_SRC + "/" + "maps/rjbmaps.xml");
        props.storeToXML(fos, null);
        fos.close();

        jar(GEN_ROOT_SRC, GEN_ROOT_LIB + FILE_SEPARATOR + MAPPING_JAR_NAME, marker);

        if (_webPublishingEnabled)
            genWeb();

        DirectJNI._mappingClassLoader = null;

    } finally {

        System.exit(0);

    }
}

From source file:edu.indiana.d2i.sloan.internal.SwitchVMSimulator.java

/**
 * @param args//from  w  w w  .j a va2s. co m
 */
public static void main(String[] args) {
    SwitchVMSimulator simulator = new SwitchVMSimulator();

    CommandLineParser parser = new PosixParser();

    try {
        CommandLine line = simulator.parseCommandLine(parser, args);

        String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR));
        String mode = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE));
        String policyFilePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH));

        if (!HypervisorCmdSimulator.resourceExist(wdir)) {
            logger.error(String.format("Cannot find VM working dir: %s", wdir));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_EXIST));
        }

        VMMode requestedMode = HypervisorCmdSimulator.getVMMode(mode);

        if (requestedMode == null) {
            logger.error(String.format("Invalid requested mode: %s, can only be %s or %s", mode,
                    VMMode.MAINTENANCE.toString(), VMMode.SECURE.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_VM_MODE));
        }

        if (!HypervisorCmdSimulator.resourceExist(policyFilePath)) {
            logger.error(String.format("Cannot find plicy file: %s", policyFilePath));
            System.exit(ERROR_CODE.get(ERROR_STATE.FIREWALL_POLICY_NOT_EXIST));
        }

        // load VM state file
        Properties prop = new Properties();
        String filename = HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME;

        prop.load(new FileInputStream(new File(filename)));

        // cannot switch when VM is not running
        VMState currentState = VMState.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE)));

        if (!currentState.equals(VMState.RUNNING)) {
            logger.error("Cannot perform switch when VM is not running");
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_NOT_RUNNING));
        }

        // get current mode
        VMMode currentMode = VMMode.valueOf(prop.getProperty(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE)));

        if (currentMode.equals(requestedMode)) {
            logger.error(String.format("VM is already in the requested mode: %s", requestedMode.toString()));
            System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_IN_REQUESTED_MODE));
        }

        // switch VM
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.error(e.getMessage());
        }

        // update firewall policy
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.POLICY_PATH), policyFilePath);

        // update VM status file, i.e. set mode to the requested mode
        prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), requestedMode.toString());

        // save VM state file back
        prop.store(new FileOutputStream(new File(filename)), "");

        // success
        System.exit(0);
    } catch (ParseException e) {
        logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s",
                StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, "")));

        System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS));
    } catch (FileNotFoundException e) {
        logger.error(String.format("Cannot find vm state file: %s", e.getMessage()));

        System.exit(ERROR_CODE.get(ERROR_STATE.VM_STATE_FILE_NOT_FOUND));
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR));
    }
}

From source file:TerminalMonitor.java

static public void main(String args[]) {
    DriverPropertyInfo[] required;
    StringBuffer buffer = new StringBuffer();
    Properties props = new Properties();
    boolean connected = false;
    Driver driver;/*from  w  w  w. j ava2s  .c o m*/
    String url;
    int line = 1; // Mark current input line

    if (args.length < 1) {
        System.out.println("Syntax: <java -Djdbc.drivers=DRIVER_NAME " + "TerminalMonitor JDBC_URL>");
        return;
    }
    url = args[0];
    // We have to get a reference to the driver so we can
    // find out what values to prompt the user for in order
    // to make a connection.
    try {
        driver = DriverManager.getDriver(url);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to find a driver for the specified " + "URL.");
        System.err.println("Make sure you passed the jdbc.drivers " + "property on the command line to specify "
                + "the driver to be used.");
        return;
    }
    try {
        required = driver.getPropertyInfo(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to get driver property information.");
        return;
    }
    input = new BufferedReader(new InputStreamReader(System.in));
    // some drivers do not implement this properly
    // if that is the case, prompt for user name and password
    try {
        if (required.length < 1) {
            props.put("user", prompt("user: "));
            props.put("password", prompt("password: "));
        } else {
            // for each required attribute in the driver property info
            // prompt the user for the value
            for (int i = 0; i < required.length; i++) {
                if (!required[i].required) {
                    continue;
                }
                props.put(required[i].name, prompt(required[i].name + ": "));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Unable to read property info.");
        return;
    }
    // Make the connection.
    try {
        connection = DriverManager.getConnection(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to connect to the database.");
    }
    connected = true;
    System.out.println("Connected to " + url);
    // Enter into a user input loop
    while (connected) {
        String tmp, cmd;

        // Print a prompt
        if (line == 1) {
            System.out.print("TM > ");
        } else {
            System.out.print(line + " -> ");
        }
        System.out.flush();
        // Get the next line of input
        try {
            tmp = input.readLine();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return;
        }
        // Get rid of extra space in the command
        cmd = tmp.trim();
        // The user wants to commit pending transactions
        if (cmd.equals("commit")) {
            try {
                connection.commit();
                System.out.println("Commit successful.");
            } catch (SQLException e) {
                System.out.println("Error in commit: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants to execute the current buffer
        else if (cmd.equals("go")) {
            if (!buffer.equals("")) {
                try {
                    executeStatement(buffer);
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to quit
        else if (cmd.equals("quit")) {
            connected = false;
            continue;
        }
        // The user wants to clear the current buffer
        else if (cmd.equals("reset")) {
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to abort a pending transaction
        else if (cmd.equals("rollback")) {
            try {
                connection.rollback();
                System.out.println("Rollback successful.");
            } catch (SQLException e) {
                System.out.println("An error occurred during rollback: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants version info
        else if (cmd.startsWith("show")) {
            DatabaseMetaData meta;

            try {
                meta = connection.getMetaData();
                cmd = cmd.substring(5, cmd.length()).trim();
                if (cmd.equals("version")) {
                    showVersion(meta);
                } else {
                    System.out.println("show version"); // Bad arg
                }
            } catch (SQLException e) {
                System.out.println("Failed to load meta data: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The input that is not a keyword should appended be to the buffer
        else {
            buffer.append(" " + tmp);
            line++;
            continue;
        }
    }
    try {
        connection.close();
    } catch (SQLException e) {
        System.out.println("Error closing connection: " + e.getMessage());
    }
    System.out.println("Connection closed.");
}