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.mirth.connect.server.util.LoginRequirementsChecker.java

License:Open Source License

public long getStrikeTimeRemaining() {
    Duration lockoutPeriod = Duration.standardHours(passwordRequirements.getLockoutPeriod());

    synchronized (userLoginStrikes) {
        Duration strikeDuration = new Duration(
                userLoginStrikes.get(username).getLastStrikeTime().getTimeInMillis(),
                System.currentTimeMillis());
        return lockoutPeriod.minus(strikeDuration).getMillis();
    }//from w w w . j a v a 2s. c o  m
}

From source file:com.mirth.connect.server.util.LoginRequirementsChecker.java

License:Open Source License

private Duration getDurationRemainingFromDays(long passwordTime, long currentTime, int durationDays) {
    Duration expirationDuration = Duration.standardDays(durationDays);
    Duration passwordDuration = new Duration(passwordTime, currentTime);

    return expirationDuration.minus(passwordDuration);
}

From source file:com.mirth.connect.server.util.PasswordRequirementsChecker.java

License:Open Source License

private String checkReusePeriod(List<Credentials> previousCredentials, String plainPassword, int reusePeriod) {
    // Return without checking if the reuse policies are off
    if (reusePeriod == 0) {
        return null;
    }/*w  ww  .  j a v  a  2  s .  c  o m*/

    UserController userController = ControllerFactory.getFactory().createUserController();

    // Let -1 mean the duration is infinite
    Duration reusePeriodDuration = null;
    if (reusePeriod != -1) {
        reusePeriodDuration = Duration.standardDays(reusePeriod);
    }

    for (Credentials credentials : previousCredentials) {
        boolean checkPassword = false;
        if (reusePeriodDuration == null) {
            checkPassword = true;
        } else {
            checkPassword = reusePeriodDuration.isLongerThan(
                    new Duration(credentials.getPasswordDate().getTimeInMillis(), System.currentTimeMillis()));
        }

        if (checkPassword && userController.checkPassword(plainPassword, credentials.getPassword())) {
            if (reusePeriod == -1) {
                return "You cannot reuse the same password.";
            }
            return "You cannot reuse the same password within " + reusePeriod + " days.";
        }
    }

    return null;
}

From source file:com.moosemorals.mediabrowser.ui.PVRFileTreeCellRenderer.java

License:Open Source License

@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean isExpanded,
        boolean leaf, int row, boolean hasFocus) {

    PVRItem item = (PVRItem) value;//  w  w  w . ja  va  2 s.  co  m
    if (isSelected) {
        setBackground(UIManager.getColor("Tree.selectionBackground"));
        text.setForeground(UIManager.getColor("Tree.selectionForeground"));
    } else {
        setBackground(UIManager.getColor("Tree.textBackground"));
        text.setForeground(UIManager.getColor("Tree.textForeground"));
    }

    if (!(item.isDlnaScanned() && item.isFtpScanned())) {
        float[] colorComponents = text.getForeground().getRGBComponents(null);
        text.setForeground(new Color(colorComponents[0], colorComponents[1], colorComponents[2], 0.25f));
    }

    if (item.isFile()) {
        PVRFile file = (PVRFile) item;

        if (file.isHighDef()) {
            text.setIcon(HD_ICON);
        } else {
            text.setIcon(leafIcon);
        }

        Duration length = new Duration(file.getStartTime(), file.getEndTime());

        StringBuilder title = new StringBuilder().append(file.getTitle()).append(": ")
                .append(PVR.DISPLAY_DATE_AND_TIME.print(file.getStartTime())).append(" (")
                .append(PERIOD_FORMAT.print(length.toPeriod())).append(") ")
                .append(PVR.humanReadableSize(file.getSize()));

        if (file.isLocked()) {
            setIcon(lockIcon, LOCK_ICON);
        } else {
            setIcon(lockIcon, null);
        }

        text.setText(title.toString());

    } else {
        PVRFolder folder = (PVRFolder) item;

        if (isExpanded) {
            text.setIcon(UIManager.getIcon("Tree.openIcon"));
        } else {
            text.setIcon(UIManager.getIcon("Tree.closedIcon"));
        }

        setIcon(lockIcon, null);

        StringBuilder title = new StringBuilder().append(folder.getRemoteFilename()).append(": ")
                .append(PVR.humanReadableSize(folder.getSize())).append(" (").append(folder.getChildCount())
                .append(" item").append(folder.getChildCount() == 1 ? "" : "s").append(")");

        text.setText(title.toString());
    }

    Border padding = BorderFactory.createEmptyBorder(1, 0, 1, 0);

    Border select;
    if (hasFocus) {
        select = BorderFactory.createLineBorder(Color.black);
    } else {
        select = BorderFactory.createEmptyBorder(1, 1, 1, 1);
    }

    JTree.DropLocation dropLocation = tree.getDropLocation();
    if (dropLocation != null && dropLocation.getChildIndex() == -1
            && tree.getRowForPath(dropLocation.getPath()) == row) {

        select = BorderFactory.createLineBorder(Color.blue);
    }

    setBorder(BorderFactory.createCompoundBorder(padding, select));

    Dimension preferredSize = getPreferredSize();

    preferredSize.width = tree.getWidth();

    setSize(preferredSize);

    return this;
}

