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.boundary.metrics.vmware.poller.VMwarePerfPoller.java

License:Apache License

/**
 * Extracts performance metrics from Managed Objects on the monitored entity
 * //from   www .j av  a2  s  . c o  m
 * @throws MalformedURLException Bad URL
 * @throws RemoteException Endpoint exception
 * @throws InvalidPropertyFaultMsg Bad Property
 * @throws RuntimeFaultFaultMsg Runtime error
 * @throws SOAPFaultException WebServer error
 */
public void collectPerformanceData() throws MalformedURLException, RemoteException, InvalidPropertyFaultMsg,
        RuntimeFaultFaultMsg, SOAPFaultException {

    ManagedObjectReference root = client.getServiceContent().getRootFolder();

    // 'now' according to the server
    DateTime now = TimeUtils.toDateTime(client.getVimPort().currentTime(client.getServiceInstanceReference()));
    Duration serverSkew = new Duration(now, new DateTime());
    if (serverSkew.isLongerThan(Duration.standardSeconds(1))
            && (skew == null || skew.getStandardSeconds() != serverSkew.getStandardSeconds())) {
        LOG.warn("Server {} and local time skewed by {} seconds", client.getHost(),
                serverSkew.getStandardSeconds());
        skew = serverSkew;
    }
    if (lastPoll == null) {
        lastPoll = now.minusSeconds(20);
    }

    // Holder for all our newly found measurements
    // TODO set an upper size limit on measurements list
    List<Measurement> measurements = Lists.newArrayList();

    /*
    * A {@link PerfMetricId} consistents of the performance counter and
    * the instance it applies to.
    * 
    * In our particular case we are requesting for all of the instances
    * associated with the performance counter.
    * 
    * Will this work when we have a mix of VirtualMachine, HostSystem, and DataSource
    * managed objects.
    * 
    */
    List<PerfMetricId> perfMetricIds = Lists.newArrayList();
    for (String counterName : metrics.keySet()) {
        if (this.performanceCounterMap.containsKey(counterName)) {
            PerfMetricId metricId = new PerfMetricId();
            /* Get the ID for this counter. */
            metricId.setCounterId(this.performanceCounterMap.get(counterName));
            metricId.setInstance("*");
            perfMetricIds.add(metricId);
        }
    }

    GetMOREF getMOREFs = new GetMOREF(client);
    Map<String, ManagedObjectReference> entities = getMOREFs.inFolderByType(root, "VirtualMachine");

    for (Map.Entry<String, ManagedObjectReference> entity : entities.entrySet()) {
        ManagedObjectReference mor = entity.getValue();
        String entityName = entity.getKey();

        /*
        * Create the query specification for queryPerf().
        * Specify 5 minute rollup interval and CSV output format.
        */
        PerfQuerySpec querySpec = new PerfQuerySpec();
        querySpec.setEntity(mor);
        querySpec.setIntervalId(20);
        querySpec.setFormat("normal");
        querySpec.setStartTime(TimeUtils.toXMLGregorianCalendar(lastPoll));
        querySpec.setEndTime(TimeUtils.toXMLGregorianCalendar(now));
        querySpec.getMetricId().addAll(perfMetricIds);

        LOG.info("Entity: {}, MOR: {}-{}, Interval: {}, Format: {}, MetricIds: {}, Start: {}, End: {}",
                entityName, mor.getType(), mor.getValue(), querySpec.getIntervalId(), querySpec.getFormat(),
                FluentIterable.from(perfMetricIds).transform(toStringFunction), lastPoll, now);

        List<PerfEntityMetricBase> retrievedStats = client.getVimPort()
                .queryPerf(client.getServiceContent().getPerfManager(), ImmutableList.of(querySpec));

        /*
        * Cycle through the PerfEntityMetricBase objects. Each object contains
        * a set of statistics for a single ManagedEntity.
        */
        for (PerfEntityMetricBase singleEntityPerfStats : retrievedStats) {
            if (singleEntityPerfStats instanceof PerfEntityMetric) {
                PerfEntityMetric entityStats = (PerfEntityMetric) singleEntityPerfStats;
                List<PerfMetricSeries> metricValues = entityStats.getValue();
                List<PerfSampleInfo> sampleInfos = entityStats.getSampleInfo();

                for (int x = 0; x < metricValues.size(); x++) {
                    PerfMetricIntSeries metricReading = (PerfMetricIntSeries) metricValues.get(x);
                    PerfCounterInfo metricInfo = performanceCounterInfoMap
                            .get(metricReading.getId().getCounterId());
                    String metricFullName = toFullName.apply(metricInfo);
                    if (!sampleInfos.isEmpty()) {
                        PerfSampleInfo sampleInfo = sampleInfos.get(0);
                        DateTime sampleTime = TimeUtils.toDateTime(sampleInfo.getTimestamp());
                        Number sampleValue = metricReading.getValue().iterator().next();

                        if (skew != null) {
                            sampleTime = sampleTime.plusSeconds((int) skew.getStandardSeconds());
                        }

                        if (metricReading.getValue().size() > 1) {
                            LOG.warn("Metric {} has more than one value, only using the first", metricFullName);
                        }

                        String source = client.getName() + "-" + entityName;

                        if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("kiloBytes")) {
                            sampleValue = (long) sampleValue * 1024; // Convert KB to Bytes
                        } else if (metricInfo.getUnitInfo().getKey().equalsIgnoreCase("percent")) {
                            // Convert hundredth of a percent to a decimal percent
                            sampleValue = new Long((long) sampleValue).doubleValue() / 10000.0;
                        }
                        String name = metrics.get(metricFullName).getName();
                        if (name != null) {
                            Measurement measurement = Measurement.builder().setMetric(name).setSource(source)
                                    .setTimestamp(sampleTime).setMeasurement(sampleValue).build();
                            measurements.add(measurement);

                            LOG.info("{} @ {} = {} {}", metricFullName, sampleTime, sampleValue,
                                    metricInfo.getUnitInfo().getKey());
                        } else {
                            LOG.warn("Skipping collection of metric: {}", metricFullName);
                        }
                    } else {
                        LOG.warn("Didn't receive any samples when polling for {} on {} between {} and {}",
                                metricFullName, client.getHost(), lastPoll, now);
                    }
                }
            } else {
                LOG.error("Unrecognized performance entry type received: {}, ignoring",
                        singleEntityPerfStats.getClass().getName());
            }
        }
    }

    // Send metrics
    if (!measurements.isEmpty()) {
        metricsClient.addMeasurements(measurements);
    } else {
        LOG.warn("No measurements collected in last poll for {}", client.getHost());
    }

    // Reset lastPoll time
    lastPoll = now;
}

