Example usage for org.joda.time Duration Duration

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

Introduction

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

Prototype

public Duration(ReadableInstant start, ReadableInstant end) 

Source Link

Document

Creates a duration from the given interval endpoints.

Usage

From source file:com.teamlazerbeez.crm.sf.soap.BindingConfigurer.java

License:Apache License

/**
 * Use the binding to get the config data for the org that the username and password points to..
 *
 * @param username      the username to log in with
 * @param password      the password to log in with
 * @param binding       the Soap binding to configure
 * @param callSemaphore the call semaphore to use when logging in
 * @param sandboxOrg    true if this is a login to a sandbox org
 *
 * @return a result object containing a few useful bits of info discovered during the login process
 *
 * @throws ApiException if login fails// w  ww  .  j  a  va 2  s.co m
 */
@Nonnull
BindingConfig loginAndGetBindingConfigData(@Nonnull String username, @Nonnull String password,
        @Nonnull Soap binding, @Nonnull CallSemaphore callSemaphore, boolean sandboxOrg) throws ApiException {
    Login loginParam = new Login();
    loginParam.setPassword(password);
    loginParam.setUsername(username);

    // Get a BindingProvider ref to the port
    WSBindingProvider wsBindingProvider = (WSBindingProvider) binding;

    // reset initial endpoint

    if (sandboxOrg) {
        wsBindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                SANDBOX_INITIAL_ENDPOINT);
    } else {
        wsBindingProvider.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY,
                NORMAL_INITIAL_ENDPOINT);
    }

    logger.trace("Using initial endpoint: "
            + wsBindingProvider.getRequestContext().get(BindingProvider.ENDPOINT_ADDRESS_PROPERTY));

    // reset headers to just be CallOptions
    CallOptions callOpts = new CallOptions();
    callOpts.setClient(this.partnerKey);
    wsBindingProvider.setOutboundHeaders(Headers.create(this.partnerJaxbContext, callOpts));
    this.configureRequestContextConnectionParams(wsBindingProvider);

    try {
        callSemaphore.acquire();
    } catch (InterruptedException e) {
        // we're not throwing a raw InterruptedException, so re-interrupt the thread for later detection
        Thread.currentThread().interrupt();
        throw ApiException.getNewWithCause("Interrupted while getting a call token to make the login call",
                username, e);
    }

    DateTime start = new DateTime();

    LoginResponse response;
    try {
        response = binding.login(loginParam);
    } catch (InvalidIdFault_Exception e) {
        throw ApiException.getNewWithCauseAndStubApiFault("Invalid Id", username, e, e.getFaultInfo());
    } catch (LoginFault_Exception e) {
        throw ApiException.getNewWithCauseAndStubApiFault("Bad credentials for user '" + username + "'",
                username, e, e.getFaultInfo());
    } catch (UnexpectedErrorFault_Exception e) {
        throw ApiException.getNewWithCauseAndStubApiFault("Unexpected error", username, e, e.getFaultInfo());
    } catch (WebServiceException e) {
        throw ApiException.getNewWithCause("Web Service exception", username, e);
    } finally {
        callSemaphore.release();

        DateTime finish = new DateTime();
        Duration duration = new Duration(start, finish);

        long actualDuration = duration.getMillis();
        if (actualDuration > EXPECTED_LOGIN_DURATION) {
            logger.warn("Login took " + actualDuration + "ms, expected to take no more than "
                    + EXPECTED_LOGIN_DURATION + "ms, user = " + username);
        } else {
            logger.trace("Login took " + actualDuration);
        }
    }

    LoginResultType loginResult = response.getResult();
    logger.debug("User " + username + " using partner endpoint " + loginResult.getServerUrl());

    // don't bother checking if the password is expired; wait for them to try and do something
    // with it...

    Id orgId = new Id(loginResult.getUserInfo().getOrganizationId());
    String sessionId = loginResult.getSessionId();

    return new BindingConfig(orgId, sessionId, loginResult.getServerUrl(), loginResult.getMetadataServerUrl(),
            username);
}

From source file:com.triptheone.joda.Stopwatch.java

License:Apache License

/**
 * Gets the time that has elapsed from the start time until now
 * @return Duration object holding the elapsed time
 *//*from  w w  w  .  j  a  v a  2s  . c o m*/
public Duration getElapsedTime() {
    return new Duration(start, Instant.now());
}

From source file:com.vaushell.shaarlijavaapi.ShaarliClient.java

License:Open Source License

