Example usage for java.util Calendar getTimeInMillis

List of usage examples for java.util Calendar getTimeInMillis

Introduction

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

Prototype

public long getTimeInMillis() 

Source Link

Document

Returns this Calendar's time value in milliseconds.

Usage

From source file:gr.seab.r2rml.beans.Main.java

public static void main(String[] args) {
    Calendar c0 = Calendar.getInstance();
    long t0 = c0.getTimeInMillis();

    CommandLineParser cmdParser = new PosixParser();

    Options cmdOptions = new Options();
    cmdOptions.addOption("p", "properties", true,
            "define the properties file. Example: r2rml-parser -p r2rml.properties");
    cmdOptions.addOption("h", "print help", false, "help");

    String propertiesFile = "r2rml.properties";

    try {//www. j  av  a  2 s  . co m
        CommandLine line = cmdParser.parse(cmdOptions, args);

        if (line.hasOption("h")) {
            HelpFormatter help = new HelpFormatter();
            help.printHelp("r2rml-parser\n", cmdOptions);
            System.exit(0);
        }

        if (line.hasOption("p")) {
            propertiesFile = line.getOptionValue("p");
        }
    } catch (ParseException e1) {
        //e1.printStackTrace();
        log.error("Error parsing command line arguments.");
        System.exit(1);
    }

    try {
        if (StringUtils.isNotEmpty(propertiesFile)) {
            properties.load(new FileInputStream(propertiesFile));
            log.info("Loaded properties from " + propertiesFile);
        }
    } catch (FileNotFoundException e) {
        //e.printStackTrace();
        log.error("Properties file not found (" + propertiesFile + ").");
        System.exit(1);
    } catch (IOException e) {
        //e.printStackTrace();
        log.error("Error reading properties file (" + propertiesFile + ").");
        System.exit(1);
    }

    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");

    Database db = (Database) context.getBean("db");
    db.setProperties(properties);

    Parser parser = (Parser) context.getBean("parser");
    parser.setProperties(properties);

    MappingDocument mappingDocument = parser.parse();

    mappingDocument.getTimestamps().add(t0); //0 Started
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //1 Finished parsing. Starting generating result model.

    Generator generator = (Generator) context.getBean("generator");
    generator.setProperties(properties);
    generator.setResultModel(parser.getResultModel());

    //Actually do the output
    generator.createTriples(mappingDocument);

    context.close();
    Calendar c1 = Calendar.getInstance();
    long t1 = c1.getTimeInMillis();
    log.info("Finished in " + (t1 - t0) + " milliseconds. Done.");
    mappingDocument.getTimestamps().add(Calendar.getInstance().getTimeInMillis()); //5 Finished.
    //log.info("5 Finished.");

    //output the result
    for (int i = 0; i < mappingDocument.getTimestamps().size(); i++) {
        if (i > 0) {
            long l = (mappingDocument.getTimestamps().get(i).longValue()
                    - mappingDocument.getTimestamps().get(i - 1).longValue());
            //System.out.println(l);
            log.info(String.valueOf(l));
        }
    }
    log.info("Parse. Generate in memory. Dump to disk/database. Log. - Alltogether in "
            + String.valueOf(mappingDocument.getTimestamps().get(5).longValue()
                    - mappingDocument.getTimestamps().get(0).longValue())
            + " msec.");
    log.info("Done.");
    System.out.println("Done.");
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
    japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23
    japanCal.set(Calendar.MINUTE, 0);
    japanCal.set(Calendar.SECOND, 0);

    Calendar local = new GregorianCalendar();
    local.setTimeInMillis(japanCal.getTimeInMillis());
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Calendar japanCal = new GregorianCalendar(TimeZone.getTimeZone("Japan"));
    japanCal.set(Calendar.HOUR_OF_DAY, 10); // 0..23
    japanCal.set(Calendar.MINUTE, 0);
    japanCal.set(Calendar.SECOND, 0);

    Calendar local = new GregorianCalendar();
    local.setTimeInMillis(japanCal.getTimeInMillis());
    int hour = local.get(Calendar.HOUR); // 5
    int minutes = local.get(Calendar.MINUTE); // 0
    int seconds = local.get(Calendar.SECOND); // 0
    boolean am = local.get(Calendar.AM_PM) == Calendar.AM; // false
}