From source file:com.bytestemplar.subgeniuswatchface.BT_SubgeniusWatchface.java

License:Apache License

private String getXDayCountdown() {
    DateTime today = DateTime.now();//from w w w .  jav  a  2 s .com
    //DateTime today = new DateTime( 1998, 7, 6, 4, 20, 32, 0 );
    DateTime xday = new DateTime(today.getYear(), 7, 5, 7, 0, 0, 0);

    if (today.isAfter(xday)) {
        xday = new DateTime(today.getYear() + 1, 7, 5, 7, 0, 0, 0);
    }

    Duration dur = new Duration(today, xday);

    StringBuilder sb = new StringBuilder();

    if (dur.getStandardDays() > 0) {
        sb.append(dur.getStandardDays());
        sb.append(" Day");
        if (dur.getStandardDays() > 1) {
            sb.append("s");
        }
        sb.append("\n");
    }

    long hours = dur.getStandardHours() % 24;
    if (hours > 0) {
        sb.append(hours);
        sb.append(" Hour");
        if (hours > 1) {
            sb.append("s");
        }
        sb.append("\n");
    }

    long mins = dur.getStandardMinutes() % 60;
    if (mins > 0) {
        sb.append(mins);
        sb.append(" Minute");
        if (mins > 1) {
            sb.append("s");
        }
        sb.append("\n");
    }

    long secs = dur.getStandardSeconds() % 60;
    if (secs > 0) {
        sb.append(secs);
        sb.append(" Second");
        if (secs > 1) {
            sb.append("s");
        }
        sb.append("\n");
    }

    sb.append("Until X-Day!");

    return sb.toString();
}

From source file:com.cimpress.puzzle.Main.java

License:Apache License

