List of usage examples for java.util GregorianCalendar add
@Override public void add(int field, int amount)
From source file:com.mothsoft.alexis.engine.numeric.TopicActivityDataSetImporter.java
@Override public void importData() { if (this.transactionTemplate == null) { this.transactionTemplate = new TransactionTemplate(this.transactionManager); }//from w ww .java 2 s . c o m final List<Long> userIds = listUserIds(); final GregorianCalendar calendar = new GregorianCalendar(); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); int minute = calendar.get(Calendar.MINUTE); if (minute >= 45) { calendar.set(Calendar.MINUTE, 30); } else if (minute >= 30) { calendar.set(Calendar.MINUTE, 15); } else if (minute >= 15) { calendar.set(Calendar.MINUTE, 0); } else if (minute >= 0) { calendar.set(Calendar.MINUTE, 45); calendar.add(Calendar.HOUR_OF_DAY, -1); } final Date startDate = calendar.getTime(); calendar.add(Calendar.MINUTE, 15); calendar.add(Calendar.MILLISECOND, -1); final Date endDate = calendar.getTime(); for (final Long userId : userIds) { importTopicDataForUser(userId, startDate, endDate); } }
From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java
public TreeMap<Date, SynchronizedDescriptiveStatistics> getWeeklySummaryStatsAbs(Date startDate, Date endDate, Long hospitalser, String filter, boolean includeWeekends, boolean ptflag, boolean scheduledFlag) { Calendar cal = new GregorianCalendar(); TreeMap<Date, SynchronizedDescriptiveStatistics> retval = new TreeMap<>(); //SET TO BEGINNING OF WK FOR ABSOLUTE CALC cal.setTime(startDate);//from w w w. j a v a2s.c om cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); startDate = cal.getTime(); List<Object[]> events = getDailyCounts(startDate, endDate, hospitalser, filter, false, ptflag, scheduledFlag); DateFormat df = new SimpleDateFormat("MM/dd/yy"); cal.setTime(startDate); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); int wk = cal.get(Calendar.WEEK_OF_YEAR); int mo = cal.get(Calendar.MONTH); int yr = cal.get(Calendar.YEAR); if (mo == Calendar.DECEMBER && wk == 1) { yr = yr + 1; } else if (mo == Calendar.JANUARY && wk == 52) { yr = yr - 1; } String currYrWk = yr + "-" + String.format("%02d", wk); //String prevYrWk = ""; String prevYrWk = currYrWk; SynchronizedDescriptiveStatistics currStats = new SynchronizedDescriptiveStatistics(); int i = 0; while (cal.getTime().before(endDate) && i < events.size()) { Object[] event = events.get(i); Date d = (Date) event[0]; Long count = (Long) event[1]; cal.setTime(d); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); wk = cal.get(Calendar.WEEK_OF_YEAR); mo = cal.get(Calendar.MONTH); yr = cal.get(Calendar.YEAR); if (mo == Calendar.DECEMBER && wk == 1) { yr = yr + 1; } else if (mo == Calendar.JANUARY && wk == 52) { yr = yr - 1; } currYrWk = yr + "-" + String.format("%02d", wk); if (!(prevYrWk.equals(currYrWk))) { GregorianCalendar lastMon = new GregorianCalendar(); lastMon.setTime(cal.getTime()); lastMon.add(Calendar.DATE, -7); retval.put(lastMon.getTime(), currStats); currStats = new SynchronizedDescriptiveStatistics(); } prevYrWk = currYrWk; currStats.addValue(count); i++; } retval.put(cal.getTime(), currStats); return retval; }
From source file:org.webical.test.web.component.WeekViewPanelTest.java
/** * Test week view with less then 7 days//from w ww . j a v a 2s . c o m * @throws WebicalException */ public void testNonWeekUse() throws WebicalException { MockCalendarManager mockCalendarManager = (MockCalendarManager) annotApplicationContextMock .getBean("calendarManager"); Calendar calendar1 = mockCalendarManager.getCalendarById("1"); MockEventManager mockEventManager = new MockEventManager(); annotApplicationContextMock.putBean("eventManager", mockEventManager); // Define the current date final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek()); currentDate.setFirstDayOfWeek(GregorianCalendar.MONDAY); // The list containing the different events List<Event> allEvents = new ArrayList<Event>(); GregorianCalendar refcal = CalendarUtils.duplicateCalendar(currentDate); refcal.add(GregorianCalendar.DAY_OF_MONTH, 1); refcal.set(GregorianCalendar.HOUR_OF_DAY, 12); refcal.set(GregorianCalendar.MINUTE, 0); refcal.set(GregorianCalendar.SECOND, 0); GregorianCalendar cal = CalendarUtils.duplicateCalendar(currentDate); // Add a normal event tomorrow Event event = new Event(); event.setUid("e1"); event.setCalendar(calendar1); event.setSummary("Normal Event Description"); event.setLocation("Normal Event Location"); event.setDescription("Event e1"); cal.setTime(refcal.getTime()); 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 today, ending tomorrow event = new Event(); event.setUid("e2"); event.setCalendar(calendar1); event.setSummary("Recurring Event Today"); event.setLocation("Recurring Event Location"); event.setDescription("Event e2"); 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(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 week, ending next week 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(refcal.getTime()); 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 day + 1 midnight, ending day + 2 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 day + 1, ending day + 2 00:00 hours"); cal.setTime(refcal.getTime()); cal.add(GregorianCalendar.DAY_OF_MONTH, 1); 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); // 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, 4, 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); // Assert number of days rendered // Set the correct dates to find the first and last day of the week GregorianCalendar viewFirstDayCalendar = CalendarUtils.duplicateCalendar(currentDate); // Assert the first day in the view wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day" + viewFirstDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class); GregorianCalendar viewLastDayCalendar = CalendarUtils.duplicateCalendar(currentDate); viewLastDayCalendar.add(GregorianCalendar.DAY_OF_MONTH, 3); // Assert the last day in the view wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day" + viewLastDayCalendar.get(GregorianCalendar.DAY_OF_YEAR), WeekDayPanel.class); // Events for days in this 4 day period List<Event> dayEvents = new ArrayList<Event>(); // Assert weekday events GregorianCalendar weekCal = CalendarUtils.duplicateCalendar(currentDate); for (int i = 0; i < 4; ++i) { WeekDayPanel weekDayEventsListView = (WeekDayPanel) wicketTester.getLastRenderedPage() .get(PanelTestPage.PANEL_MARKUP_ID + ":weekColumnRepeater:day" + weekCal.get(GregorianCalendar.DAY_OF_YEAR)); switch (i) { case 0: dayEvents.clear(); dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 break; case 1: dayEvents.clear(); dayEvents.add(allEvents.get(0)); // e1 dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 break; case 2: dayEvents.clear(); dayEvents.add(allEvents.get(1)); // e2 dayEvents.add(allEvents.get(2)); // e3 dayEvents.add(allEvents.get(3)); // e4 break; case 3: dayEvents.clear(); dayEvents.add(allEvents.get(2)); // e3 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()); // e4 all day event else assertEquals(0, bhvs.size()); } weekCal.add(GregorianCalendar.DAY_OF_WEEK, 1); } }
From source file:org.awknet.commons.model.business.UserBOImpl.java
/** * Verify if a retrieve code still valid. The default time validation is 2 * days.// w w w .j a v a 2 s . co m * * @param requestDate * @return true for if is valid. */ public boolean isValidRequest(Date requestDate, final String retrieveCode) throws RetrieveCodeException { RetrievePasswordLog rpLog = daoFactory.getRetrievePasswordLogDao().findRetrieveCode(retrieveCode); if (rpLog == null) throw new RetrieveCodeException(RetrieveCodeExceptionType.RETRIEVE_CODE); if (rpLog.getUpdated()) throw new RetrieveCodeException(RetrieveCodeExceptionType.RETRIEVE_CODE); LOG.debug("[VALID REQUEST] found something!"); // int // days=SystemMessageAcessor.getPropertyAsInteger("request.activation.form.valid.until.days"); int days = RetrievePasswordLog.DEFAULT_TIME_RETRIEVE_CODE; GregorianCalendar currentDate = new GregorianCalendar(); GregorianCalendar dateGenerateLink = new GregorianCalendar(); dateGenerateLink.setTime(requestDate); dateGenerateLink.add(Calendar.DAY_OF_YEAR, days); if (currentDate.before(dateGenerateLink)) { return true; // try { // FIXME must set true here? // rpLog.setUpdated(true); // daoFactory.beginTransaction(); // daoFactory.getRetrievePasswordLogDao().update(rpLog); // daoFactory.commit(); // return true; // } catch (ConstraintViolationException e) { // // FIXME adjust message // LOG.error("[VALID REQUEST] code not updated in DB.", e); // return false; // } catch (Exception e) { // LOG.error("[VALID REQUEST] generic error in DB.", e); // return false; // } } return false; }
From source file:com.qut.middleware.esoe.sso.impl.AuthenticationAuthorityProcessorFuncTest.java
/** * Test method for/*from w w w. ja v a 2s . c o m*/ * {@link com.qut.middleware.esoe.sso.impl.SSOProcessorImpl#execute(com.qut.middleware.esoe.sso.bean.SSOProcessorData)}. * Tests for successful sso authn response creation within an allowed time skew, should set AuthnContextClassRef to * previousSession */ @Test public void testExecute2a() throws Exception { String authnIdentifier = "12345-12345"; List<String> entities = new ArrayList<String>(); entities.add("12345-12345"); authAuthorityProcessor = new SSOProcessorImpl(samlValidator, sessionsProcessor, this.metadata, identifierGenerator, metadata, keyStoreResolver, identifierMap, handlers, properties); data.setHttpRequest(request); data.setHttpResponse(response); data.setSessionID("1234567890"); data.setSamlBinding(BindingConstants.httpPost); data.setRequestDocument(generateValidRequest(true, 0)); expect(metadata.resolveKey(this.spepKeyAlias)).andReturn(pk).atLeastOnce(); expect(sessionsProcessor.getQuery()).andReturn(query).atLeastOnce(); expect(query.queryAuthnSession("1234567890")).andReturn(principal).atLeastOnce(); entityData = createMock(EntityData.class); spepRole = createMock(SPEPRole.class); expect(entityData.getRoleData(SPEPRole.class)).andReturn(spepRole).anyTimes(); expect(spepRole.getNameIDFormatList()).andReturn(this.defaultSupportedType).anyTimes(); expect(spepRole.getAssertionConsumerServiceEndpoint(BindingConstants.httpPost, 0)) .andReturn("https://spep.qut.edu.au/sso/aa").anyTimes(); expect(metadata.getEntityData(this.issuer)).andReturn(entityData).anyTimes(); expect(metadata.getEntityRoleData(this.issuer, SPEPRole.class)).andReturn(spepRole).anyTimes(); expect(principal.getSAMLAuthnIdentifier()).andReturn(authnIdentifier).atLeastOnce(); expect(principal.getActiveEntityList()).andReturn(entities).atLeastOnce(); /* User originally authenticated a long time in the past */ expect(principal.getAuthnTimestamp()).andReturn(System.currentTimeMillis()).atLeastOnce(); expect(principal.getAuthenticationContextClass()).andReturn(AuthenticationContextConstants.previousSession) .anyTimes(); expect(principal.getPrincipalAuthnIdentifier()).andReturn("beddoes").atLeastOnce(); GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.SECOND, 100); expect(principal.getSessionNotOnOrAfter()) .andReturn(new XMLGregorianCalendarImpl(cal).toGregorianCalendar().getTimeInMillis()).atLeastOnce(); principal.addEntitySessionIndex((String) notNull(), (String) notNull()); expect(sessionsProcessor.getUpdate()).andReturn(update).anyTimes(); expect(identifierGenerator.generateSAMLSessionID()).andReturn("_1234567-1234567-samlsessionid"); expect(request.getServerName()).andReturn("http://esoe-unittest.code"); expect(identifierGenerator.generateSAMLID()).andReturn("_1234567-1234567-samlid").once(); expect(identifierGenerator.generateSAMLID()).andReturn("_1234567-1234568-samlid").anyTimes(); setUpMock(); SSOProcessor.result result = authAuthorityProcessor.execute(data); assertEquals("Ensure success result for response creation", SSOProcessor.result.SSOGenerationSuccessful, result); Response samlResponse = unmarshaller.unMarshallSigned(data.getResponseDocument()); assertTrue("Asserts the response document InReplyTo field is the same value as the original request id", samlResponse.getInResponseTo().equals(this.issuer)); tearDownMock(); }
From source file:org.extensiblecatalog.ncip.v2.koha.KohaLookupUserService.java
private void updateResponseData(ILSDIvOneOneLookupUserInitiationData initData, ILSDIvOneOneLookupUserResponseData responseData, JSONObject kohaUser, KohaRemoteServiceManager svcMgr) throws ParseException, KohaException { ResponseHeader responseHeader = KohaUtil.reverseInitiationHeader(initData); if (responseHeader != null) responseData.setResponseHeader(responseHeader); UserId userId = KohaUtil.createUserId(initData.getUserId().getUserIdentifierValue(), LocalConfig.getDefaultAgency()); responseData.setUserId(userId);//from www . ja v a 2 s . c o m UserOptionalFields userOptionalFields = new UserOptionalFields(); if (LocalConfig.useRestApiInsteadOfSvc()) { if (initData.getNameInformationDesired()) { String firstname = (String) kohaUser.get("firstname"); String surname = (String) kohaUser.get("surname"); String title = (String) kohaUser.get("title"); String othernames = (String) kohaUser.get("othernames"); StructuredPersonalUserName structuredPersonalUserName = new StructuredPersonalUserName(); structuredPersonalUserName.setGivenName(firstname); structuredPersonalUserName.setPrefix(title); structuredPersonalUserName.setSurname(surname); structuredPersonalUserName.setSuffix(othernames); PersonalNameInformation personalNameInformation = new PersonalNameInformation(); personalNameInformation.setStructuredPersonalUserName(structuredPersonalUserName); NameInformation nameInformation = new NameInformation(); nameInformation.setPersonalNameInformation(personalNameInformation); userOptionalFields.setNameInformation(nameInformation); } if (initData.getUserAddressInformationDesired()) userOptionalFields.setUserAddressInformations(KohaUtil.parseUserAddressInformations(kohaUser)); if (initData.getUserPrivilegeDesired()) { String branchcode = (String) kohaUser.get("branchcode"); String agencyUserPrivilegeType = (String) kohaUser.get("categorycode"); if (branchcode != null && agencyUserPrivilegeType != null) { List<UserPrivilege> userPrivileges = new ArrayList<UserPrivilege>(); UserPrivilege userPrivilege = new UserPrivilege(); userPrivilege.setAgencyId(new AgencyId(branchcode)); userPrivilege.setAgencyUserPrivilegeType(new AgencyUserPrivilegeType( "http://www.niso.org/ncip/v1_0/imp1/schemes/agencyuserprivilegetype/agencyuserprivilegetype.scm", agencyUserPrivilegeType)); userPrivilege.setValidFromDate( KohaUtil.parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateenrolled"))); userPrivilege.setValidToDate( KohaUtil.parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateexpiry"))); userPrivileges.add(userPrivilege); userOptionalFields.setUserPrivileges(userPrivileges); } } if (initData.getDateOfBirthDesired()) { String dateOfBirth = (String) kohaUser.get("dateofbirth"); userOptionalFields.setDateOfBirth(KohaUtil.parseGregorianCalendarFromKohaDate(dateOfBirth)); } if (initData.getLoanedItemsDesired()) { JSONArray checkouts = (JSONArray) kohaUser.get("checkouts"); if (checkouts != null && checkouts.size() != 0) { List<LoanedItem> loanedItems = new ArrayList<LoanedItem>(); for (int i = 0; i < checkouts.size(); ++i) { JSONObject checkout = (JSONObject) checkouts.get(i); loanedItems.add(KohaUtil.parseLoanedItem(checkout)); } responseData.setLoanedItems(loanedItems); } } if (initData.getRequestedItemsDesired()) { JSONArray holds = (JSONArray) kohaUser.get("holds"); if (holds != null && holds.size() != 0) { List<RequestedItem> requestedItems = new ArrayList<RequestedItem>(); for (int i = 0; i < holds.size(); ++i) { JSONObject hold = (JSONObject) holds.get(i); RequestedItem requestedItem = KohaUtil.parseRequestedItem(hold); if (requestedItem != null) requestedItems.add(requestedItem); } responseData.setRequestedItems(requestedItems); } } if (initData.getBlockOrTrapDesired()) { List<BlockOrTrap> blocks = new ArrayList<BlockOrTrap>(4); // Parse expiration GregorianCalendar expiryDate = KohaUtil .parseGregorianCalendarFromKohaDate((String) kohaUser.get("dateexpiry")); GregorianCalendar warningForExpiryDateGregCal = ((GregorianCalendar) expiryDate.clone()); warningForExpiryDateGregCal.add(GregorianCalendar.DAY_OF_YEAR, -14); Date now = new Date(); if (now.after(expiryDate.getTime())) { BlockOrTrap expired = KohaUtil.createBlockOrTrap("Expired"); blocks.add(expired); } else if (now.after(warningForExpiryDateGregCal.getTime())) { Days days = Days.daysBetween(new DateTime(now), new DateTime(expiryDate)); BlockOrTrap expiresSoon = KohaUtil .createBlockOrTrap("Expires in " + (days.getDays() + 1) + " days"); blocks.add(expiresSoon); } // Parse debarred status String debarredStatus = (String) kohaUser.get("debarred"); if (debarredStatus != null && !debarredStatus.isEmpty()) { String debarredComment = (String) kohaUser.get("debarredcomment"); BlockOrTrap debarred = KohaUtil.createBlockOrTrap( "Debarred" + (debarredComment != null ? ": " + debarredComment : "")); blocks.add(debarred); } if (blocks.size() > 0) userOptionalFields.setBlockOrTraps(blocks); } if (initData.getUserFiscalAccountDesired()) { JSONArray accountLines = (JSONArray) kohaUser.get("accountLines"); if (accountLines != null && accountLines.size() != 0) { List<UserFiscalAccount> userFiscalAccounts = new ArrayList<UserFiscalAccount>(1); UserFiscalAccount userFiscalAccount = new UserFiscalAccount(); List<AccountDetails> accountDetails = new ArrayList<AccountDetails>(); for (int i = 0; i < accountLines.size(); ++i) { JSONObject accountLine = (JSONObject) accountLines.get(i); accountDetails.add(KohaUtil.parseAccountDetails(accountLine)); } BigDecimal amount = null; // Sum all transactions .. for (AccountDetails details : accountDetails) { if (amount == null) amount = details.getFiscalTransactionInformation().getAmount().getMonetaryValue(); else amount = amount .add(details.getFiscalTransactionInformation().getAmount().getMonetaryValue()); } userFiscalAccount.setAccountBalance(KohaUtil.createAccountBalance(amount)); userFiscalAccount.setAccountDetails(accountDetails); userFiscalAccounts.add(userFiscalAccount); // Suppose user has // only one account // .. responseData.setUserFiscalAccounts(userFiscalAccounts); } } if (initData.getHistoryDesired() != null) { LoanedItemsHistory loanedItemsHistory = KohaUtil.parseLoanedItemsHistory(kohaUser, initData); responseData.setLoanedItemsHistory(loanedItemsHistory); } } else { JSONObject userInfo = (JSONObject) kohaUser.get("userInfo"); if (userInfo != null) { if (initData.getNameInformationDesired()) { String firstname = (String) userInfo.get("firstname"); String surname = (String) userInfo.get("surname"); String title = (String) userInfo.get("title"); String othernames = (String) userInfo.get("othernames"); StructuredPersonalUserName structuredPersonalUserName = new StructuredPersonalUserName(); structuredPersonalUserName.setGivenName(firstname); structuredPersonalUserName.setPrefix(title); structuredPersonalUserName.setSurname(surname); structuredPersonalUserName.setSuffix(othernames); PersonalNameInformation personalNameInformation = new PersonalNameInformation(); personalNameInformation.setStructuredPersonalUserName(structuredPersonalUserName); NameInformation nameInformation = new NameInformation(); nameInformation.setPersonalNameInformation(personalNameInformation); userOptionalFields.setNameInformation(nameInformation); } if (initData.getUserAddressInformationDesired()) userOptionalFields.setUserAddressInformations(KohaUtil.parseUserAddressInformations(userInfo)); if (initData.getUserPrivilegeDesired()) { String branchcode = (String) userInfo.get("branchcode"); String agencyUserPrivilegeType = (String) userInfo.get("categorycode"); if (branchcode != null && agencyUserPrivilegeType != null) { List<UserPrivilege> userPrivileges = new ArrayList<UserPrivilege>(); UserPrivilege userPrivilege = new UserPrivilege(); userPrivilege.setAgencyId(new AgencyId(branchcode)); userPrivilege.setAgencyUserPrivilegeType(new AgencyUserPrivilegeType( "http://www.niso.org/ncip/v1_0/imp1/schemes/agencyuserprivilegetype/agencyuserprivilegetype.scm", agencyUserPrivilegeType)); userPrivilege.setValidFromDate( KohaUtil.parseGregorianCalendarFromKohaDate((String) userInfo.get("dateenrolled"))); userPrivilege.setValidToDate( KohaUtil.parseGregorianCalendarFromKohaDate((String) userInfo.get("dateexpiry"))); userPrivileges.add(userPrivilege); userOptionalFields.setUserPrivileges(userPrivileges); } } if (initData.getBlockOrTrapDesired()) { List<BlockOrTrap> blockOrTraps = KohaUtil.parseBlockOrTraps((JSONArray) userInfo.get("blocks")); userOptionalFields.setBlockOrTraps(blockOrTraps); } if (initData.getDateOfBirthDesired()) { String dateOfBirth = (String) userInfo.get("dateofbirth"); userOptionalFields.setDateOfBirth(KohaUtil.parseGregorianCalendarFromKohaDate(dateOfBirth)); } } JSONArray requestedItemsParsed = (JSONArray) kohaUser.get("requestedItems"); if (requestedItemsParsed != null && requestedItemsParsed.size() != 0) { List<RequestedItem> requestedItems = new ArrayList<RequestedItem>(); for (int i = 0; i < requestedItemsParsed.size(); ++i) { JSONObject requestedItemParsed = (JSONObject) requestedItemsParsed.get(i); RequestedItem requestedItem = KohaUtil.parseRequestedItem(requestedItemParsed); if (requestedItem != null) requestedItems.add(requestedItem); } responseData.setRequestedItems(requestedItems); } JSONArray loanedItemsParsed = (JSONArray) kohaUser.get("loanedItems"); if (loanedItemsParsed != null && loanedItemsParsed.size() != 0) { List<LoanedItem> loanedItems = new ArrayList<LoanedItem>(); for (int i = 0; i < loanedItemsParsed.size(); ++i) { JSONObject loanedItem = (JSONObject) loanedItemsParsed.get(i); loanedItems.add(KohaUtil.parseLoanedItem(loanedItem)); } responseData.setLoanedItems(loanedItems); } JSONArray userFiscalAccountParsed = (JSONArray) kohaUser.get("userFiscalAccount"); if (userFiscalAccountParsed != null && userFiscalAccountParsed.size() != 0) { List<UserFiscalAccount> userFiscalAccounts = new ArrayList<UserFiscalAccount>(); UserFiscalAccount userFiscalAccount = new UserFiscalAccount(); List<AccountDetails> accountDetails = new ArrayList<AccountDetails>(); for (int i = 0; i < userFiscalAccountParsed.size(); ++i) { JSONObject accountDetail = (JSONObject) userFiscalAccountParsed.get(i); accountDetails.add(KohaUtil.parseAccountDetails(accountDetail)); } BigDecimal amount = null; // Sum all transactions .. for (AccountDetails details : accountDetails) { if (amount == null) amount = details.getFiscalTransactionInformation().getAmount().getMonetaryValue(); else amount.add(details.getFiscalTransactionInformation().getAmount().getMonetaryValue()); } userFiscalAccount.setAccountBalance(KohaUtil.createAccountBalance(amount)); userFiscalAccount.setAccountDetails(accountDetails); userFiscalAccounts.add(userFiscalAccount); // Suppose user has // only one account // .. responseData.setUserFiscalAccounts(userFiscalAccounts); } } responseData.setUserOptionalFields(userOptionalFields); }
From source file:edu.umm.radonc.ca_dash.model.TxInstanceFacade.java
public Map<Date, SynchronizedDescriptiveStatistics> getWeeklyTrailingSummaryStats(Date startDate, Date endDate, Long hospitalser, String filter, boolean includeWeekends, boolean ptflag, boolean scheduledFlag) { TreeMap<Date, SynchronizedDescriptiveStatistics> retval = new TreeMap(); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(endDate);/*from w w w .java 2s. c o m*/ Date d; SynchronizedDescriptiveStatistics stats; while (gc.getTime().compareTo(startDate) > 0) { d = gc.getTime(); gc.add(Calendar.DATE, -7); stats = getDailyStats(gc.getTime(), d, hospitalser, filter, includeWeekends, ptflag, scheduledFlag); retval.put(gc.getTime(), stats); } return retval; }
From source file:iSoron.HistoryChart.java
private void drawColumn(Canvas canvas, RectF location, GregorianCalendar date, int column) { drawColumnHeader(canvas, location, date); location.offset(0, columnWidth);/*www . jav a2s .c o m*/ for (int j = 0; j < 7; j++) { if (!(column == nColumns - 2 && getDataOffset() == 0 && j > todayPositionInColumn)) { int checkmarkOffset = getDataOffset() * 7 + nDays - 7 * (column + 1) + todayPositionInColumn - j; drawSquare(canvas, location, date, checkmarkOffset); } date.add(Calendar.DAY_OF_MONTH, 1); location.offset(0, columnWidth); } }
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'>>></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 w ww . j av a 2 s .co 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'>>></div>"); } else { informLbl.setValue(String.format( "<div class='informBlock'>TRIAL ENDING<br>%d DAYS LEFT</div><div class='informBlock'>>></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.apache.unomi.services.services.ProfileServiceImpl.java
private GregorianCalendar getMonth(int offset) { GregorianCalendar gc = new GregorianCalendar(); gc = new GregorianCalendar(gc.get(Calendar.YEAR), gc.get(Calendar.MONTH), 1); gc.add(Calendar.MONTH, offset); return gc;//from w ww . j av a 2 s.com }