Example usage for org.joda.time Duration getMillis

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

Introduction

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

Prototype

public long getMillis() 

Source Link

Document

Gets the length of this duration in milliseconds.

Usage

From source file:com.google.cloud.pubsub.PollingSubscriberConnection.java

License:Open Source License

private void pullMessages(final Duration backoff) {
    ListenableFuture<PullResponse> pullResult = stub
            .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS)
            .pull(PullRequest.newBuilder().setSubscription(subscription).setMaxMessages(DEFAULT_MAX_MESSAGES)
                    .setReturnImmediately(true).build());

    Futures.addCallback(pullResult, new FutureCallback<PullResponse>() {
        @Override/*from w w  w.  j  a va2  s. c o  m*/
        public void onSuccess(PullResponse pullResponse) {
            processReceivedMessages(pullResponse.getReceivedMessagesList());
            if (pullResponse.getReceivedMessagesCount() == 0) {
                // No messages in response, possibly caught up in backlog, we backoff to avoid 
                // slamming the server.
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            pullMessages(INITIAL_BACKOFF);
        }

        @Override
        public void onFailure(Throwable cause) {
            if (!(cause instanceof StatusRuntimeException)
                    || isRetryable(((StatusRuntimeException) cause).getStatus())) {
                logger.error("Failed to pull messages (recoverable): " + cause.getMessage(), cause);
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            notifyFailed(cause);
        }
    });
}

From source file:com.google.cloud.pubsub.spi.v1.FakeScheduledExecutorService.java

License:Open Source License

/**
 * This will advance the reference time of the executor and execute (in the same thread) any
 * outstanding callable which execution time has passed.
 *//*from   ww  w . j  av  a2  s .c o m*/
public void advanceTime(Duration toAdvance) {
    clock.advance(toAdvance.getMillis(), TimeUnit.MILLISECONDS);
    work();
}

From source file:com.google.cloud.pubsub.spi.v1.PollingSubscriberConnection.java

License:Open Source License

private void pullMessages(final Duration backoff) {
    ListenableFuture<PullResponse> pullResult = stub
            .withDeadlineAfter(DEFAULT_TIMEOUT.getMillis(), TimeUnit.MILLISECONDS)
            .pull(PullRequest.newBuilder().setSubscription(subscription).setMaxMessages(DEFAULT_MAX_MESSAGES)
                    .setReturnImmediately(true).build());

    Futures.addCallback(pullResult, new FutureCallback<PullResponse>() {
        @Override//from ww  w. java2 s  .co m
        public void onSuccess(PullResponse pullResponse) {
            messageDispatcher.processReceivedMessages(pullResponse.getReceivedMessagesList());
            if (pullResponse.getReceivedMessagesCount() == 0) {
                // No messages in response, possibly caught up in backlog, we backoff to avoid
                // slamming the server.
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            pullMessages(INITIAL_BACKOFF);
        }

        @Override
        public void onFailure(Throwable cause) {
            if (!(cause instanceof StatusRuntimeException)
                    || isRetryable(((StatusRuntimeException) cause).getStatus())) {
                logger.log(Level.SEVERE, "Failed to pull messages (recoverable): ", cause);
                executor.schedule(new Runnable() {
                    @Override
                    public void run() {
                        Duration newBackoff = backoff.multipliedBy(2);
                        if (newBackoff.isLongerThan(MAX_BACKOFF)) {
                            newBackoff = MAX_BACKOFF;
                        }
                        pullMessages(newBackoff);
                    }
                }, backoff.getMillis(), TimeUnit.MILLISECONDS);
                return;
            }
            notifyFailed(cause);
        }
    });
}

From source file:com.google.cloud.testing.BaseEmulatorHelper.java

License:Open Source License

private static int waitForProcess(final Process process, Duration timeout)
        throws InterruptedException, TimeoutException {
    if (process == null) {
        return 0;
    }//from   w ww .jav a  2  s  .c o m

    final SettableFuture<Integer> exitValue = SettableFuture.create();

    Thread waiter = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                exitValue.set(process.waitFor());
            } catch (InterruptedException e) {
                exitValue.setException(e);
            }
        }
    });
    waiter.start();

    try {
        return exitValue.get(timeout.getMillis(), TimeUnit.MILLISECONDS);
    } catch (ExecutionException e) {
        if (e.getCause() instanceof InterruptedException) {
            throw (InterruptedException) e.getCause();
        }
        throw new UncheckedExecutionException(e);
    } finally {
        waiter.interrupt();
    }
}

