Example usage for java.util GregorianCalendar getTime

List of usage examples for java.util GregorianCalendar getTime

Introduction

In this page you can find the example usage for java.util GregorianCalendar getTime.

Prototype

public final Date getTime() 

Source Link

Document

Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch").

Usage

From source file:org.alfresco.mobile.android.application.fragments.search.AdvancedSearchFragment.java

@Override
public void onDatePicked(String dateId, GregorianCalendar gregorianCalendar) {
    if (DATE_FROM.equalsIgnoreCase(dateId)) {
        modificationDateFromValue = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        modificationDateFromValue.setTime(gregorianCalendar.getTime());
        modificationDateFrom/*from w  w w  . j a  v  a  2 s .c o  m*/
                .setText(DateFormat.getDateFormat(getActivity()).format(modificationDateFromValue.getTime()));
    } else if (DATE_TO.equalsIgnoreCase(dateId)) {
        modificationDateToValue = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        modificationDateToValue.setTime(gregorianCalendar.getTime());
        modificationDateTo
                .setText(DateFormat.getDateFormat(getActivity()).format(modificationDateToValue.getTime()));
    }
}

From source file:com.vangent.hieos.logbrowser.servlets.GetTableServlet.java

/**
 * <b>sqlCommandProcessing</b><br/>
 * Create the sql command beginning with the sql command specified in the web.xml file and applying all the options <br/>
 * specified by the user. This command also apply a limit in the results to avoid to overload the server
 *
 */// w w  w.  j a va 2  s.c o m
