Example usage for org.joda.time Duration standardSeconds

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

Introduction

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

Prototype

public static Duration standardSeconds(long seconds) 

Source Link

Document

Create a duration with the specified number of seconds assuming that there are the standard number of milliseconds in a second.

Usage

From source file:com.predic8.membrane.core.interceptor.apimanagement.rateLimiter.AMRateLimiter.java

License:Apache License

private void fillPolicyCleanupTimes() {
    policyRateLimits.clear();/*from  ww w  .j av  a 2  s .  c  o  m*/
    for (Policy policy : amc.getPolicies().values()) {
        String name = policy.getName();
        int requests = policy.getRateLimit().getRequests();
        Duration interval = Duration.standardSeconds(policy.getRateLimit().getInterval());
        HashSet<String> services = new HashSet<String>(policy.getServiceProxies());
        PolicyRateLimit prl = new PolicyRateLimit();
        prl.setName(name);
        prl.setRequests(requests);
        prl.setInterval(interval);
        prl.setServices(services);
        prl.incrementNextCleanup();
        policyRateLimits.put(name, prl);
    }
}

From source file:com.terry.dataflow.TwitterPipeline.java

License:Apache License

public static void main(String[] args) {
    Pipeline p = Pipeline.create(PipelineOptionsFactory.fromArgs(args).withValidation().create());

    @SuppressWarnings("unchecked")
    PCollection<KV<String, Iterable<String>>> nlprocessed = (PCollection<KV<String, Iterable<String>>>) p
            .apply(PubsubIO.Read.named("ReadFromPubSub").topic("projects/useful-hour-138023/topics/twitter"))
            .apply(ParDo.named("Parse Twitter").of(new ParseTwitterFeedDoFn()))
            .apply(ParDo.named("NL Processing").of(new NLAnalyticsDoFn()));

    // Noun handling sub-pipeline
    List<TableFieldSchema> fields = new ArrayList<>();
    fields.add(new TableFieldSchema().setName("date").setType("TIMESTAMP"));
    fields.add(new TableFieldSchema().setName("noun").setType("STRING"));
    fields.add(new TableFieldSchema().setName("count").setType("INTEGER"));
    TableSchema schema = new TableSchema().setFields(fields);

    nlprocessed.apply(ParDo.named("NounFilter").of(new NounFilter()))
            .apply(Window.<String>into(FixedWindows.of(Duration.standardSeconds(30))))
            .apply(Count.<String>perElement()).apply(ParDo.named("Noun Formating").of(new AddTimeStampNoun()))
            .apply(BigQueryIO.Write.named("Write Noun Count to BQ").to(NOWN_TABLE).withSchema(schema)
                    .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
                    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));

    // Adj handling sub-pipeline
    fields = new ArrayList<>();
    fields.add(new TableFieldSchema().setName("date").setType("TIMESTAMP"));
    fields.add(new TableFieldSchema().setName("adj").setType("STRING"));
    fields.add(new TableFieldSchema().setName("count").setType("INTEGER"));
    schema = new TableSchema().setFields(fields);

    nlprocessed.apply(ParDo.named("AdjFilter").of(new AdjFilter()))
            .apply(Window.<String>into(FixedWindows.of(Duration.standardSeconds(30))))
            .apply(Count.<String>perElement()).apply(ParDo.named("Adj Formating").of(new AddTimeStampAdj()))
            .apply(BigQueryIO.Write.named("Write Adj Count to BQ").to(ADJ_TABLE).withSchema(schema)
                    .withWriteDisposition(BigQueryIO.Write.WriteDisposition.WRITE_APPEND)
                    .withCreateDisposition(BigQueryIO.Write.CreateDisposition.CREATE_IF_NEEDED));

    p.run();/*from   w  ww  .j  a va  2  s .c  o  m*/
}

From source file:com.terry.df.StarterPipeline.java

License:Apache License

