Example usage for java.lang System currentTimeMillis

List of usage examples for java.lang System currentTimeMillis

Introduction

In this page you can find the example usage for java.lang System currentTimeMillis.

Prototype

@HotSpotIntrinsicCandidate
public static native long currentTimeMillis();

Source Link

Document

Returns the current time in milliseconds.

Usage

From source file:com.datastax.dse.demos.solr.Wikipedia.java

public static void main(String[] args) {

    if (args.length == 0)
        usage();/*from   w  ww .  j ava  2  s.  c  o  m*/

    System.out.println("args: " + Arrays.asList(args));

    // parse args
    for (int i = 0; i < args.length; i = i + 2) {

        if (args[i].startsWith("--")) {
            try {
                String arg = args[i].substring(2);
                String value = args[i + 1];

                if (arg.equalsIgnoreCase("wikifile"))
                    wikifile = value;
                if (arg.equalsIgnoreCase("limit"))
                    limit = Integer.parseInt(value);
                if (arg.equalsIgnoreCase("host"))
                    host = value;
                if (arg.equalsIgnoreCase("scheme"))
                    scheme = value;
                if (arg.equalsIgnoreCase("user"))
                    user = value;
                if (arg.equalsIgnoreCase("password"))
                    password = value;
            } catch (Throwable t) {
                usage();
            }
        }
    }
    url = String.format(urlTemplate, scheme, host);
    // Initialize Solr with our custom HTTP Client helpers - which handle
    // SSL & Kerberos. We must have dse.yaml on the classpath for this
    try {
        if (DseConfig.isSslEnabled()) {
            SolrHttpClientInitializer
                    .initEncryption(new EncryptionOptions().withSSLContext(DseConfig.getSSLContext())
                            .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
        }

        if (DseConfig.isKerberosEnabled()) {
            // Obtain kerberos credentials from local ticket cache
            AuthenticationOptions options = new AuthenticationOptions();
            if (DseConfig.isSslEnabled()) {
                options.withSSLContext(DseConfig.getSSLContext())
                        .withHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            }

            SolrHttpClientInitializer.initAuthentication(options);
        }
    } catch (Exception e) {
        System.out.println("Fatal error when initializing Solr clients, exiting");
        e.printStackTrace();
        System.exit(1);
    }

    System.out.println("Start indexing wikipedia...");
    long startTime = System.currentTimeMillis();

    indexWikipedia();

    long endTime = System.currentTimeMillis();

    System.out.println("Finished");

    System.exit(0);

}

From source file:at.illecker.hama.rootbeer.examples.pagerank.cpu.PageRankCpu.java

public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
    if (args.length < 2)
        printUsage();//from w w w  .j  av  a2 s  . c o  m

    HamaConfiguration conf = new HamaConfiguration();
    GraphJob pageJob = createJob(args, conf);

    long startTime = System.currentTimeMillis();
    if (pageJob.waitForCompletion(true)) {
        System.out.println("Job Finished in " + (System.currentTimeMillis() - startTime) / 1000.0 + " seconds");
    }
}

From source file:amie.keys.CombinationsExplorationNew.java

public static void main(String[] args) throws IOException {
    CommandLine cli = parseArguments(args);

    // We get a map with the properties and their number of subjects
    propertiesSupport = kb.frequentBindingsOf(ByteString.of("?p"), ByteString.of("?s"),
            KB.triples(KB.triple("?s", "?p", "?o")));
    // Helper object that contains the implementation for the calculation
    // of confidence and support
    numberOfInstances = kb.size(Column.Subject);
    miningHelper = new DefaultMiningAssistant(kb);
    // The file with the non-keys, one per line
    List<List<String>> nonKeys = new ArrayList<>();
    for (List<String> nonKey : Utilities.parseNonKeysFile(cli.getOptionValue("nk"))) {
        if (nonKey.size() > 1) {
            nonKeys.add(nonKey);// w ww. j a  v  a 2 s  .com
        }
    }
    System.out.println("nonKeys" + nonKeys);
    // for(List<String> nonKey:nonKeys){
    //     System.out.println(nonKey);
    //}
    long timea = System.currentTimeMillis();
    // System.out.println("nonKeys:"+nonKeys);
    // We map the non-keys to an integer space
    nonKeysInt = buildDictionaries(nonKeys, propertiesList);
    //   System.out.println(nonKeysInt.size() + " => nonKeysInt:" + nonKeysInt);
    //System.out.println("prop:"+property2Id);
    System.out.println("Dictionaries built");
    // We discover the conditional keys
    discoverConditionalKeys();
    long timeb = System.currentTimeMillis();
    System.out.println("Total time in ms: " + (timeb - timea));
}