private void sqlCommandProcessing(HttpSession session, int optionNumberInt, String page,
        String numberResultsByPage) {
    String limitOffset = null;
    int parameterNumber = 1;
    String currentSqlCommand = null;
    reInitSqlCommand(session);
    String lastPartCommand = new String();
    currentSqlCommand = (String) session.getAttribute("currentSqlCommand");
    if (map != null && optionNumberInt > 0) {
        String commandTemp = new String();
        if (currentSqlCommand.toLowerCase().indexOf("where") > -1) {
            if (currentSqlCommand.toLowerCase().indexOf("order") > -1) {
                commandTemp = currentSqlCommand.substring(0, currentSqlCommand.toLowerCase().indexOf("order"));
                lastPartCommand = currentSqlCommand.substring(currentSqlCommand.toLowerCase().indexOf("order"));
                lastPartCommand = lastPartCommand.replace(';', ' ');
            } else if (currentSqlCommand.indexOf(";") > -1) {
                commandTemp = currentSqlCommand.substring(0, currentSqlCommand.indexOf(";"));
            }
            commandTemp += " AND ";
        } else {
            commandTemp += " WHERE ";
        }
        while (parameterNumber <= optionNumberInt) {
            if (map.containsKey("option" + parameterNumber)) {
                if (map.containsKey("and-or" + parameterNumber)) {
                    commandTemp += " " + map.get("and-or" + parameterNumber) + " ";
                }

                String parameterName = map.get("option" + parameterNumber).toString();

                if (parameterName.equals("ip")) {
                    commandTemp += " main.ip LIKE '%" + map.get("value" + parameterNumber).toString() + "%' ";

                } else if (parameterName.equals("pass")) {
                    commandTemp += " main.pass = " + map.get("value" + parameterNumber).toString() + " ";

                } else if (parameterName.equals("test")) {
                    String value = map.get("value" + parameterNumber).toString();
                    commandTemp += "  main.test LIKE '%" + value + "%' ";
                } else if (parameterName.equals("company")) {
                    String value = map.get("value" + parameterNumber).toString();
                    commandTemp += "  ip.company_name LIKE '%" + value + "%' ";
                } else if (parameterName.equals("date1")) {
                    String date1 = map.get("value" + parameterNumber).toString().trim();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    java.util.Date d1;
                    try {
                        d1 = sdf.parse(date1);
                        if (map.containsKey("option" + (parameterNumber + 1))
                                && map.get("option" + (parameterNumber + 1)).toString().equals("date2")) {
                            if (map.containsKey("value" + (parameterNumber + 1))) {
                                String date2 = map.get("value" + (parameterNumber + 1)).toString().trim();
                                java.util.Date d2 = sdf.parse(date2);
                                if (d2.getTime() > d1.getTime()) {
                                    commandTemp += " timereceived > '" + date1 + "%' and  timereceived < '"
                                            + date2 + "%' ";
                                } else if (d2.getTime() < d1.getTime()) {
                                    commandTemp += " timereceived < '" + date1 + "%' and  timereceived > '"
                                            + date2 + "%' ";
                                } else {
                                    commandTemp += " timereceived like '" + date1 + "%' ";
                                }

                                map.remove("value" + (parameterNumber + 1));
                                map.remove("option" + (parameterNumber + 1));
                                if (map.containsKey("and-or" + (parameterNumber + 1))) {
                                    map.remove("and-or" + (parameterNumber + 1));
                                }
                            }
                        } else {
                            commandTemp += " timereceived like '" + date1 + "%' ";
                        }

                    } catch (ParseException e) {
                    }
                } else if (parameterName.equals("date2")) {
                    String date1 = map.get("value" + parameterNumber).toString();

                    commandTemp += " timereceived like '" + date1 + "%' ";

                } else if (parameterName.equals("date")) {
                    String value = map.get("value" + parameterNumber).toString();
                    GregorianCalendar today = new GregorianCalendar();
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    if (value.equals("today")) {
                        commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' ";
                    } else if (value.equals("yesterday")) {
                        today.roll(Calendar.DAY_OF_MONTH, -1);
                        commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' ";
                    } else if (value.equals("2days")) {
                        today.roll(Calendar.DAY_OF_MONTH, -2);
                        commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' ";
                    } else if (value.equals("3days")) {
                        today.roll(Calendar.DAY_OF_MONTH, -3);
                        commandTemp += " timereceived like '" + dateFormat.format(today.getTime()) + "%' ";
                    }
                }
            }
            parameterNumber++;
        }
        currentSqlCommand = commandTemp;
    }

    if (page != null) {
        int pageNumber = new Integer(page).intValue();
        if (numberResultsByPage != null) {

            int nbResByPage = new Integer(numberResultsByPage).intValue();

            limitOffset = " LIMIT " + nbResByPage + " OFFSET " + (nbResByPage * pageNumber) + " ;";
        } else {
            limitOffset = " LIMIT " + MAX_RESULTS_BY_PAGE + " OFFSET " + (MAX_RESULTS_BY_PAGE * pageNumber)
                    + " ;";
        }

    } else {
        if (numberResultsByPage != null) {
            int nbResByPage = new Integer(numberResultsByPage).intValue();
            limitOffset = " LIMIT " + nbResByPage + " ;";
        } else {
            limitOffset = " LIMIT " + MAX_RESULTS_BY_PAGE + " ;";
        }
    }
    logger.debug("GetTableServlet: sqlRequest before treatment: >" + currentSqlCommand + "<\n");
    System.out.println("LogBrowser SQL (before treatment): " + currentSqlCommand);
    currentSqlCommand = currentSqlCommand.replace(';', ' ');
    if (currentSqlCommand.toLowerCase().indexOf(" limit") > -1) {
        currentSqlCommand = currentSqlCommand.substring(0, currentSqlCommand.toLowerCase().indexOf(" limit"));
    }
    currentSqlCommand += lastPartCommand + " " + limitOffset;
    session.setAttribute("currentSqlCommand", currentSqlCommand);
    logger.debug(currentSqlCommand);
    System.out.println("-- page: " + page);
    System.out.println("LogBrowser SQL (after treatment): " + currentSqlCommand);
}

From source file:es.tid.fiware.rss.expenditureLimit.processing.test.ProcessingLimitServiceTest.java

/**
 * Update periods and check amounts./*ww w  . j  a va2  s .c  o m*/
 */