From source file:com.mycollab.shell.view.MainViewImpl.java

License:Open Source License

private MHorizontalLayout buildAccountMenuLayout() {
    accountLayout.removeAllComponents();

    if (SiteConfiguration.isDemandEdition()) {
        // display trial box if user in trial mode
        SimpleBillingAccount billingAccount = AppContext.getBillingAccount();
        if (AccountStatusConstants.TRIAL.equals(billingAccount.getStatus())) {
            if ("Free".equals(billingAccount.getBillingPlan().getBillingtype())) {
                Label informLbl = new Label(
                        "<div class='informBlock'>FREE CHARGE<br>UPGRADE</div><div class='informBlock'>&gt;&gt;</div>",
                        ContentMode.HTML);
                informLbl.addStyleName("trialEndingNotification");
                informLbl.setHeight("100%");
                MHorizontalLayout informBox = new MHorizontalLayout(informLbl).withFullHeight()
                        .withStyleName("trialInformBox");
                informBox.setMargin(new MarginInfo(false, true, false, false));
                informBox.addLayoutClickListener(layoutClickEvent -> EventBusFactory.getInstance()
                        .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "billing" })));
                accountLayout.with(informBox).withAlign(informBox, Alignment.MIDDLE_LEFT);
            } else {
                Label informLbl = new Label("", ContentMode.HTML);
                informLbl.addStyleName("trialEndingNotification");
                informLbl.setHeight("100%");
                MHorizontalLayout informBox = new MHorizontalLayout(informLbl).withStyleName("trialInformBox")
                        .withMargin(new MarginInfo(false, true, false, false)).withFullHeight();
                informBox.addLayoutClickListener(layoutClickEvent -> EventBusFactory.getInstance()
                        .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "billing" })));
                accountLayout.with(informBox).withAlign(informBox, Alignment.MIDDLE_LEFT);

                Duration dur = new Duration(new DateTime(billingAccount.getCreatedtime()), new DateTime());
                int daysLeft = dur.toStandardDays().getDays();
                if (daysLeft > 30) {
                    informLbl.setValue("<div class='informBlock'>Trial ended<br></div>");
                    AppContext.getInstance().setIsValidAccount(false);
                } else {
                    informLbl.setValue(String.format("<div class='informBlock'>Trial ending<br>%d days "
                            + "left</div><div class='informBlock'>&gt;&gt;</div>", 30 - daysLeft));
                }//  ww  w  . j  ava2s.  com
            }
        }
    }

    Label accountNameLabel = new Label(AppContext.getSubDomain());
    accountNameLabel.addStyleName("subdomain");
    accountLayout.addComponent(accountNameLabel);

    if (SiteConfiguration.isCommunityEdition()) {
        MButton buyPremiumBtn = new MButton("Upgrade to Pro edition",
                clickEvent -> UI.getCurrent().addWindow(new AdWindow())).withIcon(FontAwesome.SHOPPING_CART)
                        .withStyleName("ad");
        accountLayout.addComponent(buyPremiumBtn);
    }

    LicenseResolver licenseResolver = AppContextUtil.getSpringBean(LicenseResolver.class);
    if (licenseResolver != null) {
        LicenseInfo licenseInfo = licenseResolver.getLicenseInfo();
        if (licenseInfo != null) {
            if (licenseInfo.isExpired()) {
                MButton buyPremiumBtn = new MButton(AppContext.getMessage(LicenseI18nEnum.EXPIRE_NOTIFICATION),
                        clickEvent -> UI.getCurrent().addWindow(new BuyPremiumSoftwareWindow()))
                                .withIcon(FontAwesome.SHOPPING_CART).withStyleName("ad");
                accountLayout.addComponent(buyPremiumBtn);
            } else if (licenseInfo.isTrial()) {
                Duration dur = new Duration(new DateTime(), new DateTime(licenseInfo.getExpireDate()));
                int days = dur.toStandardDays().getDays();
                MButton buyPremiumBtn = new MButton(
                        AppContext.getMessage(LicenseI18nEnum.TRIAL_NOTIFICATION, days),
                        clickEvent -> UI.getCurrent().addWindow(new BuyPremiumSoftwareWindow()))
                                .withIcon(FontAwesome.SHOPPING_CART).withStyleName("ad");
                accountLayout.addComponent(buyPremiumBtn);
            }
        }
    }

    NotificationComponent notificationComponent = new NotificationComponent();
    accountLayout.addComponent(notificationComponent);

    if (StringUtils.isBlank(AppContext.getUser().getAvatarid())) {
        EventBusFactory.getInstance()
                .post(new ShellEvent.NewNotification(this, new RequestUploadAvatarNotification()));
    }

    if (!SiteConfiguration.isDemandEdition()) {
        ExtMailService mailService = AppContextUtil.getSpringBean(ExtMailService.class);
        if (!mailService.isMailSetupValid()) {
            EventBusFactory.getInstance()
                    .post(new ShellEvent.NewNotification(this, new SmtpSetupNotification()));
        }

        SimpleUser user = AppContext.getUser();
        GregorianCalendar tenDaysAgo = new GregorianCalendar();
        tenDaysAgo.add(Calendar.DATE, -10);

        if (Boolean.TRUE.equals(user.getRequestad()) && user.getRegisteredtime().before(tenDaysAgo.getTime())) {
            UI.getCurrent().addWindow(new AdRequestWindow(user));
        }
    }

    Resource userAvatarRes = UserAvatarControlFactory.createAvatarResource(AppContext.getUserAvatarId(), 24);
    final PopupButton accountMenu = new PopupButton("");
    accountMenu.setIcon(userAvatarRes);
    accountMenu.setDescription(AppContext.getUserDisplayName());

    OptionPopupContent accountPopupContent = new OptionPopupContent();

    MButton myProfileBtn = new MButton(AppContext.getMessage(AdminI18nEnum.VIEW_PROFILE), clickEvent -> {
        accountMenu.setPopupVisible(false);
        EventBusFactory.getInstance()
                .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "preview" }));
    }).withIcon(SettingAssetsManager.getAsset(SettingUIConstants.PROFILE));
    accountPopupContent.addOption(myProfileBtn);

    MButton userMgtBtn = new MButton(AppContext.getMessage(AdminI18nEnum.VIEW_USERS_AND_ROLES), clickEvent -> {
        accountMenu.setPopupVisible(false);
        EventBusFactory.getInstance()
                .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "user", "list" }));
    }).withIcon(SettingAssetsManager.getAsset(SettingUIConstants.USERS));
    accountPopupContent.addOption(userMgtBtn);

    MButton generalSettingBtn = new MButton(AppContext.getMessage(AdminI18nEnum.VIEW_SETTING), clickEvent -> {
        accountMenu.setPopupVisible(false);
        EventBusFactory.getInstance()
                .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "setting", "general" }));
    }).withIcon(SettingAssetsManager.getAsset(SettingUIConstants.GENERAL_SETTING));
    accountPopupContent.addOption(generalSettingBtn);

    MButton themeCustomizeBtn = new MButton(AppContext.getMessage(AdminI18nEnum.VIEW_THEME), clickEvent -> {
        accountMenu.setPopupVisible(false);
        EventBusFactory.getInstance()
                .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "setting", "theme" }));
    }).withIcon(SettingAssetsManager.getAsset(SettingUIConstants.THEME_CUSTOMIZE));
    accountPopupContent.addOption(themeCustomizeBtn);

    if (!SiteConfiguration.isDemandEdition()) {
        MButton setupBtn = new MButton(AppContext.getMessage(AdminI18nEnum.VIEW_SETUP), clickEvent -> {
            accountMenu.setPopupVisible(false);
            EventBusFactory.getInstance()
                    .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "setup" }));
        }).withIcon(FontAwesome.WRENCH);
        accountPopupContent.addOption(setupBtn);
    }

    accountPopupContent.addSeparator();

    MButton helpBtn = new MButton(AppContext.getMessage(GenericI18Enum.ACTION_HELP))
            .withIcon(FontAwesome.MORTAR_BOARD);
    ExternalResource helpRes = new ExternalResource("https://community.mycollab.com/meet-mycollab/");
    BrowserWindowOpener helpOpener = new BrowserWindowOpener(helpRes);
    helpOpener.extend(helpBtn);
    accountPopupContent.addOption(helpBtn);

    MButton supportBtn = new MButton(AppContext.getMessage(GenericI18Enum.BUTTON_SUPPORT))
            .withIcon(FontAwesome.LIFE_SAVER);
    ExternalResource supportRes = new ExternalResource("http://support.mycollab.com/");
    BrowserWindowOpener supportOpener = new BrowserWindowOpener(supportRes);
    supportOpener.extend(supportBtn);
    accountPopupContent.addOption(supportBtn);

    MButton translateBtn = new MButton(AppContext.getMessage(GenericI18Enum.ACTION_TRANSLATE))
            .withIcon(FontAwesome.PENCIL);
    ExternalResource translateRes = new ExternalResource(
            "https://community.mycollab.com/docs/developing-mycollab/translating/");
    BrowserWindowOpener translateOpener = new BrowserWindowOpener(translateRes);
    translateOpener.extend(translateBtn);
    accountPopupContent.addOption(translateBtn);

    if (!SiteConfiguration.isCommunityEdition()) {
        MButton myAccountBtn = new MButton(AppContext.getMessage(AdminI18nEnum.VIEW_BILLING), clickEvent -> {
            accountMenu.setPopupVisible(false);
            EventBusFactory.getInstance()
                    .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "billing" }));
        }).withIcon(SettingAssetsManager.getAsset(SettingUIConstants.BILLING));
        accountPopupContent.addOption(myAccountBtn);
    }

    accountPopupContent.addSeparator();
    MButton aboutBtn = new MButton("About MyCollab", clickEvent -> {
        accountMenu.setPopupVisible(false);
        Window aboutWindow = ViewManager.getCacheComponent(AbstractAboutWindow.class);
        UI.getCurrent().addWindow(aboutWindow);
    }).withIcon(FontAwesome.INFO_CIRCLE);
    accountPopupContent.addOption(aboutBtn);

    Button releaseNotesBtn = new Button("Release Notes");
    ExternalResource releaseNotesRes = new ExternalResource(
            "https://community.mycollab.com/docs/hosting-mycollab-on-your-own-server/releases/");
    BrowserWindowOpener releaseNotesOpener = new BrowserWindowOpener(releaseNotesRes);
    releaseNotesOpener.extend(releaseNotesBtn);

    releaseNotesBtn.setIcon(FontAwesome.BULLHORN);
    accountPopupContent.addOption(releaseNotesBtn);

    MButton signoutBtn = new MButton(AppContext.getMessage(GenericI18Enum.BUTTON_SIGNOUT), clickEvent -> {
        accountMenu.setPopupVisible(false);
        EventBusFactory.getInstance().post(new ShellEvent.LogOut(this, null));
    }).withIcon(FontAwesome.SIGN_OUT);
    accountPopupContent.addSeparator();
    accountPopupContent.addOption(signoutBtn);

    accountMenu.setContent(accountPopupContent);
    accountLayout.addComponent(accountMenu);
    return accountLayout;
}