From source file:com.pureinfo.srm.config.notice.TestTimer.java

public static void main(String[] args) throws ParseException {
    Calendar start = new GregorianCalendar();
    start.setTime(format.parse("18:40"));
    Calendar cal = new GregorianCalendar();
    start.set(Calendar.YEAR, cal.get(Calendar.YEAR));
    start.set(Calendar.MONTH, cal.get(Calendar.MONTH));
    start.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH));
    while (start.before(cal)) {
        start.setTimeInMillis(start.getTimeInMillis() + DateUtils.MILLIS_PER_MINUTE);
    }/*w ww  . ja v a  2s  .  c o  m*/
    new Timer().scheduleAtFixedRate(new test1(), start.getTime(), DateUtils.MILLIS_PER_MINUTE);
}

From source file:Main.java

public static void main(String[] args) {
    Calendar localTime = Calendar.getInstance();
    localTime.set(Calendar.HOUR, 17);
    localTime.set(Calendar.MINUTE, 15);
    localTime.set(Calendar.SECOND, 20);

    int hour = localTime.get(Calendar.HOUR);
    int minute = localTime.get(Calendar.MINUTE);
    int second = localTime.get(Calendar.SECOND);

    System.out.printf("Local time  : %02d:%02d:%02d\n", hour, minute, second);

    Calendar germanyTime = new GregorianCalendar(TimeZone.getTimeZone("Germany"));
    germanyTime.setTimeInMillis(localTime.getTimeInMillis());
    hour = germanyTime.get(Calendar.HOUR);
    minute = germanyTime.get(Calendar.MINUTE);
    second = germanyTime.get(Calendar.SECOND);

    System.out.printf("Germany time: %02d:%02d:%02d\n", hour, minute, second);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Calendar start = Calendar.getInstance();
    start.set(2015, 1, 21, 11, 1, 11);//  w  w  w  . j av  a2 s  . c  o  m
    Calendar end = Calendar.getInstance();

    Calendar clone = (Calendar) start.clone();
    int year = elapsed(clone, end, Calendar.YEAR);
    System.out.println(year + " year");
    clone.add(Calendar.YEAR, year);
    int month = elapsed(clone, end, Calendar.MONTH);
    clone.add(Calendar.MONTH, month);
    System.out.println(month + " month");

    int date = elapsed(clone, end, Calendar.DATE);
    clone.add(Calendar.DATE, date);
    System.out.println(date + " day");

    int hour = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
    clone.add(Calendar.HOUR, hour);
    System.out.println(hour + " hour");

    int minute = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
    clone.add(Calendar.MINUTE, minute);
    System.out.println(minute + " minute");

    int millis = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
    System.out.println(millis + " millis");

}

From source file:com.icebreak.p2p.trade.impl.InvestServiceImpl.java

