Example usage for org.joda.time DateTime getMillis

List of usage examples for org.joda.time DateTime getMillis

Introduction

In this page you can find the example usage for org.joda.time DateTime getMillis.

Prototype

public long getMillis() 

Source Link

Document

Gets the milliseconds of the datetime instant from the Java epoch of 1970-01-01T00:00:00Z.

Usage

From source file:com.google.android.apps.paco.NotificationCreator.java

License:Open Source License

private void createAlarmForSnooze(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    Experiment experiment = experimentProviderUtil.getExperiment(notificationHolder.getExperimentId());
    Integer snoozeTime = experiment.getSignalingMechanisms().get(0).getSnoozeTime();
    int snoozeMinutes = snoozeTime / MILLIS_IN_MINUTE;
    DateTime timeoutMinutes = new DateTime(alarmTime).plusMinutes(snoozeMinutes);
    long snoozeDurationInMillis = timeoutMinutes.getMillis();

    Log.i(PacoConstants.TAG,/* ww w .j a v a  2  s.com*/
            "Creating snooze alarm to resound notification for holder: " + notificationHolder.getId()
                    + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
                    + new DateTime(alarmTime).toString() + " waking up from snooze in " + timeoutMinutes
                    + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());
    ultimateIntent.putExtra(SNOOZE_REPEATER_EXTRA_KEY, true);

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 3, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(intent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, snoozeDurationInMillis, intent);
}

From source file:com.google.android.apps.paco.ServerCommunication.java

License:Open Source License

private void setNextWakeupTime() {
    DateTime nextServerCommunicationTime = new DateTime(userPrefs.getNextServerCommunicationServiceAlarmTime());
    if (isInFuture(nextServerCommunicationTime)) {
        return;/*w  w  w . jav  a 2s .co m*/
    }

    DateTime nextCommTime = nextServerCommunicationTime.plusHours(24);
    if (nextCommTime.isBeforeNow() || nextCommTime.isEqualNow()) {
        nextCommTime = new DateTime().plusHours(24);
    }
    Intent ultimateIntent = new Intent(context, ServerCommunicationService.class);
    ultimateIntent.setData(CONTENT_URI);
    PendingIntent intent = PendingIntent.getService(context.getApplicationContext(), 0, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    alarmManager.cancel(intent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, nextCommTime.getMillis(), intent);
    userPrefs.setNextServerCommunicationServiceAlarmTime(nextCommTime.getMillis());
    Log.i(PacoConstants.TAG, "Created alarm for ServerCommunicationService. Time: " + nextCommTime.toString());
}

From source file:com.google.android.vending.licensing.PreferenceObfuscator.java

License:Apache License

public void putDateTime(String key, DateTime value) {
    putLong(key, value.getMillis());
}

From source file:com.google.cloud.dataflow.examples.opinionanalysis.IndexerPipelineUtils.java

License:Apache License

public static Long parseDateToLong(DateTimeFormatter formatter, String s) {
    Long result = null;/*  w  ww.j  a  v  a  2  s.co m*/
    DateTime date = parseDateString(formatter, s);
    if (date != null)
        result = date.getMillis();
    return result;
}

From source file:com.google.cloud.examples.coinflow.frontend.CoinflowServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    LOG.info("In CoinflowServlet doGet");

    if (req.getRequestURI().equals("/favicon.ico")) {
        return;//from  ww  w.  java 2  s  .  c  om
    }

    try (Table t = BigtableHelper.getConnection().getTable(TABLE)) {

        DateTime dateTime = new DateTime().minusHours(4);
        long beforeMillis = dateTime.getMillis();
        long nowMillis = new DateTime().getMillis();

        String beforeRowKey = "match_" + beforeMillis;
        String afterRowKey = "match_" + nowMillis;

        Scan scan = new Scan(beforeRowKey.getBytes(), afterRowKey.getBytes());
        ResultScanner rs = t.getScanner(scan);
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.setContentType("text/plain");

        List<PriceTimestamp> prices = new ArrayList<>();
        for (Result r : rs) {
            String data = new String(r.getValue(Schema.CF.getBytes(), Schema.QUALIFIER.getBytes()));
            CoinbaseData coinData = objectMapper.readValue(data, CoinbaseData.class);
            PriceTimestamp priceTimestamp = new PriceTimestamp(Float.parseFloat(coinData.getPrice()),
                    DateHelpers.convertDateToTime(coinData.getTime()));
            prices.add(priceTimestamp);
        }
        String pricesStr = objectMapper.writeValueAsString(prices);
        resp.getWriter().println(pricesStr);
    }
}

From source file:com.google.cloud.iot.examples.HttpExample.java

License:Apache License