From source file:com.mycompany.alarmdatasimulator.Main.java

public static void main(String[] args) {
    Map<Alarm, Map<Alarm, CausalRelation>> relations = getCenarioTeste2(); // Relations map
    SimulationExecutor exec = new SimulationExecutor(relations);

    DateTime init = new DateTime(2010, 5, 1, 1, 0, 0); // Initial time simulation
    Duration duration = new Duration(init, init.plusMonths(5)); // Duration of simulation, in months
    String result = exec.simulate(init, duration);
    System.out.println(result); // Print result as CSV pattern

}

From source file:com.myMinistry.util.TimeUtils.java

License:Open Source License

public static String getTimeLength(Calendar start, Calendar end, String h, String m) {
    Duration dur = new Duration(new DateTime(start), new DateTime(end));
    Period period = dur.toPeriod();

    PeriodFormatter retVal = new PeriodFormatterBuilder().printZeroNever().appendHours().appendSuffix(h)
            .appendSeparator(" ").appendMinutes().appendSuffix(m).toFormatter();

    return retVal.print(period);
}

From source file:com.myMinistry.util.TimeUtils.java

License:Open Source License

public static String getTimeLength(Cursor cursor, String h, String m, boolean showMinutes) {
    SimpleDateFormat saveDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
    Calendar start = Calendar.getInstance(Locale.getDefault());
    Calendar end = Calendar.getInstance(Locale.getDefault());

    Duration dur = new Duration(null, null);
    Duration durchange = new Duration(null, null);

    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        try {/*w  ww. j  av  a  2 s.  co m*/
            start.setTime(
                    saveDateFormat.parse(cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.DATE_START))));
        } catch (Exception e) {
            start = Calendar.getInstance(Locale.getDefault());
        }
        try {
            end.setTime(
                    saveDateFormat.parse(cursor.getString(cursor.getColumnIndex(UnionsNameAsRef.DATE_END))));
        } catch (Exception e) {
            end = Calendar.getInstance(Locale.getDefault());
        }

        durchange = new Duration(new DateTime(start), new DateTime(end));
        dur = dur.withDurationAdded(durchange, 1);
    }

    cursor.close();

    PeriodFormatter retVal;

    if (showMinutes) {
        retVal = new PeriodFormatterBuilder().printZeroRarelyFirst().appendHours().appendSuffix(h)
                .appendSeparator(" ").appendMinutes().appendSuffix(m).toFormatter();
    } else {
        retVal = new PeriodFormatterBuilder().printZeroAlways().appendHours().appendSuffix(h).toFormatter();
    }

    return retVal.print(dur.toPeriod());
}