From source file:com.google.gitiles.ConfigUtil.java

License:Open Source License

/**
 * Get a {@link CacheBuilder} from a config.
 *
 * @param config JGit config object.//from   w  w  w. ja va  2  s. c o  m
 * @param name name of the cache subsection under the "cache" section.
 * @return a new cache builder.
 */
public static CacheBuilder<Object, Object> getCacheBuilder(Config config, String name) {
    CacheBuilder<Object, Object> b = CacheBuilder.newBuilder();
    try {
        if (config.getString("cache", name, "maximumWeight") != null) {
            b.maximumWeight(config.getLong("cache", name, "maximumWeight", 20 << 20));
        }
        if (config.getString("cache", name, "maximumSize") != null) {
            b.maximumSize(config.getLong("cache", name, "maximumSize", 16384));
        }
        Duration expireAfterWrite = getDuration(config, "cache", name, "expireAfterWrite", null);
        if (expireAfterWrite != null) {
            b.expireAfterWrite(expireAfterWrite.getMillis(), TimeUnit.MILLISECONDS);
        }
        Duration expireAfterAccess = getDuration(config, "cache", name, "expireAfterAccess", null);
        if (expireAfterAccess != null) {
            b.expireAfterAccess(expireAfterAccess.getMillis(), TimeUnit.MILLISECONDS);
        }
        // Add other methods as needed.
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Error getting CacheBuilder for " + name, e);
    } catch (IllegalStateException e) {
        throw new IllegalStateException("Error getting CacheBuilder for " + name, e);
    }
    return b;
}

From source file:com.groupon.lex.metrics.lib.SkippingIterator.java

public static <T> Stream<T> adaptStream(Stream<T> stream, Function<? super T, ? extends DateTime> timestamp_fn,
        Duration stepsize) {
    if (stepsize.getMillis() <= 0L)
        return stream;

    final Iterator<T> iter = new SkippingIterator<>(stream.iterator(), timestamp_fn, stepsize);
    final Spliterator<T> spliter = Spliterators.spliteratorUnknownSize(iter, NONNULL | IMMUTABLE | ORDERED);
    return StreamSupport.stream(spliter, false);
}

From source file:com.josecalles.tistiq.task.StatCalculator.java

License:Apache License

public long timeSinceLastMessage(RealmList<TextMessage> messages) {
    long time = messages.get(messages.size() - 1).getDateReceived();
    DateTime lastMessageTime = new DateTime(time);
    DateTime currentTime = new DateTime();
    Duration duration = new Duration(lastMessageTime, currentTime);
    return duration.getMillis();
}

From source file:com.kopysoft.chronos.activities.ClockActivity.java

License:Open Source License

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.header);//from  w  w  w .  j  a  v a 2s.co m

    Chronos chronos = new Chronos(this);

    Job curJob = chronos.getAllJobs().get(0);
    jobId = curJob;
    localPunchTable = chronos.getAllPunchesForThisPayPeriodByJob(curJob);
    chronos.close();

    if (savedInstanceState != null) {
        payHolder = (PayPeriodHolder) savedInstanceState.getSerializable("payPeriod");
    } else {
        payHolder = new PayPeriodHolder(curJob);
    }

    //getSupportActionBar().setListNavigationCallbacks(list, this)
    //This is a workaround for http://b.android.com/15340 from http://stackoverflow.com/a/5852198/132047
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        BitmapDrawable bg = (BitmapDrawable) getResources().getDrawable(R.drawable.bg_striped);
        bg.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
        getSupportActionBar().setBackgroundDrawable(bg);

        BitmapDrawable bgSplit = (BitmapDrawable) getResources().getDrawable(R.drawable.bg_striped_split_img);
        bgSplit.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
        getSupportActionBar().setSplitBackgroundDrawable(bgSplit);
    }

    getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    ActionBar.Tab tab = getSupportActionBar().newTab();
    tab.setText("Today");
    tab.setTabListener(this);
    getSupportActionBar().addTab(tab);

    tab = getSupportActionBar().newTab();
    tab.setText("Pay Period");
    tab.setTabListener(this);
    getSupportActionBar().addTab(tab);

    if (savedInstanceState != null) {
        getSupportActionBar().setSelectedNavigationItem(savedInstanceState.getInt("position"));
    }

    Duration dur = PayPeriodAdapterList.getTime(localPunchTable.getPunchPair(DateTime.now()), true);
    Intent runIntent = new Intent().setClass(this, NotificationBroadcast.class);
    runIntent.putExtra("timeToday", dur.getMillis());
    this.sendBroadcast(runIntent);

    /*
    Intent newIntent =
        new Intent().setClass(this,
                PreferenceWizardActivity.class);
            
    this.startActivity(newIntent);
    */
}

