Example usage for org.joda.time Duration standardDays

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

Introduction

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

Prototype

public static Duration standardDays(long days) 

Source Link

Document

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

Usage

From source file:org.hawkular.metrics.core.service.MetricsServiceImpl.java

License:Apache License

public void setDefaultTTL(int defaultTTL) {
    this.defaultTTL = Duration.standardDays(defaultTTL).toStandardSeconds().getSeconds();
}

From source file:org.jevis.jeconfig.sample.SampleEditor.java

License:Open Source License

/**
 *
 * @param owner/*from w ww .j av  a  2 s  .  c  o m*/
 * @param attribute
 * @return
 */
public Response show(Stage owner, final JEVisAttribute attribute) {
    final Stage stage = new Stage();

    _attribute = attribute;
    stage.setTitle("Sample Editor");
    stage.initModality(Modality.NONE);
    stage.initOwner(owner);

    VBox root = new VBox();
    root.setMaxWidth(2000);

    final Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.setWidth(740);
    stage.setHeight(690);
    stage.setMaxWidth(2000);
    stage.initStyle(StageStyle.UTILITY);
    stage.setResizable(false);

    Screen screen = Screen.getPrimary();
    if (screen.getBounds().getHeight() < 740) {
        stage.setWidth(screen.getBounds().getHeight());
    }

    HBox buttonPanel = new HBox();

    ok.setDefaultButton(true);

    //        Button export = new Button("Export");
    Button cancel = new Button("Close");
    cancel.setCancelButton(true);

    Region spacer = new Region();
    spacer.setMaxWidth(2000);

    Label startLabel = new Label("From:");
    DatePicker startdate = new DatePicker();

    startdate.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    //        startdate.getCalendarView().todayButtonTextProperty().set("Today");
    startdate.getCalendarView().setShowWeeks(false);
    startdate.getStylesheets().add(JEConfig.getResource("DatePicker.css"));

    Label endLabel = new Label("Until:");
    DatePicker enddate = new DatePicker();

    enddate.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    enddate.getCalendarView().todayButtonTextProperty().set("Today");
    enddate.getCalendarView().setShowWeeks(true);
    enddate.getStylesheets().add(JEConfig.getResource("DatePicker.css"));

    SampleTabelExtension tabelExtension = new SampleTabelExtension(attribute, stage);//Default plugin

    //        final List<JEVisSample> samples = attribute.getAllSamples();
    if (attribute.hasSample()) {
        _from = attribute.getTimestampFromLastSample().minus(Duration.standardDays(1));
        _until = attribute.getTimestampFromLastSample();

        startdate = new DatePicker(Locale.getDefault(), _from.toDate());
        startdate.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        startdate.setSelectedDate(_from.toDate());
        startdate.getCalendarView().setShowWeeks(false);
        startdate.getStylesheets().add(JEConfig.getResource("DatePicker.css"));
        startdate.setMaxWidth(100d);

        //            enddate.setSelectedDate(_until.toDate());
        enddate.selectedDateProperty().setValue(_until.toDate());
        enddate.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        enddate.setSelectedDate(_until.toDate());
        enddate.getCalendarView().setShowWeeks(true);
        enddate.getStylesheets().add(JEConfig.getResource("DatePicker.css"));
        enddate.setMaxWidth(100d);

    }

    Node preclean = buildProcessorBox(attribute.getObject());

    Label timeRangeL = new Label("Time range");
    timeRangeL.setStyle("-fx-font-weight: bold");
    GridPane timeSpan = new GridPane();
    timeSpan.setHgap(5);
    timeSpan.setVgap(2);
    timeSpan.add(timeRangeL, 0, 0, 2, 1); // column=1 row=0
    timeSpan.add(startLabel, 0, 1, 1, 1); // column=1 row=0
    timeSpan.add(endLabel, 0, 2, 1, 1); // column=1 row=0

    timeSpan.add(startdate, 1, 1, 1, 1); // column=1 row=0
    timeSpan.add(enddate, 1, 2, 1, 1); // column=1 row=0

    buttonPanel.getChildren().addAll(timeSpan, preclean, spacer, ok, cancel);
    //        buttonPanel.getChildren().addAll(startLabel, startdate, endLabel, enddate, preclean, spacer, ok, cancel);
    buttonPanel.setAlignment(Pos.BOTTOM_RIGHT);
    buttonPanel.setPadding(new Insets(10, 10, 10, 10));
    buttonPanel.setSpacing(15);//10
    buttonPanel.setMaxHeight(25);
    HBox.setHgrow(spacer, Priority.ALWAYS);
    //        HBox.setHgrow(export, Priority.NEVER);
    HBox.setHgrow(ok, Priority.NEVER);
    HBox.setHgrow(cancel, Priority.NEVER);

    extensions.add(tabelExtension);
    extensions.add(new SampleGraphExtension(attribute));
    extensions.add(new AttributeStatesExtension(attribute));
    extensions.add(new SampleExportExtension(attribute));

    final List<Tab> tabs = new ArrayList<>();

    //        boolean fistEx = true;
    for (SampleEditorExtension ex : extensions) {
        //            _dataChanged
        //            if (fistEx) {
        //                System.out.println("is first");
        //                ex.setSamples(attribute, samples);
        //                ex.update();
        //                fistEx = false;
        //            }

        Tab tabEditor = new Tab();
        tabEditor.setText(ex.getTitel());
        tabEditor.setContent(ex.getView());
        tabs.add(tabEditor);

    }
    _visibleExtension = extensions.get(0);
    updateSamples(attribute, _from, _until, extensions);

    final TabPane tabPane = new TabPane();
    //        tabPane.setMaxWidth(2000);
    //        tabPane.setMaxHeight(2000);
    tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.UNAVAILABLE);

    tabPane.getTabs().addAll(tabs);

    //        tabPane.setPrefSize(200, 200);
    //        tabPane.getSelectionModel().selectFirst();
    GridPane gp = new GridPane();
    gp.setStyle("-fx-background-color: white;");

    gp.setHgap(0);
    gp.setVgap(0);
    int y = 0;
    gp.add(tabPane, 0, y);

    Node header = DialogHeader.getDialogHeader(ICON, "Sample Editor");//new Separator(Orientation.HORIZONTAL),

    root.getChildren().addAll(header, gp, new Separator(Orientation.HORIZONTAL), buttonPanel);
    VBox.setVgrow(buttonPanel, Priority.NEVER);
    VBox.setVgrow(header, Priority.NEVER);

    //        ok.setDisable(true);
    ok.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent t) {
            System.out.println("OK action to: " + _visibleExtension.getTitel());
            _visibleExtension.sendOKAction();
        }
    });

    tabPane.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {

        @Override
        public void changed(ObservableValue<? extends Tab> ov, Tab t, Tab t1) {
            //                System.out.println("tabPane.getSelectionModel(): " + t1.getText());

            for (SampleEditorExtension ex : extensions) {
                if (ex.getTitel().equals(t1.getText())) {
                    ex.update();
                    _visibleExtension = ex;
                }
            }
            //                }
        }
    });

    startdate.selectedDateProperty().addListener(new ChangeListener<Date>() {

        @Override
        public void changed(ObservableValue<? extends Date> ov, Date t, Date t1) {
            DateTime from = new DateTime(t1.getTime());
            _from = from;
            //                _visibleExtension.setSamples(attribute, attribute.getSamples(_from, _until));
            updateSamples(attribute, _from, _until, extensions);
        }
    });

    enddate.selectedDateProperty().addListener(new ChangeListener<Date>() {

        @Override
        public void changed(ObservableValue<? extends Date> ov, Date t, Date t1) {
            DateTime until = new DateTime(t1.getTime());
            _until = until;
            //                _visibleExtension.setSamples(attribute, attribute.getSamples(_from, _until));
            updateSamples(attribute, _from, _until, extensions);
        }
    });

    cancel.setOnAction(new EventHandler<ActionEvent>() {
        @Override
        public void handle(ActionEvent t) {
            stage.close();
            response = Response.CANCEL;

        }
    });

    //TODO: replace Workaround.., without it the first tab will be emty
    //        tabPane.getSelectionModel().selectLast();
    //        tabPane.getSelectionModel().selectFirst();
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            tabPane.getSelectionModel().selectLast();
            tabPane.getSelectionModel().selectFirst();
        }
    });

    stage.showAndWait();

    return response;
}