public static void main(String[] args) {
    Pipeline p = Pipeline.create(PipelineOptionsFactory.fromArgs(args).withValidation().create());

    // 1.     ?? ? ?
    // 2.  ?, ?  

    p.apply(Create.of("1,0.1,Hello", "2,0.9,World", "2,0.2,World", "2,0.2,World", "2,-0.9,World",
            "1,-0.1,World", "1,0.3,World", "1,-0.1,World", "1,0.7,World"))
            .apply(ParDo.of(new DoFn<String, KV<Integer, DataClass>>() {
                @Override/*from  w ww . j  a va2 s .  c  o m*/
                public void processElement(ProcessContext c) {
                    String str = c.element();
                    StringTokenizer st = new StringTokenizer(str, ",");

                    String str_category = st.nextToken();
                    String str_point = st.nextToken();
                    String text = st.nextToken();

                    Integer category = Integer.parseInt(str_category);
                    Float point = Float.parseFloat(str_point);

                    DataClass dt = new DataClass(category, point, text);
                    KV<Integer, DataClass> outputValue = KV.of(category, dt);
                    c.output(outputValue);
                }
            })).apply(Window.<KV<Integer, DataClass>>into(FixedWindows.of(Duration.standardSeconds(5))))
            .apply(ParDo.named("Print for debug")
                    .of(new DoFn<KV<Integer, DataClass>, KV<Integer, DataClass>>() {

                        @Override
                        public void processElement(ProcessContext c) {
                            Integer key = c.element().getKey();
                            DataClass value = c.element().getValue();

                            LOG.info("key :" + key + "point:" + value.getPoint() + " text:" + value.getText());

                            c.output(c.element());
                        }

                    }))
            .apply(GroupByKey.<Integer, DataClass>create())
            .apply(ParDo.named("Caculate Stat").of(new StatDoFn()))
            .apply(ParDo.named("Print Result").of(new PrintResultDoFn()));

    p.run();
}

From source file:com.threewks.thundr.request.servlet.ServletSupport.java

License:Apache License

public static Cookie toThundrCookie(javax.servlet.http.Cookie cookie) {
    // @formatter:off
    Duration expires = cookie.getMaxAge() > 0 ? Duration.standardSeconds(cookie.getMaxAge()) : null;
    return Cookie.build(cookie.getName()).withValue(cookie.getValue()).withComment(cookie.getComment())
            .withDomain(cookie.getDomain()).withMaxAge(expires).withPath(cookie.getPath())
            .withSecure(cookie.getSecure()).withVersion(cookie.getVersion()).build();
    // @formatter:on
}

From source file:com.tomtom.speedtools.geometry.Geo.java

License:Apache License

/**
 * Return a best estimate for the minimum travel time required to get from A to B. The estimate is based on the
 * distance rounded to the <b>roundToMeters</b> given.  This method must be optimized for calculation speed and is
 * not allowed to call out to other systems, or databases.
 *
 * @param from          From point A./*from   w w  w  . ja va2 s  .c  o  m*/
 * @param to            To point B.
 * @param roundToMeters The number of metres the distance should be rounded to before calculation (must be &gt;= 0).
 * @return Estimated minimum travel time.
 */
@Nonnull
public static Duration estimatedMinTravelTime(@Nonnull final GeoPoint from, @Nonnull final GeoPoint to,
        final int roundToMeters) {
    assert from != null;
    assert to != null;
    assert roundToMeters >= 0;

    //  Round distance in meters to the nearest roundToMeters.
    final int roundToMetersOr1 = (roundToMeters == 0) ? 1 : roundToMeters;
    final double distanceDivByRoundToMeters = distanceInMeters(from, to) / roundToMetersOr1;
    double distance = Math.round(distanceDivByRoundToMeters) * roundToMetersOr1;

    double totSecs = 0.0;
    int i = 0;
    while (distance > 0) {

        // Get crow distance and speed.
        final double crowM = CROW_FLIGHT_SPEED_TABLE[i] * 1000.0;
        ++i;
        final double crowMPerS = (CROW_FLIGHT_SPEED_TABLE[i] * 1000.0) / 3600.0;
        ++i;
        final double nextCrowM = CROW_FLIGHT_SPEED_TABLE[i] * 1000.0;

        // Calculate remaining distance and time required.
        final double distM = Math.min(distance, (nextCrowM - crowM));
        final double secs = distM / crowMPerS;
        totSecs = totSecs + secs;

        // Reduce remaining distance.
        distance = distance - (nextCrowM - crowM);
    }
    return Duration.standardSeconds(Math.round(totSecs));
}

From source file:de.chaosfisch.google.youtube.upload.Upload.java

License:Open Source License

public void setDateTimeOfStart(final DateTime dateTimeOfStart) {
    if (null == dateTimeOfStart || dateTimeOfStart.isBefore(Instant.now().minus(Duration.standardSeconds(5)))) {
        this.dateTimeOfStart = null;
    } else {/* w  ww.  ja  v a  2  s .  c o  m*/
        this.dateTimeOfStart = dateTimeOfStart;
    }
}

From source file:de.rwth.idsg.xsharing.router.persistence.domain.routes.representation.factory.UraRepresentationFactory.java

License:Open Source License