From source file:com.kopysoft.chronos.activities.ClockActivity.java

License:Open Source License

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (enableLog)
        Log.d(TAG, "Request Code: " + requestCode);
    if (enableLog)
        Log.d(TAG, "Result Code: " + resultCode);
    if (enableLog)
        Log.d(TAG, "Selected Navigation Index: " + getSupportActionBar().getSelectedNavigationIndex());

    if (requestCode == FROM_CLOCK_ACTIVITY) {
        Chronos chronos = new Chronos(this);
        localPunchTable = chronos.getAllPunchesForThisPayPeriodByJob(chronos.getAllJobs().get(0));
        chronos.close();/*  w  w  w .  j  a  v  a2 s .  c o  m*/
    } else if (requestCode == NewPunchActivity.NEW_PUNCH) {
        if (enableLog)
            Log.d(TAG, "New Punch Created");
        Chronos chronos = new Chronos(this);
        localPunchTable = chronos.getAllPunchesForThisPayPeriodByJob(chronos.getAllJobs().get(0));
        chronos.close();
    } else if (requestCode == JobEditor.UPDATE_JOB) {
        Chronos chron = new Chronos(this);
        Job thisJob = chron.getAllJobs().get(0);
        localPunchTable = chron.getAllPunchesForThisPayPeriodByJob(thisJob);
        payHolder = new PayPeriodHolder(thisJob);
        chron.close();
    } else if (requestCode == QuickBreakActivity.NEW_BREAK) {
        if (enableLog)
            Log.d(TAG, "Got new break");
        Chronos chronos = new Chronos(this);
        localPunchTable = chronos.getAllPunchesForThisPayPeriodByJob(chronos.getAllJobs().get(0));
        chronos.close();
    } else {
        Chronos chronos = new Chronos(this);
        localPunchTable = chronos.getAllPunchesForThisPayPeriodByJob(chronos.getAllJobs().get(0));
        chronos.close();
    }

    //Send intent to create notification
    Duration dur = PayPeriodAdapterList.getTime(localPunchTable.getPunchPair(new DateTime()), true);
    Intent runIntent = new Intent().setClass(this, NotificationBroadcast.class);
    runIntent.putExtra("timeToday", dur.getMillis());
    this.sendBroadcast(runIntent);

    if (getSupportActionBar().getSelectedNavigationIndex() == 0) {
        setContentView(new DatePairView(this, localPunchTable.getPunchesByDay(new DateTime()), DateTime.now()));
        //setContentView(new DatePairView(this, new DateTime()));
    } else if (getSupportActionBar().getSelectedNavigationIndex() == 1) {
        setContentView(new PayPeriodSummaryView(this, getPunchesByDate()));
    }
}

From source file:com.kopysoft.chronos.activities.Viewers.DateViewerActivity.java

License:Open Source License

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Chronos chronos = new Chronos(this);
    Job curJob = chronos.getAllJobs().get(0);
    jobId = curJob.getID();/*  w  w w .j a  v a 2  s. co m*/
    PunchTable localPunchTable = chronos.getAllPunchesForThisPayPeriodByJob(chronos.getAllJobs().get(0));
    //List<Punch> punches = chronos.getPunchesByJobAndDate(curJob, new DateTime(date));
    List<Punch> punches = chronos.getPunchesByJobAndDate(curJob, new DateTime(date));
    Log.d(TAG, "Number of punches:" + punches.size());

    chronos.close();

    Duration dur = PayPeriodAdapterList.getTime(localPunchTable.getPunchPair(new DateTime()), true);
    Intent runIntent = new Intent().setClass(this, NotificationBroadcast.class);
    runIntent.putExtra("timeToday", dur.getMillis());
    this.sendBroadcast(runIntent);

    setContentView(new DatePairView(this, punches, new DateTime(date)));
}