public static void main(final String... args) {

    logger.debug("tt");

    ApplicationContext cntx = new ClassPathXmlApplicationContext("classpath:spring-integration-context.xml");

    AsyncLogger asyncLogger = cntx.getBean("asyncLogger", AsyncLogger.class);

    asyncLogger.log("Container loaded", String.class, Main.class, logger);
    PuzzleAPI puzzleAPI = cntx.getBean("puzzleAPI", PuzzleAPI.class);

    DateTime dt = new DateTime();
    Puzzle puzzle = puzzleAPI.generatePuzzle();

    // new SquareFinder().solvePuzzle(Environment.getPuzzleObject());
    List<Square> squareList = new SquareFinder().solvePuzzle(puzzle);
    System.out.println("Total squares :" + squareList.size());
    puzzleAPI.postSolution(squareList, puzzle.getId());
    DateTime d2 = new DateTime();
    Duration elapsedTime = new Duration(dt, d2);
    System.out.println("\nTotal Time Taken :" + elapsedTime.getStandardSeconds());
}

From source file:com.dataartisans.timeoutmonitoring.session.LatencyWindowFunction.java

License:Apache License

@Override
public JSONObject apply(JSONObject left, JSONObject right) {

    JSONObject result = JSONObjectExtractor.createJSONObject(left, resultFields);

    String firstTimestamp = left.getString("timestamp");
    String lastTimestamp = right.getString("timestamp");

    DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
    DateTime firstDateTime = formatter.parseDateTime(firstTimestamp);
    DateTime lastDateTime = formatter.parseDateTime(lastTimestamp);

    Duration diff = new Duration(firstDateTime, lastDateTime);

    result.put("latency", diff.getMillis() + "");

    return result;
}

From source file:com.ehdev.chronos.lib.types.holders.PunchPair.java

License:Open Source License

/**
 * Returns an interval based on the two Punches held in the class.
 *
 * @return Interval with the two punches. If one of the punches
 *  doesn't exists the return value will be a new Interval with the value of 0
 *///from  w ww.  j ava2  s . c om
public long getDuration() {
    if (getInPunch() == null || getOutPunch() == null) {
        return -1 * getInPunch().getTime().getMillis();
    } else {
        return new Duration(getInPunch().getTime(), getOutPunch().getTime()).getMillis();
    }
}

From source file:com.ephemeraldreams.gallyshuttle.ui.MainFragment.java

License:Apache License

/**
 * Calculate time difference in milliseconds between now and next available shuttle arrival time.
 *
 * @param stationId Station id to get times from.
 * @return Duration between now and next arrival time in milliseconds.
 *//*from w  w  w  .j ava  2  s.  c o m*/
private long calculateTimeFromNowToNextArrivalAtStation(int stationId) {
    List<String> times = schedule.getTimes(stationId);
    LocalDateTime now = LocalDateTime.now();
    arrivalTime = null;
    LocalDateTime stationTime;
    for (String time : times) {
        stationTime = DateUtils.parseToLocalDateTime(time);
        Timber.d(stationTime.toString());

        //Workaround midnight exception case where station time was converted to midnight of current day instead of next day.
        if (stationTime.getHourOfDay() == 0 && now.getHourOfDay() != 0) {
            stationTime = stationTime.plusDays(1);
        }
        if (now.isBefore(stationTime)) {
            arrivalTime = stationTime;
            break;
        }
    }
    if (arrivalTime == null) {
        arrivalTimeTextView.setText(getString(R.string.arrival_not_available_message));
        return -1;
    } else {
        arrivalTimeTextView.setText(String.format(getString(R.string.until_arrival_time_message),
                DateUtils.formatTime(arrivalTime)));

        Duration duration = new Duration(now.toDateTime(), arrivalTime.toDateTime());
        long milliseconds = duration.getMillis();

        Timber.d("Now: " + DateUtils.formatTime(now));
        Timber.d("Arrival: " + DateUtils.formatTime(arrivalTime));
        Timber.d("Time difference between now and arrival: "
                + DateUtils.convertMillisecondsToTime(milliseconds));

        return milliseconds;
    }
}

From source file:com.ephemeraldreams.gallyshuttle.ui.MainFragment.java

License:Apache License

/**
 * Set a timer for arrival notification.
 *
 * @param notificationsBoxChecked Notification check box's checked status.
 *///from  ww w .  j av a2  s.  c om
private void setArrivalNotificationTimer(boolean notificationsBoxChecked) {
    if (notificationsBoxChecked) {
        if (arrivalTime != null) {
            Intent notificationIntent = new Intent(getActivity(), ArrivalNotificationReceiver.class);
            notificationIntent.putExtra(ArrivalNotificationReceiver.EXTRA_STATION_NAME,
                    stationStopsAdapter.getItem(stationIndex));
            notificationPendingIntent = PendingIntent.getBroadcast(getActivity(), 0, notificationIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Duration duration = new Duration(LocalDateTime.now().toDateTime(), arrivalTime.toDateTime());
            long millis = duration.getMillis();
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis,
                    notificationPendingIntent);
            Timber.d("Arrival Notification receiver set: " + DateUtils.convertMillisecondsToTime(millis));
        } else {
            Timber.d("Arrival Notification receiver not set. Arrival time is null.");
        }
    } else {
        alarmManager.cancel(notificationPendingIntent);
        Timber.d("Arrival Notification receiver cancelled.");
    }
}