private static <T extends AbstractLegRepresentation> List<IndividualTrip> getListOfTrips(List<T> reps,
        DateTime startTime) {//from   www  .j a va2 s  .c o m
    List<IndividualTrip> resultList = new ArrayList<>(reps.size());
    DateTime arrival;
    DateTime departure = startTime;

    // convert legs one by one
    for (T leg : reps) {
        arrival = departure;
        Location startLocation;
        Location endLocation;
        Integer startDelay = 0;
        Integer endDelay = 0;

        switch (leg.getType()) {

        // Station -> Station
        //
        case BikeLeg: {
            // incorporate delays by check-out etc.
            startDelay += leg.getTransferTime();
            endDelay += leg.getTransferTime();

            StationRepresentation startStation = null;
            StationRepresentation endStation = null;
            if (leg instanceof LegDetailsRepresentation) {
                startStation = ((LegDetailsRepresentation) leg).getStartStation();
                endStation = ((LegDetailsRepresentation) leg).getEndStation();
            }
            startLocation = getUraStation(leg.getFrom(), startStation);
            endLocation = getUraStation(leg.getTo(), endStation);
        }
            break;

        // Station -> Position
        //
        case CarLeg: {
            // incorporate delays by check-out etc.
            startDelay += leg.getTransferTime();

            StationRepresentation startStation = null;
            if (leg instanceof LegDetailsRepresentation) {
                startStation = ((LegDetailsRepresentation) leg).getStartStation();
            }
            startLocation = getUraStation(leg.getFrom(), startStation);
            endLocation = getUraPosition(leg.getTo());
        }
            break;

        // Position -> Position
        //
        case WalkingLeg: {
            startLocation = getUraPosition(leg.getFrom());
            endLocation = getUraPosition(leg.getTo());
        }
            break;

        default:
            throw new RuntimeException("Unexpected leg type");
        }

        departure = arrival.plus(Duration.standardSeconds(startDelay));

        // predictions need to include delay by transfers
        Prediction start = new Prediction.Builder().withScheduledArrivalTime(arrival)
                .withScheduledDepartureTime(departure).withLocation(startLocation).build();

        arrival = departure.plus(Duration.standardSeconds(leg.getDuration()));
        departure = arrival.plus(Duration.standardSeconds(endDelay));

        Prediction end = new Prediction.Builder().withScheduledArrivalTime(arrival)
                .withScheduledDepartureTime(departure).withLocation(endLocation).build();

        PathData path = null;
        if (leg instanceof LegDetailsRepresentation) {
            path = new PathData.Builder()
                    .withRouteGeometry(convertRouteGeometry((LegDetailsRepresentation) leg)).build();
        }

        IndividualTrip trip = new IndividualTrip.Builder()
                .withDuration(Duration.standardSeconds((long) leg.getDuration())).withStart(start).withEnd(end)
                .withLengthInM(leg.getDistance()).withUuid(String.valueOf(leg.getId()))
                .withModalType(toModalType(leg.getType())).withPathDataSource("xsharing-iv").withPathData(path)
                .build();

        resultList.add(trip);
    }
    return resultList;
}

From source file:es.usc.citius.servando.calendula.pinlock.UnlockStateManager.java

License:Open Source License

/**
 * Checks if unlock is set and not expired
 *
 * @return <code>true</code> if unlocked, false otherwise.
 *//*from ww  w  .ja v  a2s .co  m*/
public boolean isUnlocked() {
    LogUtil.v(TAG, "isUnlocked() called");
    if (unlockTimestamp != null) {
        Duration diff = new Duration(unlockTimestamp, DateTime.now());
        // need to be a string to use a ListPreference
        final String maxDurationStr = PreferenceUtils.getString(PreferenceKeys.UNLOCK_PIN_TIMEOUT,
                DEFAULT_UNLOCK_DURATION_SECONDS);
        Duration maxDuration = Duration.standardSeconds(Integer.parseInt(maxDurationStr));
        LogUtil.d(TAG, "Max unlock duration is " + maxDuration.toString());
        if (diff.compareTo(maxDuration) <= 0) {
            LogUtil.d(TAG, "isUnlocked() returned: " + true);
            return true;
        } else {
            LogUtil.d(TAG, "isUnlocked: unlock has expired, unsetting and returning null");
            unlockTimestamp = null;
            return false;
        }
    } else {
        LogUtil.d(TAG, "isUnlocked: timestamp is null");
    }
    return false;
}

From source file:fr.amap.commons.animation.Timeline.java

/**
 * /*  w w w.ja  v  a  2s .c  o m*/
 * @param timePosition
 * @param keyFrame
 * @return The nearest DateTime in the timeline from the given DateTime.
 */
public DateTime insertKeyFrame(DateTime timePosition, KeyFrame keyFrame) {

    int index = getNearestIndex(timePosition);

    insertKeyFrame(index, keyFrame);

    DateTime nearestDateTime = startTime.plus(Duration.standardSeconds((long) ((index * timeStep) * 3600)));

    return nearestDateTime;
}

From source file:fr.amap.commons.animation.Timeline.java

public DateTime insertEvent(DateTime timePosition, Event event) {

    int index = getNearestIndex(timePosition);

    super.insertEvent(index, event);

    DateTime nearestDateTime = startTime.plus(Duration.standardSeconds((long) ((index * timeStep) * 3600)));

    return nearestDateTime;
}