@Test
@Transactional(propagation = Propagation.SUPPORTS)
public void checkControls() {
    DbeTransaction tx = ProcessingLimitServiceTest.generateTransaction();
    tx.setTxEndUserId("userIdUpdate");
    try {
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        Assert.assertNotNull(controlsBefore);
        // Reset dates to current date--> if not test fail
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DAY_OF_MONTH, 1);
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        for (DbeExpendControl control : controlsBefore) {
            control.setDtNextPeriodStart(cal.getTime());
            controlService.createOrUpdate(control);
        }
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        ProcessingLimitServiceTest.logger.debug("Controls:" + controlsAfter.size());
        for (DbeExpendControl controlInit : controlsBefore) {
            for (DbeExpendControl controlEnd : controlsAfter) {
                if (controlInit.getId().getTxElType().equalsIgnoreCase(controlEnd.getId().getTxElType())) {
                    // All the values without modification
                    Assert.assertTrue(
                            controlInit.getFtExpensedAmount().compareTo(controlEnd.getFtExpensedAmount()) == 0);
                    break;
                }
            }
        }
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Error: " + e.getMessage());
        Assert.fail("Exception not expected");
    }
    // check error
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(1000));
        limitService.proccesLimit(tx);
        Assert.fail("Exception expected");
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        // "SVC3705",
        Assert.assertTrue(e.getMessage().contains("Insufficient payment method balance"));
    }
    // check that
    try {
        tx.setFtChargedTotalAmount(null);
        tx.setFtInternalTotalAmount(new BigDecimal(30));
        List<DbeExpendControl> controlsBefore = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        // Reset period
        DbeExpendControl control = controlsBefore.get(0);
        GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MONTH, -1);
        control.setDtNextPeriodStart(cal.getTime());
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
        TransactionStatus status = transactionManager.getTransaction(def);
        controlService.update(control);
        transactionManager.commit(status);
        limitService.proccesLimit(tx);
        List<DbeExpendControl> controlsAfter = controlService.getExpendDataForUserAppProvCurrencyObCountry(
                tx.getTxEndUserId(), tx.getBmService(), tx.getTxAppProvider(), tx.getBmCurrency(),
                tx.getBmObMop().getBmObCountry());
        boolean finded = false;
        for (DbeExpendControl checkControl : controlsAfter) {
            if (checkControl.getFtExpensedAmount().compareTo(new BigDecimal(0)) == 0) {
                finded = true;
                break;
            }
        }
        // reset control found
        Assert.assertTrue(finded);
    } catch (RSSException e) {
        ProcessingLimitServiceTest.logger.debug("Exception received: " + e.getMessage());
        Assert.fail("Exception expected");
    }
}

From source file:org.accada.epcis.repository.query.QuerySubscription.java

/**
 * Updates or adds the 'GE_recordTime' query parameter in the given query
 * parameter array and sets its value to the given time.
 * /*from w ww .  j a v  a2s .  c  om*/
 * @param queryParams
 *            The (old) query parameter array.
 * @param initialRecordTime
 *            The time to which the 'GE_recordTime' parameter will be
 *            updated.
 */
private void updateRecordTime(final QueryParams queryParams, final GregorianCalendar initialRecordTime) {
    // update or add GE_recordTime restriction
    boolean foundRecordTime = false;
    for (QueryParam p : this.queryParams.getParam()) {
        if (p.getName().equalsIgnoreCase("GE_recordTime")) {
            LOG.debug("Updating query parameter 'GE_recordTime' with value '" + initialRecordTime.getTime()
                    + "'.");
            p.setValue(initialRecordTime);
            foundRecordTime = true;
            break;
        }
    }
    if (!foundRecordTime) {
        LOG.debug("Adding query parameter 'GE_recordTime' with value '" + initialRecordTime.getTime() + "'.");
        QueryParam newParam = new QueryParam();
        newParam.setName("GE_recordTime");
        newParam.setValue(initialRecordTime);
        this.queryParams.getParam().add(newParam);
    }

    // update the subscription in the db
    updateSubscription(initialRecordTime);
}

From source file:org.wso2.carbon.connector.integration.test.verticalresponse.VerticalResponseConnectorIntegrationTest.java

/**
 * Positive test case for sendEmail method with optional parameters.
 *///from   w  w w  .j a va2 s .  c  o  m
@Test(priority = 2, groups = { "wso2.esb" }, dependsOnMethods = { "testCreateContactWithMandatoryParameters",
        "testCreateContactWithOptionalParameters" }, description = "VerticalResponse {sendEmail} integration "
                + "test with optional parameters.")