From source file:org.obm.push.utils.DateUtils.java

License:Open Source License

public static long daysToSeconds(long days) {
    return Duration.standardDays(days).getStandardSeconds();
}

From source file:org.openmainframe.ade.ext.main.Train.java

License:Open Source License

/**
 * Parse the AdeExt Argument.  This method is used to parse
 * the input argument in AdeCore./*from w  w  w.  j a  va  2s.  c  o m*/
 * 
 * @param args
 * @return 
 * @throws AdeException
 */
public final ArrayList<String> parseAdeExtArgs(String[] args) throws AdeException {
    ArrayList<String> adeArgs;
    adeArgs = new ArrayList<String>();

    if (args.length == 0) {
        usageError("Expecting at least one argument");
        return new ArrayList<String>(0);
    }
    if (args.length > 3) {
        usageError("Too many arguments");
    }

    /* Convert the Source argument to AnalysisGroup */
    if (args[0].equalsIgnoreCase("all")) {
        adeArgs.add("-a");
    } else {
        /* Add the source.  
         * Note that Ade expect analysisGroup instead of source. 
         *
         * In Upload and Analyze, the AnalysisGroup always use the same name as 
         * the sourceId.  Therefore, the sourceId input here can be used as 
         * AnalysisGroup name.
         */
        adeArgs.add("-s");
        adeArgs.add(args[0]);
    }

    //"MM/dd/yyyy HH:mm ZZZ"
    final DateTimeFormatter outFormatter = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm ZZZ").withOffsetParsed()
            .withZoneUTC();

    /* Handle the end date if exist */

    if (args.length > 2) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy").withOffsetParsed()
                .withZoneUTC();
        m_endDateTime = formatter.parseDateTime(args[2]);

        /* Move the endDate's time to the end of date.  AdeCore requires the end date
         * to be the start day of the next day. 
         * 
         * For example, if the endDate specified is 10/10.  The endDate will be set to
         * 10/11 00:00:00.  This will include the entire 10/10 in the Model.  */
        adeArgs.add("-end-date");
        m_endDateTime = m_endDateTime.withDurationAdded(Duration.standardDays(1), 1);
        adeArgs.add(m_endDateTime.toString(outFormatter));
    } else {
        /* If endDate wasn't specified, don't specify it. */
        m_endDateTime = null;
    }

    /* Handle the start date if exist */
    if (args.length > 1) {
        final DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy").withOffsetParsed()
                .withZoneUTC();
        m_startDateTime = formatter.parseDateTime(args[1]);
        adeArgs.add("-start-date");
        adeArgs.add(m_startDateTime.toString(outFormatter));
    } else {
        m_startDateTime = null;
    }

    /* call the super class with the converted arguments */
    StringBuilder bldadeArgsString = new StringBuilder("");
    for (String arg : adeArgs) {
        bldadeArgsString.append(arg + " ");
    }
    logger.trace("Arguments used to call TrainLog: " + bldadeArgsString.toString());

    return adeArgs;
}