From source file:edu.xiyou.fruits.WebCrawler.fetcher.Fetcher.java

public static void main(String[] args) {
    Scheduler scheduler1 = new BloomScheduler();
    scheduler1.putTasks(Arrays.asList("http://www.importnew.com/all-posts", "http://blog.csdn.net/"));
    Fetcher fetcher = new Fetcher(scheduler1, new Handler() {
        @Override//from  ww  w .  jav  a2s  .  co  m
        public void onSuccess(Response response) {
            //                System.out.println(((Html) response).getUrl() + response.getStatusLine());
            //                System.out.println(new String(((Html)response).getContent()));
            String path = "/home/andrew/Data/";
            String fileName = path + System.currentTimeMillis();
            try {
                FileUtils.write2File(new File(fileName), ((Html) response).getContent());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFail(Response response) {

        }

        @Override
        public List<String> handleAndGetLinks(Response response) {
            LinksList list = new LinksList();
            RegexRule regexRule = new RegexRule();
            regexRule.addPositive(Arrays.asList("http://blog.csdn.net/\\w+/article/details/\\d+",
                    "http://www.importnew.com/\\d+.html", "http://blog.csdn.net/?&page=\\d+"));
            list.getLinkByA(Jsoup.parse(new String(response.getContent())), regexRule);
            return list;
        }
    }, 0);

    //        try {
    //            System.out.println(scheduler1.takeTasks());
    //        } catch (InterruptedException e) {
    //            logger.error(e.getMessage() + "bbbbbbbbbbbbbb");
    //        }
    fetcher.fetch();
}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);//from ww w.j a  v  a  2 s  .  c o m
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:is.landsbokasafn.deduplicator.indexer.IndexingLauncher.java

public static void main(String[] args) throws Exception {
    loadConfiguration();//from w  w  w  .jav  a 2 s  .  c  om

    // Set default values for all settings
    boolean verbose = readBooleanConfig(VERBOSE_CONF_KEY, true);
    boolean etag = readBooleanConfig(ETAG_CONF_KEY, false);
    boolean canonical = readBooleanConfig(CANONICAL_CONF_KEY, true);
    boolean indexURL = readBooleanConfig(INDEX_URL_KEY, true);
    boolean addToIndex = readBooleanConfig(ADD_TO_INDEX_CONF_KEY, false);
    String mimefilter = readStringConfig(MIME_CONF_KEY, "^text/.*");
    boolean whitelist = readBooleanConfig(WHITELIST_CONF_KEY, false);
    String iteratorClassName = readStringConfig(ITERATOR_CONF_KEY, WarcIterator.class.getName());

    // Parse command line options       
    CommandLineParser clp = new CommandLineParser(args, new PrintWriter(System.out));
    Option[] opts = clp.getCommandLineOptions();
    for (int i = 0; i < opts.length; i++) {
        Option opt = opts[i];
        switch (opt.getId()) {
        case 'w':
            whitelist = true;
            break;
        case 'a':
            addToIndex = true;
            break;
        case 'e':
            etag = true;
            break;
        case 'h':
            clp.usage(0);
            break;
        case 'i':
            iteratorClassName = opt.getValue();
            break;
        case 'm':
            mimefilter = opt.getValue();
            break;
        case 'u':
            indexURL = false;
            break;
        case 's':
            canonical = false;
            break;
        case 'v':
            verbose = true;
            break;
        }
    }

    if (!indexURL && canonical) {
        canonical = false;
    }

    List<String> cargs = clp.getCommandLineArguments();
    if (cargs.size() != 2) {
        // Should be exactly two arguments. Source and target!
        clp.usage(0);
    }

    String source = cargs.get(0);
    String target = cargs.get(1);

    // Load the CrawlDataIterator
    CrawlDataIterator iterator = (CrawlDataIterator) Class.forName(iteratorClassName).newInstance();

    // Print initial stuff
    System.out.println("Indexing: " + source);
    System.out.println(" - Index URL: " + indexURL);
    System.out.println(" - Mime filter: " + mimefilter + " (" + (whitelist ? "whitelist" : "blacklist") + ")");
    System.out.println(" - Includes" + (canonical ? " <canonical URL>" : "") + (etag ? " <etag>" : ""));
    System.out.println(" - Iterator: " + iteratorClassName);
    System.out.println("   - " + iterator.getSourceType());
    System.out.println("Target: " + target);
    if (addToIndex) {
        System.out.println(" - Add to existing index (if any)");
    } else {
        System.out.println(" - New index (erases any existing index at " + "that location)");
    }

    iterator.initialize(source);

    // Create the index
    long start = System.currentTimeMillis();
    IndexBuilder di = new IndexBuilder(target, indexURL, canonical, etag, addToIndex);
    di.writeToIndex(iterator, mimefilter, !whitelist, verbose);

    // Clean-up
    di.close();

    System.out.println("Total run time: "
            + DateUtils.formatMillisecondsToConventional(System.currentTimeMillis() - start));
}

From source file:com.lfv.lanzius.Main.java

public static void main(String[] args) {

    /*//  ww  w  .  j av a2 s.c  om
     * debug levels:
     * error - Runtime errors or unexpected conditions. Expect these to be immediately visible on a status console. See also Internationalization.
     * warn  - Use of deprecated APIs, poor use of API, 'almost' errors, other runtime situations that are undesirable or unexpected, but not necessarily "wrong". Expect these to be immediately visible on a status console. See also Internationalization.
     * info  - Interesting runtime events (startup/shutdown). Expect these to be immediately visible on a console, so be conservative and keep to a minimum. See also Internationalization.
     * debug - detailed information on the flow through the system. Expect these to be written to logs only.
     */

    Log log = null;
    DOMConfigurator conf = new DOMConfigurator();
    DOMConfigurator.configure("data/properties/loggingproperties.xml");
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.Log4JLogger");

    try {
        if (args.length >= 1) {
            // Help
            if (args[0].startsWith("-h")) {
                printUsage();
                return;
            }
            // List devices
            else if (args[0].startsWith("-l")) {
                AudioTest.listDevices();
                return;
            }
            // Test seleted device
            else if (args[0].startsWith("-d")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    String option = "all";
                    if (args.length >= 4)
                        option = args[3];

                    if (option.equals("loop:direct"))
                        AudioTest.testDevicesDirect(Integer.parseInt(args[1]), Integer.parseInt(args[2]));
                    else {
                        if (option.indexOf("debug") != -1)
                            System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "debug");

                        AudioTest.testDevices(Integer.parseInt(args[1]), Integer.parseInt(args[2]), option,
                                (args.length >= 5) ? args[4] : null, (args.length >= 6) ? args[5] : null,
                                (args.length >= 7) ? args[6] : null);
                    }
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println(
                            "  yada.jar -d output_device input_device <option> <jitter_buffer> <output_buffer> <input_buffer>");
                    System.out.println("  option:");
                    System.out.println("    all(default)");
                    System.out.println("    clip");
                    System.out.println("    loop:jspeex");
                    System.out.println("    loop:null");
                    System.out.println("    loop:direct");
                    System.out.println("    loopdebug:jspeex");
                    System.out.println("    loopdebug:null");
                    System.out.println("  jitter_buffer:");
                    System.out.println("    size of jitter buffer in packets (1-20)");
                    System.out.println("  output_buffer:");
                    System.out.println("    size of output buffer in packets (1.0-4.0)");
                    System.out.println("  input_buffer:");
                    System.out.println("    size of input buffer in packets (1.0-4.0)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                //System.out.println("Exiting...");
                return;
            } else if (args[0].startsWith("-m")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn");
                try {
                    AudioTest.testMicrophoneLevel(Integer.parseInt(args[1]));
                } catch (Exception ex) {
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -m input_device");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-s")) {
                Packet.randomSeed = 9182736455L ^ System.currentTimeMillis();
                if (args.length > 2 && args[1].startsWith("-configuration")) {
                    String configFilename = args[2];
                    if (args.length > 4 && args[3].startsWith("-exercise")) {
                        String exerciseFilename = args[4];

                        LanziusServer.start(configFilename, exerciseFilename);
                    } else {
                        LanziusServer.start(configFilename);
                    }
                } else {
                    LanziusServer.start();
                }
                return;
            } else if (args[0].startsWith("-f")) {
                System.setProperty("org.apache.commons.logging.Log",
                        "org.apache.commons.logging.impl.SimpleLog");
                System.setProperty(
                        "org.apache.commons.logging.simplelog.log.com.lfv.lanzius.application.FootSwitchController",
                        "debug");
                try {
                    System.out.println("Starting footswitch controller test using device " + args[1]);
                    try {
                        boolean inverted = false;
                        if (args.length >= 3)
                            inverted = args[2].toLowerCase().startsWith("inv");
                        FootSwitchController c = new FootSwitchController(null, args[1],
                                Constants.PERIOD_FTSW_CONNECTED, inverted);
                        c.start();
                        Thread.sleep(30000);
                    } catch (UnsatisfiedLinkError err) {
                        if (args.length > 1)
                            System.out.println("UnsatisfiedLinkError: " + err.getMessage());
                        else
                            throw new ArrayIndexOutOfBoundsException();
                        System.out.println("Missing ftsw library (ftsw.dll or libftsw.so)");
                        if (!args[1].equalsIgnoreCase("ftdi"))
                            System.out
                                    .println("Missing rxtxSerial library (rxtxSerial.dll or librxtxSerial.so)");
                        if (AudioTest.showStackTrace)
                            err.printStackTrace();
                    }
                } catch (Exception ex) {
                    if (ex instanceof NoSuchPortException)
                        System.out.println("The serial port " + args[1] + " does not exist!");
                    else if (ex instanceof PortInUseException)
                        System.out.println("The serial port " + args[1] + " is already in use!");
                    System.out.println();
                    System.out.println(Config.VERSION);
                    System.out.println();
                    System.out.println("Usage:");
                    System.out.println("  yada.jar -f interface <invert>");
                    System.out.println("  interface:");
                    System.out.println("    ftdi");
                    System.out.println("    comport (COMx or /dev/ttyx)");
                    System.out.println("  invert:");
                    System.out.println("    true");
                    System.out.println("    false (default)");
                    System.out.println();
                    if (AudioTest.showStackTrace && !(ex instanceof ArrayIndexOutOfBoundsException))
                        ex.printStackTrace();
                }
                return;
            } else if (args[0].startsWith("-c")) {
                Packet.randomSeed = 7233103157L ^ System.currentTimeMillis();
                if (args.length >= 2) {
                    try {
                        int id = Integer.valueOf(args[1]);
                        if (id <= 0)
                            throw new NumberFormatException();
                        Controller c = Controller.getInstance();
                        if (args.length >= 3) {
                            if (args[2].equalsIgnoreCase("test")) {
                                c.setAutoTester(true);
                            }
                        }
                        c.init(id);
                        return;
                    } catch (NumberFormatException ex) {
                        printUsage();
                    }
                } else {
                    Controller.getInstance().init(0);
                }
            } else
                printUsage();
        } else
            printUsage();
    } catch (Throwable t) {
        if (log == null)
            log = LogFactory.getLog(Main.class);
        log.error("Unhandled exception or error", t);
    }
}

From source file:io.anserini.index.UserPostFrequencyDistribution.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws Exception {
    Options options = new Options();

    options.addOption(new Option(HELP_OPTION, "show help"));

    options.addOption(new Option(STORE_TERM_VECTORS_OPTION, "store term vectors"));

    options.addOption(OptionBuilder.withArgName("collection").hasArg()
            .withDescription("source collection directory").create(COLLECTION_OPTION));
    options.addOption(OptionBuilder.withArgName("property").hasArg()
            .withDescription("source collection directory").create("property"));
    options.addOption(OptionBuilder.withArgName("collection_pattern").hasArg()
            .withDescription("source collection directory").create("collection_pattern"));

    CommandLine cmdline = null;/* w w w.ja  va2 s.co m*/
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (cmdline.hasOption(HELP_OPTION) || !cmdline.hasOption(COLLECTION_OPTION)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(UserPostFrequencyDistribution.class.getName(), options);
        System.exit(-1);
    }

    String collectionPath = cmdline.getOptionValue(COLLECTION_OPTION);

    final FieldType textOptions = new FieldType();
    textOptions.setIndexOptions(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);
    textOptions.setStored(true);
    textOptions.setTokenized(true);
    textOptions.setStoreTermVectors(true);

    LOG.info("collection: " + collectionPath);
    LOG.info("collection_pattern " + cmdline.getOptionValue("collection_pattern"));
    LOG.info("property " + cmdline.getOptionValue("property"));
    LongOpenHashSet deletes = null;

    long startTime = System.currentTimeMillis();
    File file = new File(collectionPath);
    if (!file.exists()) {
        System.err.println("Error: " + file + " does not exist!");
        System.exit(-1);
    }

    final JsonStatusCorpusReader stream = new JsonStatusCorpusReader(file,
            cmdline.getOptionValue("collection_pattern"));

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {

            try {

                stream.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            ;

            System.out.println("# of users indexed this round: " + userIndexedCount);

            System.out.println("Shutting down");

        }
    });
    Status status;
    boolean readerNotInitialized = true;

    try {
        Properties prop = new Properties();
        while ((status = stream.next()) != null) {

            // try{
            // status = DataObjectFactory.createStatus(s);
            // if (status==null||status.getText() == null) {
            // continue;
            // }}catch(Exception e){
            //
            // }
            //

            boolean pittsburghRelated = false;
            try {

                if (Math.abs(status.getLongitude() - pittsburghLongitude) < 0.05d
                        && Math.abs(status.getlatitude() - pittsburghLatitude) < 0.05d)
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getPlace().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }
            try {
                if (status.getUserLocation().contains("Pittsburgh, PA"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            try {
                if (status.getText().contains("Pittsburgh"))
                    pittsburghRelated = true;
            } catch (Exception e) {

            }

            if (pittsburghRelated) {

                int previousPostCount = 0;

                if (prop.containsKey(String.valueOf(status.getUserid()))) {
                    previousPostCount = Integer
                            .valueOf(prop.getProperty(String.valueOf(status.getUserid())).split(" ")[1]);
                }

                prop.setProperty(String.valueOf(status.getUserid()),
                        String.valueOf(status.getStatusesCount()) + " " + (1 + previousPostCount));
                if (prop.size() > 0 && prop.size() % 1000 == 0) {
                    Runtime runtime = Runtime.getRuntime();
                    runtime.gc();
                    System.out.println("Property size " + prop.size() + "Memory used:  "
                            + ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB\n");
                }
                OutputStream output = new FileOutputStream(cmdline.getOptionValue("property"), false);
                prop.store(output, null);
                output.close();

            }
        }
        //         prop.store(output, null);
        LOG.info(String.format("Total of %s statuses added", userIndexedCount));
        LOG.info("Total elapsed time: " + (System.currentTimeMillis() - startTime) + "ms");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {

        stream.close();
    }
}

From source file:fr.inria.atlanmod.instantiator.neoEMF.Launcher.java

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

    ResourceSetImpl resourceSet = new ResourceSetImpl();
    { // initializing the registry

        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(EcorePackage.eNS_PREFIX,
                new EcoreResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap()
                .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl());
        resourceSet.getResourceFactoryRegistry().getProtocolToFactoryMap().put(NeoEMFURI.NEOEMF_HBASE_SCHEME,
                NeoEMFResourceFactory.eINSTANCE);

    }//www  .  ja  v  a2  s  . c  o m

    Options options = new Options();

    configureOptions(options);

    CommandLineParser parser = new GnuParser();

    try {
        CommandLine commandLine = parser.parse(options, args);

        String epackage_class = commandLine.getOptionValue(E_PACKAGE_CLASS);

        LOGGER.info("Start loading the package");
        Class<?> inClazz = Launcher.class.getClassLoader().loadClass(epackage_class);
        EPackage _package = (EPackage) inClazz.getMethod("init").invoke(null);

        Resource metamodelResource = new XMIResourceImpl(URI.createFileURI("dummy"));
        metamodelResource.getContents().add(_package);
        LOGGER.info("Finish loading the package");

        int size = Launcher.DEFAULT_AVERAGE_MODEL_SIZE;
        if (commandLine.hasOption(SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(SIZE);
            size = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        float variation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}", VARIATION,
                        number.floatValue()));
            }
            variation = number.floatValue();
        }

        float propVariation = Launcher.DEFAULT_DEVIATION;
        if (commandLine.hasOption(PROP_VARIATION)) {
            Number number = (Number) commandLine.getParsedOptionValue(PROP_VARIATION);
            if (number.floatValue() < 0.0f || number.floatValue() > 1.0f) {
                throw new ParseException(MessageFormat.format("Invalid value for option -{0}: {1}",
                        PROP_VARIATION, number.floatValue()));
            }
            propVariation = number.floatValue();
        }

        long seed = System.currentTimeMillis();
        if (commandLine.hasOption(SEED)) {
            seed = ((Number) commandLine.getParsedOptionValue(SEED)).longValue();
        }

        Range<Integer> range = Range.between(Math.round(size * (1 - variation)),
                Math.round(size * (1 + variation)));

        GenericMetamodelConfig config = new GenericMetamodelConfig(metamodelResource, range, seed);
        GenericMetamodelGenerator modelGen = new GenericMetamodelGenerator(config);

        if (commandLine.hasOption(OUTPUT_PATH)) {
            String outDir = commandLine.getOptionValue(OUTPUT_PATH);
            //java.net.URI intermediateURI = java.net.URI.create(outDir);
            modelGen.setSamplesPath(outDir);
        }

        int numberOfModels = 1;
        if (commandLine.hasOption(N_MODELS)) {
            numberOfModels = ((Number) commandLine.getParsedOptionValue(N_MODELS)).intValue();
        }

        int valuesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_VALUES_LENGTH;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(VALUES_SIZE);
            valuesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        int referencesSize = GenericMetamodelConfig.DEFAULT_AVERAGE_REFERENCES_SIZE;
        if (commandLine.hasOption(VALUES_SIZE)) {
            Number number = (Number) commandLine.getParsedOptionValue(DEGREE);
            referencesSize = (int) Math.min(Integer.MAX_VALUE, number.longValue());
        }

        config.setValuesRange(Math.round(valuesSize * (1 - propVariation)),
                Math.round(valuesSize * (1 + propVariation)));

        config.setReferencesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        config.setPropertiesRange(Math.round(referencesSize * (1 - propVariation)),
                Math.round(referencesSize * (1 + propVariation)));

        long start = System.currentTimeMillis();
        modelGen.runGeneration(resourceSet, numberOfModels, size, variation);
        long end = System.currentTimeMillis();
        LOGGER.info(
                MessageFormat.format("Generation finished after {0} s", Long.toString((end - start) / 1000)));

        if (commandLine.hasOption(DIAGNOSE)) {
            for (Resource resource : resourceSet.getResources()) {
                LOGGER.info(
                        MessageFormat.format("Requested validation for resource ''{0}''", resource.getURI()));
                BasicDiagnostic diagnosticChain = diagnoseResource(resource);
                if (!isFailed(diagnosticChain)) {
                    LOGGER.info(MessageFormat.format("Result of the diagnosis of resurce ''{0}'' is ''OK''",
                            resource.getURI()));
                } else {
                    LOGGER.severe(MessageFormat.format("Found ''{0}'' error(s) in the resource ''{1}''",
                            diagnosticChain.getChildren().size(), resource.getURI()));
                    for (Diagnostic diagnostic : diagnosticChain.getChildren()) {
                        LOGGER.fine(diagnostic.getMessage());
                    }
                }
            }
            LOGGER.info("Validation finished");
        }

    } catch (ParseException e) {
        System.err.println(e.getLocalizedMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.setOptionComparator(new OptionComarator<Option>());
        try {
            formatter.setWidth(Math.max(Terminal.getTerminal().getTerminalWidth(), 80));
        } catch (Throwable t) {
            LOGGER.warning("Unable to get console information");
        }
        ;
        formatter.printHelp("java -jar <this-file.jar>", options, true);
        System.exit(ERROR);
    } catch (ClassNotFoundException t) {
        System.err.println("ERROR: Unable to load class" + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(stringWriter.toString());
    } catch (Throwable t) {
        System.err.println("ERROR: " + t.getLocalizedMessage());
        StringWriter stringWriter = new StringWriter();
        t.printStackTrace(new PrintWriter(stringWriter));
        System.err.println(t);
        LOGGER.severe(stringWriter.toString());
        System.exit(ERROR);
    }
}

From source file:com.l2jfree.loginserver.tools.L2AccountManager.java

/**
 * Launches the interactive account manager.
 * // www . j av  a2  s.c  o m
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Account Management");

    _log.info("Please choose:");
    //_log.info("list - list registered accounts");
    _log.info("reg - register a new account");
    _log.info("rem - remove a registered account");
    _log.info("prom - promote a registered account");
    _log.info("dem - demote a registered account");
    _log.info("ban - ban a registered account");
    _log.info("unban - unban a registered account");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2AccountManager acm = new L2AccountManager();

    String line;
    try {
        while ((line = br.readLine()) != null) {
            line = line.trim();
            Connection con = null;
            switch (acm.getState()) {
            case USER_NAME:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        acm.setUser(line);

                        _log.info("Desired password:");
                        acm.setState(ManagerState.PASSWORD);
                    } else {
                        _log.info("User name already in use.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case PASSWORD:
                try {
                    MessageDigest sha = MessageDigest.getInstance("SHA");
                    byte[] pass = sha.digest(line.getBytes("US-ASCII"));
                    acm.setPass(HexUtil.bytesToHexString(pass));
                } catch (NoSuchAlgorithmException e) {
                    _log.fatal("SHA1 is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                } catch (UnsupportedEncodingException e) {
                    _log.fatal("ASCII is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                }
                _log.info("Super user: [y/n]");
                acm.setState(ManagerState.SUPERUSER);
                break;
            case SUPERUSER:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        acm.setSuper(true);
                    else if (line.charAt(0) == 'n')
                        acm.setSuper(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    _log.info("Date of birth: [yyyy-mm-dd]");
                    acm.setState(ManagerState.DOB);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            case DOB:
                try {
                    Date d = Date.valueOf(line);
                    if (d.after(new Date(System.currentTimeMillis())))
                        throw new IllegalArgumentException("Future date specified.");
                    acm.setDob(d);

                    _log.info("Ban reason ID or nothing:");
                    acm.setState(ManagerState.SUSPENDED);
                } catch (IllegalArgumentException e) {
                    _log.info("[yyyy-mm-dd] in the past:");
                }
                break;
            case SUSPENDED:
                try {
                    if (line.length() > 0) {
                        int id = Integer.parseInt(line);
                        acm.setBan(L2BanReason.getById(id));
                    } else
                        acm.setBan(null);

                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)");
                        ps.setString(1, acm.getUser());
                        ps.setString(2, acm.getPass());
                        ps.setBoolean(3, acm.isSuper());
                        ps.setDate(4, acm.getDob());
                        L2BanReason lbr = acm.getBan();
                        if (lbr == null)
                            ps.setNull(5, Types.INTEGER);
                        else
                            ps.setInt(5, lbr.getId());
                        ps.executeUpdate();
                        _log.info("Account " + acm.getUser() + " has been registered.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register an account!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID or nothing:");
                }
                break;
            case REMOVE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?");
                    ps.setString(1, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been removed.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not remove an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case PROMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, true);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been promoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not promote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case DEMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, false);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been demoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case UNBAN:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setNull(1, Types.INTEGER);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been unbanned.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case BAN:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        acm.setUser(line);

                        _log.info("Ban reason ID:");
                        acm.setState(ManagerState.REASON);
                    } else {
                        _log.info("Account does not exist.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case REASON:
                try {
                    int ban = Integer.parseInt(line);
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setInt(1, ban);
                    ps.setString(2, acm.getUser());
                    ps.executeUpdate();
                    _log.info("Account " + acm.getUser() + " has been banned.");
                    ps.close();
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID:");
                } catch (SQLException e) {
                    _log.error("Could not ban an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            default:
                line = line.toLowerCase();
                if (line.equals("reg")) {
                    _log.info("Desired user name:");
                    acm.setState(ManagerState.USER_NAME);
                } else if (line.equals("rem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.REMOVE);
                } else if (line.equals("prom")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.PROMOTE);
                } else if (line.equals("dem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.DEMOTE);
                } else if (line.equals("unban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.UNBAN);
                } else if (line.equals("ban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.BAN);
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}