public void testSendEmailWithOptionalParameters() throws Exception {

    String urlRemainder = "/messages/emails/";
    String apiURL = connectorProperties.getProperty("apiUrl");
    String email = connectorProperties.getProperty("email");
    String emailOptional = connectorProperties.getProperty("emailOptional");
    String subject = connectorProperties.getProperty("subject");

    // Get next day from calendar:
    GregorianCalendar calendar = new GregorianCalendar();
    calendar.add(calendar.DAY_OF_MONTH, 1);
    Date tomorrow = calendar.getTime();
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    String nextDate = fmt.format(tomorrow);

    esbRequestHeadersMap.put("Action", "urn:sendEmail");
    parametersMap.put("email", email);
    parametersMap.put("subject", subject);
    parametersMap.put("emailOptional", emailOptional);
    parametersMap.put("listId", listId);
    parametersMap.put("scheduledAt", nextDate);

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_sendEmail_optional.json", parametersMap);
    String apiEndPoint = esbRestResponse.getBody().get("url").toString();
    emailId = apiEndPoint.split(urlRemainder)[1];
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(
            apiURL + urlRemainder + emailId + "?type=basic", "GET", apiRequestHeadersMap);

    Assert.assertEquals(apiRestResponse.getHttpStatusCode(), esbRestResponse.getHttpStatusCode());
    Assert.assertEquals(apiRestResponse.getBody().getJSONObject("attributes").get("subject").toString(),
            subject);
    Assert.assertEquals(apiRestResponse.getBody().getJSONObject("attributes").get("id").toString(), emailId);
}

From source file:edu.umm.radonc.ca_dash.controllers.PieChartController.java

public PieChartController() {
    endDate = new Date();
    this.interval = "";

    GregorianCalendar gc = new GregorianCalendar();
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    Map<String, Object> sessionMap = externalContext.getSessionMap();

    if (sessionMap.containsKey("endDate")) {
        endDate = (Date) sessionMap.get("endDate");
    } else {/*from   ww  w  . j  av  a  2s.  c  o m*/
        endDate = new Date();
        sessionMap.put("endDate", endDate);
    }

    if (sessionMap.containsKey("startDate")) {
        startDate = (Date) sessionMap.get("startDate");
    } else {
        gc.setTime(endDate);
        gc.add(Calendar.MONTH, -1);
        startDate = gc.getTime();
        sessionMap.put("startDate", startDate);
        this.interval = "1m";
    }

    this.df = new SimpleDateFormat("MM/dd/YYYY");
    this.decf = new DecimalFormat("###.###");
    this.decf.setRoundingMode(RoundingMode.HALF_UP);
    this.selectedFacility = new Long(-1);
    this.dstats = new SynchronizedDescriptiveStatistics();
    this.dstatsPerDoc = new TreeMap<>();
    this.dstatsPerRTM = new TreeMap<>();
    this.pieChart = new PieChartModel();

    selectedFilters = "all-tx";
}

From source file:org.apache.unomi.services.services.ProfileServiceImpl.java

public Session loadSession(String sessionId, Date dateHint) {
    Session s = persistenceService.load(sessionId, dateHint, Session.class);
    if (s == null && dateHint != null) {
        GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(dateHint);/*from   w w  w  . j a  v a2 s .co  m*/
        if (gc.get(Calendar.DAY_OF_MONTH) == 1) {
            gc.add(Calendar.DAY_OF_MONTH, -1);
            s = persistenceService.load(sessionId, gc.getTime(), Session.class);
        }
    }
    return s;
}

From source file:org.webical.test.web.component.DayViewPanelTest.java