From source file:org.qipki.ca.domain.ca.CAMixin.java

License:Open Source License

@Override
public X509Certificate sign(X509Profile x509profile, PKCS10CertificationRequest pkcs10) {
    LOGGER.debug(//from  www  . j ava 2s . c  o  m
            "Handling a PKCS#10 Certificate Signing Request using X509Profile " + x509profile.name().get());
    try {

        ensureX509ProfileIsAllowed(x509profile);

        List<X509ExtensionHolder> extensions = x509ExtReader.extractRequestedExtensions(pkcs10);
        ensureNoIllegalRequestedExtensions(extensions);

        // Adding extensions commons to all profiles
        SubjectKeyIdentifier subjectKeyID = x509ExtBuilder.buildSubjectKeyIdentifier(pkcs10.getPublicKey());
        extensions.add(new X509ExtensionHolder(X509Extensions.SubjectKeyIdentifier, false, subjectKeyID));
        AuthorityKeyIdentifier authKeyID = x509ExtBuilder
                .buildAuthorityKeyIdentifier(certificate().getPublicKey());
        extensions.add(new X509ExtensionHolder(X509Extensions.AuthorityKeyIdentifier, false, authKeyID));

        // Applying X509Profile on issued X509Certificate
        if (x509profile.basicConstraints().get().subjectIsCA().get()) {
            BasicConstraints bc = x509ExtBuilder
                    .buildCABasicConstraints(x509profile.basicConstraints().get().pathLengthConstraint().get());
            extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints,
                    x509profile.basicConstraints().get().critical().get(), bc));
        } else {
            BasicConstraints bc = x509ExtBuilder.buildNonCABasicConstraints();
            extensions.add(new X509ExtensionHolder(X509Extensions.BasicConstraints,
                    x509profile.basicConstraints().get().critical().get(), bc));
        }
        KeyUsage keyUsages = x509ExtBuilder.buildKeyUsages(x509profile.keyUsages().get().keyUsages().get());
        extensions.add(new X509ExtensionHolder(X509Extensions.KeyUsage,
                x509profile.keyUsages().get().critical().get(), keyUsages));

        ExtendedKeyUsage extendedKeyUsage = x509ExtBuilder
                .buildExtendedKeyUsage(x509profile.extendedKeyUsages().get().extendedKeyUsages().get());
        extensions.add(new X509ExtensionHolder(X509Extensions.ExtendedKeyUsage,
                x509profile.extendedKeyUsages().get().critical().get(), extendedKeyUsage));

        NetscapeCertType netscapeCertType = x509ExtBuilder
                .buildNetscapeCertTypes(x509profile.netscapeCertTypes().get().netscapeCertTypes().get());
        extensions.add(new X509ExtensionHolder(MiscObjectIdentifiers.netscapeCertType,
                x509profile.netscapeCertTypes().get().critical().get(), netscapeCertType));

        String[] crlDistPoints = gatherCRLDistributionPoints();
        if (crlDistPoints.length > 0) {
            CRLDistPoint crlDistPointsExt = x509ExtBuilder
                    .buildCRLDistributionPoints(certificate().getSubjectX500Principal(), crlDistPoints);
            extensions.add(
                    new X509ExtensionHolder(X509Extensions.CRLDistributionPoints, false, crlDistPointsExt));
        }

        DistinguishedName issuerDN = new DistinguishedName(certificate().getSubjectX500Principal());
        DistinguishedName subjectDN = new DistinguishedName(pkcs10.getCertificationRequestInfo().getSubject());
        X509Certificate certificate = x509Generator.generateX509Certificate(privateKey(), issuerDN,
                BigInteger.probablePrime(120, new SecureRandom()), subjectDN, pkcs10.getPublicKey(),
                Duration.standardDays(x509profile.validityDays().get()), extensions);

        return certificate;

    } catch (GeneralSecurityException ex) {
        LOGGER.error(ex.getMessage(), ex);
        throw new QiPkiFailure("Unable to enroll PKCS#10", ex);
    }
}