From source file:com.mythesis.userbehaviouranalysis.RequestServlet.java

License:Apache License

/**
 * Handles the HTTP <code>POST</code> method.
 * @param request servlet request/*from ww w. jav  a2 s  .c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String userPath = request.getServletPath();
    File input = new File("D://UserBehaviourAnalysisInput.txt");
    ProfileAnalysis analysis = new ProfileAnalysis();
    switch (userPath) {
    // if history is sent
    case "/history":
        String id = request.getParameter("userID");
        String[] urls = request.getParameter("urls").split(",");

        Mongo mongo = new Mongo("localhost", 27017);
        DB db = mongo.getDB("profileAnalysis");
        DBCollection userinfo = db.getCollection("userinfo");
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("userID", id);
        DBCursor cursor = userinfo.find(searchQuery);
        if (cursor.hasNext()) {
            DateTime current = new DateTime();
            SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm");
            DBObject entry = cursor.next();
            String check = (String) entry.get("timestamp");
            Date temp = null;
            try {
                temp = format.parse(check);
            } catch (ParseException ex) {
                Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
            DateTime previous = new DateTime(temp);
            System.out.println("last history analysis on: " + previous);
            System.out.println("current date/time: " + current);
            Duration duration = new Duration(previous, current);
            if (duration.getStandardHours() < 24)
                break;
        }
        analysis.perform(id, urls, input);
        break;
    // if query is sent    
    case "/query":
        try {
            JSONObject data = new JSONObject(request.getParameter("data"));
            Iterator it = data.keys();

            ArrayList<String> profiles = new ArrayList<>();
            ArrayList<String> queries = new ArrayList<>();
            while (it.hasNext()) {
                String key = (String) it.next();
                profiles.add(key);
                queries.add((String) data.get(key));
            }
            analysis.storeQueries(profiles, queries, input);
        } catch (JSONException ex) {
            Logger.getLogger(RequestServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        break;
    }
}

From source file:com.nubits.nubot.utils.Utils.java

License:Open Source License

public static String getDurationDate(DateTime from, DateTime to) {
    Duration duration = new Duration(from, to);
    Period period = duration.toPeriod();
    Period normalizedPeriod = period.normalizedStandard();
    PeriodFormatter minutesAndSeconds = new PeriodFormatterBuilder().appendDays().appendSuffix(" day", " days")
            .appendSeparator(" ").printZeroIfSupported()
            //.minimumPrintedDigits(2)
            .appendHours().appendSuffix(" hour", " hours").appendSeparator(" ").appendMinutes()
            .appendSuffix(" minute", " minutes").printZeroIfSupported()
            //.minimumPrintedDigits(2)
            .appendSeparator(" ").appendSeconds().appendSuffix(" second", " seconds")
            //.minimumPrintedDigits(2)
            .toFormatter();//from   w ww. j ava 2 s  .  co  m

    /*
    .printZeroAlways()
    .appendMinutes()
    .appendSeparator(":")
    .appendSeconds()
    .toFormatter();*/
    String result = minutesAndSeconds.print(normalizedPeriod);
    return result;
}