From source file:com.esofthead.mycollab.common.service.ibatis.TimelineTrackingServiceImpl.java

License:Open Source License

private List<Date> boundDays(DateTime start, DateTime end) {
    Duration duration = new Duration(start, end);
    long days = duration.getStandardDays();
    List<Date> dates = new ArrayList<>();
    //Will try to get from cache values from the end date to (startdate - 1)
    for (int i = 0; i <= days; i++) {
        dates.add(start.plusDays(i).toDate());
    }//from   w  w w.  ja  v  a  2 s.c  om
    return dates;
}

From source file:com.esofthead.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%");
                HorizontalLayout informBox = new HorizontalLayout();
                informBox.addStyleName("trialInformBox");
                informBox.setSizeFull();
                informBox.addComponent(informLbl);
                informBox.setMargin(new MarginInfo(false, true, false, false));
                informBox.addLayoutClickListener(new LayoutEvents.LayoutClickListener() {
                    private static final long serialVersionUID = 1L;

                    @Override//  ww  w . j a  va2  s  .  c o  m
                    public void layoutClick(LayoutClickEvent event) {
                        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%");
                HorizontalLayout informBox = new HorizontalLayout();
                informBox.addStyleName("trialInformBox");
                informBox.setSizeFull();
                informBox.setMargin(new MarginInfo(false, true, false, false));
                informBox.addComponent(informLbl);
                informBox.addLayoutClickListener(new LayoutEvents.LayoutClickListener() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void layoutClick(LayoutClickEvent event) {
                        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<br></div><div class='informBlock'>&gt;&gt;</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));
                }
            }
        }
    }

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

    if (SiteConfiguration.isCommunityEdition()) {
        Button buyPremiumBtn = new Button("Upgrade to Pro edition", new ClickListener() {
            @Override
            public void buttonClick(ClickEvent event) {
                UI.getCurrent().addWindow(new AdWindow());
            }
        });
        buyPremiumBtn.setIcon(FontAwesome.SHOPPING_CART);
        buyPremiumBtn.addStyleName("ad");
        accountLayout.addComponent(buyPremiumBtn);
    }

    LicenseResolver licenseResolver = AppContextUtil.getSpringBean(LicenseResolver.class);
    if (licenseResolver != null) {
        LicenseInfo licenseInfo = licenseResolver.getLicenseInfo();
        if (licenseInfo != null) {
            if (licenseInfo.isExpired()) {
                Button buyPremiumBtn = new Button(AppContext.getMessage(LicenseI18nEnum.EXPIRE_NOTIFICATION),
                        new ClickListener() {
                            @Override
                            public void buttonClick(ClickEvent event) {
                                UI.getCurrent().addWindow(new BuyPremiumSoftwareWindow());
                            }
                        });
                buyPremiumBtn.setIcon(FontAwesome.SHOPPING_CART);
                buyPremiumBtn.addStyleName("ad");
                accountLayout.addComponent(buyPremiumBtn);
            } else if (licenseInfo.isTrial()) {
                Duration dur = new Duration(new DateTime(), new DateTime(licenseInfo.getExpireDate()));
                int days = dur.toStandardDays().getDays();
                Button buyPremiumBtn = new Button(
                        AppContext.getMessage(LicenseI18nEnum.TRIAL_NOTIFICATION, days), new ClickListener() {
                            @Override
                            public void buttonClick(ClickEvent event) {
                                UI.getCurrent().addWindow(new BuyPremiumSoftwareWindow());
                            }
                        });
                buyPremiumBtn.setIcon(FontAwesome.SHOPPING_CART);
                buyPremiumBtn.addStyleName("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();

    Button myProfileBtn = new Button(AppContext.getMessage(AdminI18nEnum.VIEW_PROFILE),
            new Button.ClickListener() {
                private static final long serialVersionUID = 1L;

                @Override
                public void buttonClick(ClickEvent event) {
                    accountMenu.setPopupVisible(false);
                    EventBusFactory.getInstance()
                            .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "preview" }));
                }
            });
    myProfileBtn.setIcon(SettingAssetsManager.getAsset(SettingUIConstants.PROFILE));
    accountPopupContent.addOption(myProfileBtn);

    Button userMgtBtn = new Button(AppContext.getMessage(AdminI18nEnum.VIEW_USERS_AND_ROLES),
            new Button.ClickListener() {
                private static final long serialVersionUID = 1L;

                @Override
                public void buttonClick(final ClickEvent event) {
                    accountMenu.setPopupVisible(false);
                    EventBusFactory.getInstance()
                            .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "user", "list" }));
                }
            });
    userMgtBtn.setIcon(SettingAssetsManager.getAsset(SettingUIConstants.USERS));
    accountPopupContent.addOption(userMgtBtn);

    Button generalSettingBtn = new Button(AppContext.getMessage(AdminI18nEnum.VIEW_SETTING),
            new ClickListener() {
                @Override
                public void buttonClick(ClickEvent clickEvent) {
                    accountMenu.setPopupVisible(false);
                    EventBusFactory.getInstance().post(
                            new ShellEvent.GotoUserAccountModule(this, new String[] { "setting", "general" }));
                }
            });
    generalSettingBtn.setIcon(SettingAssetsManager.getAsset(SettingUIConstants.GENERAL_SETTING));
    accountPopupContent.addOption(generalSettingBtn);

    Button themeCustomizeBtn = new Button(AppContext.getMessage(AdminI18nEnum.VIEW_THEME), new ClickListener() {
        @Override
        public void buttonClick(ClickEvent clickEvent) {
            accountMenu.setPopupVisible(false);
            EventBusFactory.getInstance()
                    .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "setting", "theme" }));
        }
    });
    themeCustomizeBtn.setIcon(SettingAssetsManager.getAsset(SettingUIConstants.THEME_CUSTOMIZE));
    accountPopupContent.addOption(themeCustomizeBtn);

    if (!SiteConfiguration.isDemandEdition()) {
        Button setupBtn = new Button(AppContext.getMessage(AdminI18nEnum.VIEW_SETUP), new ClickListener() {
            @Override
            public void buttonClick(ClickEvent clickEvent) {
                accountMenu.setPopupVisible(false);
                EventBusFactory.getInstance()
                        .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "setup" }));
            }
        });
        setupBtn.setIcon(FontAwesome.WRENCH);
        accountPopupContent.addOption(setupBtn);
    }

    accountPopupContent.addSeparator();

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

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

    Button translateBtn = new Button(AppContext.getMessage(GenericI18Enum.ACTION_TRANSLATE));
    translateBtn.setIcon(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()) {
        Button myAccountBtn = new Button(AppContext.getMessage(AdminI18nEnum.VIEW_BILLING),
                new Button.ClickListener() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public void buttonClick(final ClickEvent event) {
                        accountMenu.setPopupVisible(false);
                        EventBusFactory.getInstance()
                                .post(new ShellEvent.GotoUserAccountModule(this, new String[] { "billing" }));
                    }
                });
        myAccountBtn.setIcon(SettingAssetsManager.getAsset(SettingUIConstants.BILLING));
        accountPopupContent.addOption(myAccountBtn);
    }

    accountPopupContent.addSeparator();
    Button aboutBtn = new Button("About MyCollab", new ClickListener() {
        @Override
        public void buttonClick(ClickEvent clickEvent) {
            accountMenu.setPopupVisible(false);
            Window aboutWindow = ViewManager.getCacheComponent(AbstractAboutWindow.class);
            UI.getCurrent().addWindow(aboutWindow);
        }
    });
    aboutBtn.setIcon(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);

    Button signoutBtn = new Button(AppContext.getMessage(GenericI18Enum.BUTTON_SIGNOUT),
            new Button.ClickListener() {
                private static final long serialVersionUID = 1L;

                @Override
                public void buttonClick(ClickEvent event) {
                    accountMenu.setPopupVisible(false);
                    EventBusFactory.getInstance().post(new ShellEvent.LogOut(this, null));
                }
            });
    signoutBtn.setIcon(FontAwesome.SIGN_OUT);
    accountPopupContent.addSeparator();
    accountPopupContent.addOption(signoutBtn);

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

From source file:com.facebook.stats.AbstractCompositeCounter.java

License:Apache License

@Override
public Duration getLength() {
    trimIfNeeded();

    return new Duration(start, end);
}