From source file:org.springframework.analytics.metrics.memory.InMemoryAggregateCounter.java

License:Apache License

private static List<long[]> accumulateDayCounts(Map<Integer, long[]> fromDayCounts, DateTime start,
        DateTime end, int subSize) {
    List<long[]> days = new ArrayList<long[]>();
    Duration step = Duration.standardDays(1);
    long[] emptySubArray = new long[subSize];
    end = end.plusDays(1); // Need to account for an interval which crosses days

    for (DateTime now = start; now.isBefore(end); now = now.plus(step)) {
        int countsByDayKey = now.getYear() * 1000 + now.getDayOfYear();
        long[] dayCounts = fromDayCounts.get(countsByDayKey);

        if (dayCounts == null) {
            // Use an empty array if we don't have data
            dayCounts = emptySubArray;/*  w  ww. j ava  2s.  co  m*/
        }
        days.add(dayCounts);
    }
    return days;
}

From source file:org.wisdom.cache.ehcache.CachedActionInterceptor.java

License:Apache License

/**
 * Intercepts a @Cached action method.//from   w  w w.  j  av a2 s.  co  m
 * If the result of the action is cached, returned it immediately without having actually invoked the action method.
 * In this case, the interception chain is cut.
 * <p>
 * If the result is not yet cached, the interception chain continues, and the result is cached to be used during
 * the next invocation.
 *
 * @param configuration the interception configuration
 * @param context       the interception context
 * @return the result.
 * @throws Exception something bad happened
 */