private DateTime generateDateID() {
    synchronized (this) {
        DateTime now = new DateTime();

        if (lastGeneratedDate != null) {
            Duration diff = new Duration(lastGeneratedDate, now);
            while (diff.getMillis() < 1000L) {
                try {
                    // It's better than a Thread.sleep in a synchronized block
                    wait(1000L - diff.getMillis());
                } catch (final InterruptedException ex) {
                    // Ignore
                }/*from w  ww .j av a 2s  .c  om*/

                now = new DateTime();
                diff = new Duration(lastGeneratedDate, now);
            }
        }

        lastGeneratedDate = now;

        return lastGeneratedDate;
    }
}

From source file:com.vaushell.superpipes.nodes.A_Node.java

License:Open Source License

/**
 * Pop the last message.//ww w. j a  v  a 2 s  . c om
 *
 * @return the message
 * @throws InterruptedException
 */
protected Message getLastMessageOrWait() throws InterruptedException {
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getNodeID() + "] getLastMessageOrWait");
    }

    final Message message;
    synchronized (internalStack) {
        while (internalStack.isEmpty()) {
            internalStack.wait();
        }

        message = internalStack.pollLast();
    }

    if (lastPop != null && antiBurst != null) {
        // Null for now
        final Duration elapsed = new Duration(lastPop, null);

        final Duration remaining = antiBurst.minus(elapsed);
        if (remaining.getMillis() > 0L) {
            Thread.sleep(remaining.getMillis());
        }
    }

    lastPop = new DateTime();

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("[" + getNodeID() + "] wait message and get message=" + Message.formatSimple(message));
    }

    return message;
}

From source file:com.vaushell.superpipes.nodes.A_Node.java

License:Open Source License

/**
 * Pop the last message./*from w  w w .j  a  v a  2  s.  c om*/
 *
 * @param timeout max time to wait. If timeout is smaller than antiburst, use antiburst.
 * @return the message (or null if empty)
 * @throws InterruptedException
 */
protected Message getLastMessageOrWait(final Duration timeout) throws InterruptedException {
    if (timeout == null) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getNodeID() + "] getLastMessageOrWait() : timeout=" + timeout);
    }

    final Message message;
    synchronized (internalStack) {
        DateTime start = new DateTime();
        Duration remaining = timeout;
        while (internalStack.isEmpty() && remaining.getMillis() > 0L) {
            internalStack.wait(remaining.getMillis());

            final DateTime now = new DateTime();

            final Duration elapsed = new Duration(start, now);

            remaining = remaining.minus(elapsed);

            start = now;
        }

        message = internalStack.pollLast();
    }

    if (lastPop != null && antiBurst != null) {
        // Null for now
        final Duration elapsed = new Duration(lastPop, null);

        final Duration remaining = antiBurst.minus(elapsed);
        if (remaining.getMillis() > 0L) {
            Thread.sleep(remaining.getMillis());
        }
    }

    lastPop = new DateTime();

    if (LOGGER.isDebugEnabled()) {
        if (message == null) {
            LOGGER.debug("[" + getNodeID() + "] wait message for " + timeout + "ms and get nothing");
        } else {
            LOGGER.debug("[" + getNodeID() + "] wait message for " + timeout + "ms and get message="
                    + Message.formatSimple(message));
        }
    }

    return message;
}

From source file:com.vaushell.superpipes.nodes.test.N_ReceiveBlocking.java

License:Open Source License

/**
 * Get the actual processing message, or wait it.
 *
 * @param timeout a timeout/*from   w  w  w . j a  va 2s  .  c  om*/
 * @return the Message
 * @throws InterruptedException
 */
public Message getProcessingMessageOrWait(final Duration timeout) throws InterruptedException {
    if (timeout == null) {
        throw new IllegalArgumentException();
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("[" + getNodeID() + "] getProcessingMessageOrWait() : timeout=" + timeout);
    }

    synchronized (messages) {
        DateTime start = new DateTime();
        Duration remaining = timeout;
        while (messages.isEmpty() && remaining.getMillis() > 0L) {
            messages.wait(remaining.getMillis());

            final DateTime now = new DateTime();

            final Duration elapsed = new Duration(start, now);

            remaining = remaining.minus(elapsed);

            start = now;
        }

        return messages.pollFirst();
    }
}

From source file:com.vaushell.superpipes.tools.retry.A_Retry.java

License:Open Source License

/**
 * Execute.//from w  w w. j a  v  a 2s .  co  m
 *
 * @return Function returns if necessary.
 * @throws RetryException
 */