/** Parse arguments and publish messages. */
public static void main(String[] args) throws Exception {
    HttpExampleOptions options = HttpExampleOptions.fromFlags(args);
    if (options == null) {
        // Could not parse the flags.
        System.exit(1);/*from  w  w w  .j  av  a2s  .c  o m*/
    }

    // Create the corresponding JWT depending on the selected algorithm.
    String token;
    DateTime iat = new DateTime();
    if (options.algorithm.equals("RS256")) {
        token = createJwtRsa(options.projectId, options.privateKeyFile);
    } else if (options.algorithm.equals("ES256")) {
        token = createJwtEs(options.projectId, options.privateKeyFile);
    } else {
        throw new IllegalArgumentException(
                "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
    }

    String urlPath = String.format("%s/%s/", options.httpBridgeAddress, options.apiVersion);
    System.out.format("Using URL: '%s'\n", urlPath);

    // Publish numMessages messages to the HTTP bridge.
    for (int i = 1; i <= options.numMessages; ++i) {
        String payload = String.format("%s/%s-payload-%d", options.registryId, options.deviceId, i);
        System.out.format("Publishing %s message %d/%d: '%s'\n", options.messageType, i, options.numMessages,
                payload);

        // Refresh the authentication token if the token has expired.
        long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
        if (secsSinceRefresh > (options.tokenExpMins * 60)) {
            System.out.format("\tRefreshing token after: %d seconds\n", secsSinceRefresh);
            iat = new DateTime();

            if (options.algorithm.equals("RS256")) {
                token = createJwtRsa(options.projectId, options.privateKeyFile);
            } else if (options.algorithm.equals("ES256")) {
                token = createJwtEs(options.projectId, options.privateKeyFile);
            }
        }

        publishMessage(payload, urlPath, options.messageType, token, options.projectId, options.cloudRegion,
                options.registryId, options.deviceId);

        if (options.messageType.equals("event")) {
            // Frequently send event payloads (every second)
            Thread.sleep(1000);
        } else {
            // Update state with low frequency (once every 5 seconds)
            Thread.sleep(5000);
        }
    }
    System.out.println("Finished loop successfully. Goodbye!");
}

From source file:com.google.cloud.training.dataanalyst.sandiego.BigtableHelper.java

License:Apache License

private static PCollection<KV<ByteString, Iterable<Mutation>>> toMutations(PCollection<LaneInfo> laneInfo) {
    return laneInfo.apply("pred->mutation", ParDo.of(new DoFn<LaneInfo, KV<ByteString, Iterable<Mutation>>>() {
        @ProcessElement//from   w ww . ja  v a  2 s. com
        public void processElement(ProcessContext c) throws Exception {
            LaneInfo info = c.element();
            DateTime ts = fmt.parseDateTime(info.getTimestamp().replace('T', ' '));

            // key is HIGHWAY#DIR#LANE#REVTS
            String key = info.getHighway() //
                    + "#" + info.getDirection() //
                    + "#" + info.getLane() //
                    + "#" + (Long.MAX_VALUE - ts.getMillis()); // reverse time stamp

            // all the data is in a wide column table with only one column family
            List<Mutation> mutations = new ArrayList<>();
            addCell(mutations, "timestamp", info.getTimestamp(), ts.getMillis());
            addCell(mutations, "latitude", info.getLatitude(), ts.getMillis());
            addCell(mutations, "longitude", info.getLongitude(), ts.getMillis());
            addCell(mutations, "highway", info.getHighway(), ts.getMillis());
            addCell(mutations, "direction", info.getDirection(), ts.getMillis());
            addCell(mutations, "lane", info.getLane(), ts.getMillis());
            addCell(mutations, "speed", info.getSpeed(), ts.getMillis());
            addCell(mutations, "sensorId", info.getSensorKey(), ts.getMillis());
            c.output(KV.of(ByteString.copyFromUtf8(key), mutations));
        }

    }));
}

From source file:com.google.enterprise.adaptor.secmgr.servlets.ResponseParser.java

License:Apache License

private boolean isValidExpiration(DateTime expiration) {
    return warnIfFalse(expiration != null, "Assertion expiration was null.")
            && warnIfFalse(SecurityManagerUtil.isRemoteOnOrAfterTimeValid(expiration.getMillis(), now),
                    "The assertion's expiration time is invalid.",
                    "Security Manager Current Time: " + new DateTime(now).toString(),
                    "Assertion expiration:" + new DateTime(expiration.getMillis()).toString());
}

From source file:com.google.enterprise.adaptor.secmgr.servlets.ResponseParser.java

License:Apache License

private boolean isValidConditionNotBefore(DateTime notBefore) {
    return notBefore == null || SecurityManagerUtil.isRemoteBeforeTimeValid(notBefore.getMillis(), now);
}

From source file:com.google.enterprise.adaptor.secmgr.servlets.ResponseParser.java

License:Apache License

private boolean isValidConditionNotOnOrAfter(DateTime notOnOrAfter) {
    return notOnOrAfter == null
            || SecurityManagerUtil.isRemoteOnOrAfterTimeValid(notOnOrAfter.getMillis(), now);
}