@Override
public Result call(Cached configuration, RequestContext context) throws Exception {
    // Can we use the Cached version ?
    boolean nocache = HeaderNames.NOCACHE_VALUE
            .equalsIgnoreCase(context.context().header(HeaderNames.CACHE_CONTROL));

    String key;
    if (Strings.isNullOrEmpty(configuration.key())) {
        key = context.request().uri();
    } else {
        key = configuration.key();
    }

    Result result = null;
    if (!nocache) {
        result = (Result) cache.get(key);
    }

    if (result == null) {
        result = context.proceed();
    } else {
        LOGGER.info("Returning cached result for {} (key:{})", context.request().uri(), key);
        return result;
    }

    Duration duration;
    if (configuration.duration() == 0) {
        // Eternity == 1 year.
        duration = Duration.standardDays(365);
    } else {
        duration = Duration.standardSeconds(configuration.duration());
    }

    cache.set(key, result, duration);
    LoggerFactory.getLogger(this.getClass()).info("Caching result of {} for {} seconds (key:{})",
            context.request().uri(), configuration.duration(), key);

    return result;
}

From source file:silvertrout.plugins.packagetracker.Package.java

License:Open Source License

/**
 * Check if package have expired, either if it was created and not updated for a while
 * /*from  ww w.  jav a  2  s.co m*/
 * @return true if package have expired
 */
public boolean expired() {
    Duration timeSinceUpdated = new Duration(new DateTime(created), null);
    Duration timeSinceCreated = new Duration(new DateTime(updated), null);

    return timeSinceUpdated.isLongerThan(Duration.standardDays(PACKAGE_TTL))
            && timeSinceCreated.isLongerThan(Duration.standardDays(PACKAGE_TTL));
}

From source file:ua.com.fielden.platform.example.swing.booking.BookingChartPanelExample.java

private static IBookingChartMouseEventListener<VehicleEntity, BookingEntity> createMouseListener(
        final JLabel taskBar, final Date now) {
    return new IBookingChartMouseEventListener<VehicleEntity, BookingEntity>() {

        private final Duration defaultDuration = Duration.standardDays(1);

        @Override/*w ww . j a  va  2 s  . com*/
        public void mouseClick(final BookingMouseEvent<VehicleEntity, BookingEntity> event) {
            if (event.getTask() == null && event.getSourceEvent().getClickCount() == 2
                    && event.getX().after(now)) {
                addNewSubTask(event);
            } else if (event.getTask() != null) {
                taskBar.setText(
                        event.getTask().getEntity() + ", " + event.getTask().getSubEntity().getBookingStart());
            }
        }

        private void addNewSubTask(final BookingMouseEvent<VehicleEntity, BookingEntity> event) {
            final BookingTask<VehicleEntity, BookingEntity> firstBefore = event.getSource()
                    .getFirstTaskBefore(bookingSeries, event.getX(), event.getY());
            final BookingTask<VehicleEntity, BookingEntity> firstAfter = event.getSource()
                    .getFirstTaskAfter(bookingSeries, event.getX(), event.getY());
            final Date firstBeforeDate = firstBefore != null && firstBefore.getTo() != null
                    && firstBefore.getTo().after(now) ? firstBefore.getTo() : now;
            final Date firstAfterDate = firstAfter != null && firstAfter.getFrom() != null
                    ? firstAfter.getFrom()
                    : new DateTime(event.getX().getTime()).plus(defaultDuration).toDate();
            DateTime start = null;
            DateTime end = null;
            if (firstAfterDate.getTime() - firstBeforeDate.getTime() >= defaultDuration.getMillis()) {
                start = new DateTime(event.getX().getTime() - defaultDuration.getMillis() / 2);
                if (start.isBefore(firstBeforeDate.getTime())) {
                    start = new DateTime(firstBeforeDate.getTime());
                }
                end = start.plus(defaultDuration);
                if (end.isAfter(firstAfterDate.getTime())) {
                    end = new DateTime(firstAfterDate.getTime());
                    start = end.minus(defaultDuration);
                }
            } else {
                start = new DateTime(firstBeforeDate.getTime());
                end = new DateTime(firstAfterDate.getTime());
            }
            final BookingEntity booking = new BookingEntity().//
            setVehicleEntity(event.getSource().getEntity(event.getY())).//
            setBookingStart(start.toDate()).setBookingFinish(end.toDate());
            event.getSource().addTask(bookingSeries, event.getY(), booking);
        }

        @Override
        public void mouseMove(final BookingMouseEvent<VehicleEntity, BookingEntity> event) {
            // TODO Auto-generated method stub

        }

    };
}