public void testWithEvents() throws WebicalException {

    // Get the CalendarManager.
    MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock
            .getBean("calendarManager");
    Calendar calendar1 = mockCalendarManager.getCalendarById("1");

    // Add an EventManager for the test Events.
    MockEventManager mockEventManager = new MockEventManager();
    annotApplicationContextMock.putBean("eventManager", mockEventManager);

    final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek());

    GregorianCalendar cal = CalendarUtils.duplicateCalendar(currentDate);
    GregorianCalendar refcal = CalendarUtils.duplicateCalendar(currentDate);
    refcal.set(GregorianCalendar.HOUR_OF_DAY, 12);
    refcal.set(GregorianCalendar.MINUTE, 0);
    refcal.set(GregorianCalendar.SECOND, 0);

    // Create list with events for the manager
    final List<Event> events = new ArrayList<Event>();
    // Add a normal event
    Event event = new Event();
    event.setUid("e1");
    event.setCalendar(calendar1);//w  w w.  ja  v a2s  .  c  om
    event.setSummary("Normal Event Summary");
    event.setLocation("Normal Event Location");
    event.setDescription("Normal Event Description");
    event.setDtStart(refcal.getTime());
    event.setDtEnd(CalendarUtils.addHours(refcal.getTime(), 2));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a recurring event, starting yesterday, ending tommorrow
    event = new Event();
    event.setUid("e2");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Yesterday Summary");
    event.setLocation("Recurring Event Location");
    event.setDescription("Recurring Event Yesterday Description");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.DAY_OF_MONTH, 2);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event, new Recurrence(0, 1, cal.getTime()));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a recurring event, starting last month, ending next month
    event = new Event();
    event.setUid("e3");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Last Month Summary");
    event.setLocation("Recurring Event Location");
    event.setDescription("Recurring Event Last Month Description");
    cal.setTime(refcal.getTime());
    cal.add(GregorianCalendar.MONTH, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.MONTH, 2);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event, new Recurrence(0, 1, CalendarUtils.getEndOfDay(cal.getTime())));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Add a (pseudo) all day event, starting today 00:00 hours, ending today 00:00 hours
    event = new Event();
    event.setUid("e4");
    event.setCalendar(calendar1);
    event.setSummary("Pseudo All Day Event");
    event.setLocation("All Day Event Location");
    event.setDescription("Starting yesterday midnight, ending today 00:00 hours");
    cal.setTime(refcal.getTime());
    cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
    cal.set(GregorianCalendar.MINUTE, 0);
    cal.set(GregorianCalendar.SECOND, 0);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    events.add(event);
    mockEventManager.storeEvent(event);

    // Create the test page with a DayViewPanel
    wicketTester.startPage(new ITestPageSource() {
        private static final long serialVersionUID = 1L;

        public Page getTestPage() {
            return new PanelTestPage(new DayViewPanel(PanelTestPage.PANEL_MARKUP_ID, 1, currentDate) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onAction(IAction action) {
                    /* NOTHING TO DO */ }
            });
        }
    });

    // Basic assertions
    wicketTester.assertRenderedPage(PanelTestPage.class);
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID, DayViewPanel.class);

    // Assert the heading label
    DateFormat dateFormat = new SimpleDateFormat("EEEE", getTestSession().getLocale());
    wicketTester.assertLabel(PanelTestPage.PANEL_MARKUP_ID + ":dayLink",
            dateFormat.format(currentDate.getTime()));

    // Assert the number of events rendered
    String panelPath = PanelTestPage.PANEL_MARKUP_ID + ":eventItem";
    wicketTester.assertListView(panelPath, events);
}

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

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//from ww  w .j ava2s  .  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);

                Date createdTime = billingAccount.getCreatedtime();
                long timeDeviation = System.currentTimeMillis() - createdTime.getTime();
                int daysLeft = (int) Math.floor(timeDeviation / (double) (DateTimeUtils.MILISECONDS_IN_A_DAY));
                if (daysLeft > 30) {
                    BillingService billingService = ApplicationContextUtil.getSpringBean(BillingService.class);
                    BillingPlan freeBillingPlan = billingService.getFreeBillingPlan();
                    //                        billingAccount.setBillingPlan(freeBillingPlan);
                    informLbl.setValue("<div class='informBlock'>TRIAL ENDING<br>"
                            + " 0 DAYS LEFT</div><div class='informBlock'>&gt;&gt;</div>");
                } 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 = ApplicationContextUtil.getSpringBean(LicenseResolver.class);
    if (licenseResolver != null) {
        LicenseInfo licenseInfo = licenseResolver.getLicenseInfo();
        if (licenseInfo != null) {
            if (licenseInfo.isExpired()) {
                Button buyPremiumBtn = new Button("License is expired. Upgrade?", new ClickListener() {
                    @Override
                    public void buttonClick(ClickEvent event) {
                        UI.getCurrent().addWindow(new AdWindow());
                    }
                });
                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(String.format("Trial license: %d days left. Buy?", days),
                        new ClickListener() {
                            @Override
                            public void buttonClick(ClickEvent event) {
                                UI.getCurrent().addWindow(new AdWindow());
                            }
                        });
                buyPremiumBtn.setIcon(FontAwesome.SHOPPING_CART);
                buyPremiumBtn.addStyleName("ad");
                accountLayout.addComponent(buyPremiumBtn);
            }
        }
    }

    NotificationComponent notificationComponent = new NotificationComponent();
    accountLayout.addComponent(notificationComponent);
    if (AppContext.getUser().getTimezone() == null) {
        EventBusFactory.getInstance().post(new ShellEvent.NewNotification(this, new TimezoneNotification()));
    }

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

    if ("admin@mycollab.com".equals(AppContext.getUsername())) {
        EventBusFactory.getInstance()
                .post(new ShellEvent.NewNotification(this, new ChangeDefaultUsernameNotification()));
    }

    if (!SiteConfiguration.isDemandEdition()) {
        ExtMailService mailService = ApplicationContextUtil.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())) {
            EventBusFactory.getInstance().post(new ShellEvent.RequestAd(this, null));
        }
    }

    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("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("Make 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 supportBtn = new 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 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/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:org.webical.test.web.component.WeekViewPanelTest.java

public void testWeekUse() throws WebicalException {
    MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock
            .getBean("calendarManager");
    Calendar calendar1 = mockCalendarManager.getCalendarById("1");

    MockEventManager mockEventManager = new MockEventManager();
    annotApplicationContextMock.putBean("eventManager", mockEventManager);

    SimpleDateFormat dateFormat = new SimpleDateFormat(
            WebicalSession.getWebicalSession().getUserSettings().getTimeFormat(), getTestSession().getLocale());

    final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek());

    // All events for this week
    List<Event> allEvents = new ArrayList<Event>();

    Date midWeek = CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek());
    midWeek = CalendarUtils.addDays(midWeek, 3);

    /* CREATE EVENTS TO RENDER */
    GregorianCalendar cal = CalendarUtils.duplicateCalendar(currentDate);

    // Add a normal event this week
    Event event = new Event();
    event.setUid("e1");
    event.setCalendar(calendar1);//from ww w.jav  a  2  s. com
    event.setSummary("Normal Event Description");
    event.setLocation("Normal Event Location");
    event.setDescription("Event e1");
    cal.setTime(midWeek);
    cal.set(GregorianCalendar.HOUR_OF_DAY, 12);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a short recurring event, starting Tuesday, ending Friday
    event = new Event();
    event.setUid("e2");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Yesterday");
    event.setLocation("Recurring Event Location");
    event.setDescription("Event e2");
    cal.setTime(midWeek);
    cal.set(GregorianCalendar.HOUR_OF_DAY, 15);
    cal.add(GregorianCalendar.DAY_OF_MONTH, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 3);
    cal.add(GregorianCalendar.DAY_OF_MONTH, 3);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event,
            new Recurrence(Recurrence.DAILY, 1, CalendarUtils.getEndOfDay(cal.getTime())));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a long recurring event, starting last month, ending next month
    event = new Event();
    event.setUid("e3");
    event.setCalendar(calendar1);
    event.setSummary("Recurring Event Last Month");
    event.setLocation("Recurring Event Location");
    event.setDescription("Event e3");
    cal.setTime(midWeek);
    cal.set(GregorianCalendar.HOUR_OF_DAY, 9);
    cal.add(GregorianCalendar.WEEK_OF_YEAR, -1);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    cal.add(GregorianCalendar.WEEK_OF_YEAR, 3);
    event.setDtEnd(cal.getTime());
    RecurrenceUtil.setRecurrenceRule(event,
            new Recurrence(Recurrence.DAILY, 1, CalendarUtils.getEndOfDay(cal.getTime())));
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a (pseudo) all day event, starting Monday midnight, ending Tuesday 00:00 hours
    event = new Event();
    event.setUid("e4");
    event.setCalendar(calendar1);
    event.setSummary("Pseudo All Day Event");
    event.setLocation("All Day Event Location");
    event.setDescription("Starting Monday 00:00 hours, ending Tuesday 00:00 hours");
    cal.setTime(midWeek);
    cal.add(GregorianCalendar.DAY_OF_MONTH, -2);
    cal.set(GregorianCalendar.HOUR_OF_DAY, 0);
    cal.set(GregorianCalendar.MINUTE, 0);
    cal.set(GregorianCalendar.SECOND, 0);
    cal.set(GregorianCalendar.MILLISECOND, 0);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Add a long event this week starting Friday 14.00 hours and ending Saturday 16.00 hours
    event = new Event();
    event.setUid("e5");
    event.setCalendar(calendar1);
    event.setSummary("Long Event Description");
    event.setLocation("Long Event Location");
    event.setDescription("Event e5");
    cal.setTime(midWeek);
    cal.add(GregorianCalendar.DAY_OF_MONTH, 2);
    cal.set(GregorianCalendar.HOUR_OF_DAY, 14);
    cal.set(GregorianCalendar.MINUTE, 0);
    event.setDtStart(cal.getTime());
    cal.add(GregorianCalendar.DAY_OF_MONTH, 1);
    cal.add(GregorianCalendar.HOUR_OF_DAY, 2);
    event.setDtEnd(cal.getTime());
    log.debug(
            "Adding event: " + event.getDescription() + " -> " + event.getDtStart() + " - " + event.getDtEnd());
    allEvents.add(event);
    mockEventManager.storeEvent(event);

    // Create test page with a WeekViewPanel
    wicketTester.startPage(new ITestPageSource() {
        private static final long serialVersionUID = 1L;

        public Page getTestPage() {
            return new PanelTestPage(new WeekViewPanel(PanelTestPage.PANEL_MARKUP_ID, 7, currentDate) {
                private static final long serialVersionUID = 1L;

                @Override
                public void onAction(IAction action) {
                    /* NOTHING TO DO */ }
            });
        }
    });

    // Basic assertions
    wicketTester.assertRenderedPage(PanelTestPage.class);
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID, WeekViewPanel.class);

    // Set the correct dates to find the first and last day of the week

    // Assert number of days rendered
    GregorianCalendar weekFirstDayCalendar = CalendarUtils.duplicateCalendar(currentDate);
    weekFirstDayCalendar.setTime(CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek()));
    // Assert the first day in the view
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
            + weekFirstDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class);

    GregorianCalendar weekLastDayCalendar = CalendarUtils.duplicateCalendar(currentDate);
    weekLastDayCalendar.setTime(CalendarUtils.getLastDayOfWeek(currentDate.getTime(), getFirstDayOfWeek()));
    // Assert the last day in the view
    wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
            + weekLastDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class);

    // Events for days in this week
    List<Event> dayEvents = new ArrayList<Event>();
    // Assert weekday events
    GregorianCalendar weekCal = CalendarUtils.duplicateCalendar(currentDate);
    weekCal.setTime(CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek()));
    for (int i = 0; i < 7; ++i) {
        WeekDayPanel weekDayEventsListView = (WeekDayPanel) wicketTester.getLastRenderedPage()
                .get(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day"
                        + weekCal.get(GregorianCalendar.DAY_OF_YEAR));
        int weekDay = getFirstDayOfWeek() + weekCal.get(GregorianCalendar.DAY_OF_WEEK) - 1; // First day of the week is 1
        if (weekDay > 7)
            weekDay = 1;
        switch (weekDay) {
        case GregorianCalendar.SUNDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(2)); // e3
            break;
        case GregorianCalendar.MONDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(2)); // e3
            dayEvents.add(allEvents.get(3)); // e4
            break;
        case GregorianCalendar.TUESDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            break;
        case GregorianCalendar.WEDNESDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(0)); // e1
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            break;
        case GregorianCalendar.THURSDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            break;
        case GregorianCalendar.FRIDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(1)); // e2
            dayEvents.add(allEvents.get(2)); // e3
            dayEvents.add(allEvents.get(4)); // e5
            break;
        case GregorianCalendar.SATURDAY:
            dayEvents.clear();
            dayEvents.add(allEvents.get(2)); // e3
            dayEvents.add(allEvents.get(4)); // e5
            break;
        }
        String path = weekDayEventsListView.getPageRelativePath() + ":eventItem";
        wicketTester.assertListView(path, dayEvents);

        ListView listView = (ListView) wicketTester.getComponentFromLastRenderedPage(path);
        Iterator<?> lvIt = listView.iterator();
        while (lvIt.hasNext()) {
            ListItem item = (ListItem) lvIt.next();
            Event evt = (Event) item.getModelObject();
            List<?> bhvs = item.getBehaviors();
            if (evt.getUid().equals("e4"))
                assertEquals(1, bhvs.size()); // only e4 is an all day event
            else
                assertEquals(0, bhvs.size());

            if (evt.getUid().equals("e5")) { // e5: Fri 14:00 to Sat 16:00
                String timePath = item.getPageRelativePath() + ":eventLink:eventTime";
                String timeLabelText = null;
                if (weekDay == GregorianCalendar.FRIDAY)
                    timeLabelText = dateFormat.format(evt.getDtStart());
                else
                    timeLabelText = dateFormat.format(midWeek); // time 00:00
                wicketTester.assertLabel(timePath, timeLabelText);
            }
        }

        weekCal.add(GregorianCalendar.DAY_OF_WEEK, 1);
    }
}