public T execute() throws RetryException {
    start = new DateTime();

    while (true) {
        try {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("try " + tryCount + "/" + retry);
            }

            return executeContent();
        } catch (final Throwable ex) {
            // Error
            if (tryCount >= retry) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("try count reached");
                }

                throw new RetryException(ex);
            }

            if (maxDuration.getMillis() > 0L) {
                final Duration actualDuration = new Duration(start, null);

                if (!actualDuration.isShorterThan(maxDuration)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("try delay reached");
                    }

                    throw new RetryException(ex);
                }
            }
        }

        if (waitTime.getMillis() > 0L) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(
                        "try " + tryCount + "/" + retry + " failed. Wait " + waitTime + " before next retry");
            }

            try {
                Thread.sleep(waitTime.getMillis());
            } catch (final InterruptedException ex) {
                // Ignore
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("try " + tryCount + "/" + retry + " failed. Don't wait");
            }
        }

        // First, multiply time
        waitTime = new Duration((long) ((double) waitTime.getMillis() * waitTimeMultiplier));

        // Second, add jitter
        if (jitterRange > 0) {
            final int jitter = random.nextInt(jitterRange);
            if (random.nextBoolean()) {
                waitTime = waitTime.plus((long) jitter);
            } else {
                if ((long) jitter < waitTime.getMillis()) {
                    waitTime = waitTime.minus((long) jitter);
                }
            }
        }

        ++tryCount;
    }
}

From source file:com.webarch.common.datetime.DateTimeUtils.java

License:Apache License

/**
 * ?//from   www. jav a 2s.  c  o  m
 *
 * @param startTime
 * @param endTime
 * @return
 */
public static long getPeriodMillis(Date startTime, Date endTime) {
    Duration duration = new Duration(new DateTime(startTime), new DateTime(endTime));
    return duration.getMillis();
}

From source file:com.wellsandwhistles.android.redditsp.common.SRTime.java

License:Open Source License

public static String formatDurationFrom(final Context context, final long startTime) {
    final String space = " ";
    final String comma = ",";
    final String separator = comma + space;

    final long endTime = utcCurrentTimeMillis();
    final DateTime dateTime = new DateTime(endTime);
    final DateTime localDateTime = dateTime.withZone(DateTimeZone.getDefault());
    Period period = new Duration(startTime, endTime).toPeriodTo(localDateTime);

    PeriodFormatter periodFormatter = new PeriodFormatterBuilder().appendYears().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_year), context.getString(R.string.time_years))
            .appendSeparator(separator).appendMonths().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_month), context.getString(R.string.time_months))
            .appendSeparator(separator).appendDays().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_day), context.getString(R.string.time_days))
            .appendSeparator(separator).appendHours().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_hour), context.getString(R.string.time_hours))
            .appendSeparator(separator).appendMinutes().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_min), context.getString(R.string.time_mins))
            .appendSeparator(separator).appendSeconds().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_sec), context.getString(R.string.time_secs))
            .appendSeparator(separator).appendMillis().appendSuffix(space)
            .appendSuffix(context.getString(R.string.time_ms)).toFormatter();

    String duration = periodFormatter.print(period.normalizedStandard(PeriodType.yearMonthDayTime()));

    List<String> parts = Arrays.asList(duration.split(comma));
    if (parts.size() >= 2) {
        duration = parts.get(0) + comma + parts.get(1);
    }//ww w.j a  va2 s  .c om

    return String.format(context.getString(R.string.time_ago), duration);
}

From source file:com.yahoo.bard.webservice.data.time.DefaultTimeGrain.java

License:Apache License

/**
 * Constructor./* w w w  .  ja va2 s . c o  m*/
 *
 * @param period  Period of the TimeGRain
 * @param roundFunction  Function to round a DateTime to the start of the bucket it falls in
 * @param alignmentDescription  A human-readable description of how this TimeGrain aligns
 * @param satisfyingGrains  A collection of TimeGrains that satisfy this TimeGrain
 */
DefaultTimeGrain(ReadablePeriod period, UnaryOperator<DateTime> roundFunction, String alignmentDescription,
        TimeGrain... satisfyingGrains) {

    this.period = period;
    this.roundFloor = roundFunction;
    this.satisfyingGrains = new HashSet<>(Arrays.asList(satisfyingGrains));
    this.alignmentDescription = alignmentDescription;

    DateTime dateTime = new DateTime();
    this.estimatedDuration = new Duration(roundFloor(dateTime), roundFloor(dateTime).plus(period));
}