public static void main(String[] args) {
    int days = 56;
    Calendar endTime = Calendar.getInstance();
    Calendar beginTime = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date = null;/*from   w  ww. j a  va 2  s.  c  o m*/
    try {
        date = sdf.parse("2015-01-27 09:49:21");
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    beginTime.setTime(date);
    int cutDays = (int) ((endTime.getTimeInMillis() - beginTime.getTimeInMillis()) / 1000 / 60 / 60 / 24);
    days = days - cutDays;
    days = (days < 0 ? 0 : days);
    System.out.println("cutDays: " + cutDays);
    System.out.println("days: " + days);
}

From source file:eu.smartfp7.foursquare.AttendanceCrawler.java

/**
 * The main takes an undefined number of cities as arguments, then initializes
 * the specific crawling of all the trending venues of these cities.
 * The trending venues must have been previously identified using the `DownloadPages`
 * program./*from   w ww  . j ava2  s  .c o m*/
 * 
 * Current valid cities are: london, amsterdam, goldcoast, sanfrancisco.
 * 
 */
public static void main(String[] args) throws Exception {
    Settings settings = Settings.getInstance();
    String folder = settings.getFolder();

    // We keep info and error logs, so that we know what happened in case
    // of incoherence in the time series.
    Map<String, FileWriter> info_logs = new HashMap<String, FileWriter>();
    Map<String, FileWriter> error_logs = new HashMap<String, FileWriter>();

    // For each city we monitor, we store the venue IDs that we got from
    // a previous crawl.
    Map<String, Collection<String>> city_venues = new HashMap<String, Collection<String>>();

    // Contains the epoch time when the last API call has been made for each 
    // venue. Ensures that we get data only once each hour. 
    Map<String, Long> venue_last_call = new HashMap<String, Long>();

    // Contains the epoch time when we last checked if time series were broken
    // for each city.
    // We do these checks once every day before the batch forecasting begins.
    Map<String, Long> sanity_checks = new HashMap<String, Long>();

    // We also keep in memory the number of checkins for the last hour for
    // each venue.
    Map<String, Integer> venue_last_checkin = new HashMap<String, Integer>();

    Map<Long, Integer> APICallsCount = new HashMap<Long, Integer>();

    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    int total_venues = 0;
    long total_calls = 0;
    long time_spent_on_API = 0;

    for (String c : args) {
        settings.checkFileHierarchy(c);

        city_venues.put(c, loadVenues(c));
        total_venues += city_venues.get(c).size();

        info_logs.put(c,
                new FileWriter(folder + c + File.separator + "log" + File.separator + "info.log", true));
        error_logs.put(c,
                new FileWriter(folder + c + File.separator + "log" + File.separator + "error.log", true));

        Calendar cal = Calendar.getInstance();

        info_logs.get(c).write("[" + df.format(cal.getTime()) + "] Crawler initialization for " + c + ". "
                + city_venues.get(c).size() + " venues loaded.\n");
        info_logs.get(c).flush();

        // If we interrupted the program for some reason, we can get back
        // the in-memory data.
        // Important: the program must not be interrupted for more than one
        // hour, or we will lose time series data.
        for (String venue_id : city_venues.get(c)) {
            String ts_file = folder + c + File.separator + "attendances_crawl" + File.separator + venue_id
                    + ".ts";

            if (new File(ts_file).exists()) {
                BufferedReader buffer = new BufferedReader(new FileReader(ts_file));
                String mem = null, line = null;
                for (; (line = buffer.readLine()) != null; mem = line)
                    ;
                buffer.close();

                if (mem == null)
                    continue;

                String[] tmp = mem.split(",");
                venue_last_call.put(venue_id, df.parse(tmp[0]).getTime());
                venue_last_checkin.put(venue_id, Integer.parseInt(tmp[3]));

                VenueUtil.fixBrokenTimeSeriesVenue(new File(ts_file));
            } // if
        } // for

        sanity_checks.put(c, cal.getTimeInMillis());
    } // for

    if (total_venues > 5000) {
        System.out.println(
                "Too much venues for a single API account (max 5000).\nPlease create a new Foursquare API account and use these credentials.\nExiting now.");
        return;
    }

    while (true) {

        for (String c : args) {
            // We create a FIFO queue and pop venue IDs one at a time.
            LinkedList<String> city_venues_buffer = new LinkedList<String>(city_venues.get(c));
            String venue_id = null;

            // Artificial wait to avoid processors looping at 100% of their capacity
            // when there is no more venues to crawl for the current hour.
            Thread.sleep(3000);

            while ((venue_id = city_venues_buffer.pollFirst()) != null) {
                // We get the current time according to the city's time zone
                Calendar cal = Calendar.getInstance();
                cal.add(Calendar.MILLISECOND,
                        TimeZone.getTimeZone(settings.getCityTimezone(c)).getOffset(cal.getTime().getTime())
                                - Calendar.getInstance().getTimeZone().getOffset(cal.getTime().getTime()));
                //TimeZone.getTimeZone("Europe/London").getOffset(cal.getTime().getTime()));

                long current_time = DateUtils.truncate(cal.getTime(), Calendar.HOUR).getTime();

                // We query Foursquare only once per hour per venue.
                if (venue_last_call.get(venue_id) != null
                        && current_time < venue_last_call.get(venue_id) + 3600000)
                    continue;

                intelligentWait(total_venues, cal.getTime().getTime(),
                        (total_calls == 0 ? 0 : Math.round(time_spent_on_API / total_calls)));

                Venue venue = null;

                try {
                    long beforeCall = System.currentTimeMillis();
                    venue = new Venue(getFoursquareVenueById(venue_id, c));

                    // If there is no last call, this is the beginning of the time series
                    // for this venue. We get the number of people "here now" to initialize
                    // the series.
                    if (venue_last_call.get(venue_id) == null) {
                        /** TODO: by doing this, we keep a representation of the venue dating from the beginning
                         *       of the specific crawl. we might want to change this and update this file once
                         *      in a while.
                         */
                        FileWriter info = new FileWriter(folder + c + File.separator + "foursquare_venues"
                                + File.separator + venue_id + ".info");
                        info.write(venue.getFoursquareJson());
                        info.close();

                        FileWriter out = new FileWriter(folder + c + File.separator + "attendances_crawl"
                                + File.separator + venue_id + ".ts");
                        out.write("Date,here_now,hour_checkins,total_checkins\n");
                        out.write(df.format(current_time) + "," + venue.getHereNow() + "," + venue.getHereNow()
                                + "," + venue.getCheckincount() + "\n");
                        out.close();
                    } else {
                        FileWriter out = new FileWriter(folder + c + File.separator + "attendances_crawl"
                                + File.separator + venue_id + ".ts", true);
                        int checks = venue.getCheckincount() - venue_last_checkin.get(venue_id);
                        out.write(df.format(current_time) + "," + venue.getHereNow() + ","
                                + Integer.toString(checks) + "," + venue.getCheckincount() + "\n");
                        out.close();
                    }

                    if (APICallsCount.get(current_time) == null)
                        APICallsCount.put(current_time, 1);
                    else
                        APICallsCount.put(current_time, APICallsCount.get(current_time) + 1);

                    total_calls++;

                    venue_last_call.put(venue_id, current_time);
                    venue_last_checkin.put(venue_id, venue.getCheckincount());

                    time_spent_on_API += System.currentTimeMillis() - beforeCall;
                } catch (Exception e) {
                    // If something bad happens (crawler not available, IO error, ...), we put the
                    // venue_id in the FIFO queue so that it gets reevaluated later.
                    //e.printStackTrace();
                    error_logs.get(c)
                            .write("[" + df.format(cal.getTime().getTime()) + "] Error with venue " + venue_id
                                    + " (" + e.getMessage() + "). " + APICallsCount.get(current_time)
                                    + " API calls so far this hour, " + city_venues_buffer.size()
                                    + " venues remaining in the buffer.\n");
                    error_logs.get(c).flush();

                    System.out.println("[" + df.format(cal.getTime().getTime()) + "] " + c + " -- "
                            + APICallsCount.get(current_time) + " API calls // " + city_venues_buffer.size()
                            + " venues remaining " + " (" + e.getMessage() + ")");

                    if (e instanceof FoursquareAPIException)
                        if (((FoursquareAPIException) e).getHttp_code().equals("400")
                                && ((FoursquareAPIException) e).getError_detail()
                                        .equals("Venue " + venue_id + " has been deleted")) {
                            city_venues.get(c).remove(venue_id);
                            removeVenue(venue_id, c);
                        } else
                            city_venues_buffer.add(venue_id);

                    continue;
                }
            } // while

            // Every day between 0am and 2am, we repair all the broken time series (if there
            // is something to repair).
            Calendar cal = Calendar.getInstance();
            if (city_venues_buffer.peekFirst() == null
                    && (cal.getTimeInMillis() - sanity_checks.get(c)) >= 86400000
                    && cal.get(Calendar.HOUR_OF_DAY) < 2) {
                VenueUtil.fixBrokenTimeSeriesCity(c, folder);
                sanity_checks.put(c, cal.getTimeInMillis());
                info_logs.get(c).write("[" + df.format(cal.getTime()) + "] Sanity check OK.\n");
                info_logs.get(c).flush();
            }
        } // for
    } // while
}

From source file:Main.java

public static long getDifference(Calendar a, Calendar b, TimeUnit units) {
    return units.convert(b.getTimeInMillis() - a.getTimeInMillis(), TimeUnit.MILLISECONDS);
}

From source file:Main.java

public static boolean overOneMin(Calendar cl1, Calendar cl2) {
    if ((cl2.getTimeInMillis() - cl1.getTimeInMillis()) > 60 * 1000) {
        return true;
    }// w w w. ja va2  s  . c o m
    return false;
}