List of usage examples for java.util GregorianCalendar add
@Override public void add(int field, int amount)
From source file:nodomain.freeyourgadget.gadgetbridge.service.devices.miband2.operations.FetchActivityOperation.java
private GregorianCalendar saveSamples() { if (samples.size() > 0) { // save all the samples that we got try (DBHandler handler = GBApplication.acquireDB()) { DaoSession session = handler.getDaoSession(); SampleProvider<MiBandActivitySample> sampleProvider = new MiBandSampleProvider(getDevice(), session);/*from ww w . j a va2s. c om*/ Device device = DBHelper.getDevice(getDevice(), session); User user = DBHelper.getUser(session); GregorianCalendar timestamp = (GregorianCalendar) startTimestamp.clone(); for (MiBandActivitySample sample : samples) { sample.setDevice(device); sample.setUser(user); sample.setTimestamp((int) (timestamp.getTimeInMillis() / 1000)); sample.setProvider(sampleProvider); if (LOG.isDebugEnabled()) { // LOG.debug("sample: " + sample); } timestamp.add(Calendar.MINUTE, 1); } sampleProvider.addGBActivitySamples(samples.toArray(new MiBandActivitySample[0])); saveLastSyncTimestamp(timestamp); LOG.info("Mi2 activity data: last sample timestamp: " + DateTimeUtils.formatDateTime(timestamp.getTime())); return timestamp; } catch (Exception ex) { GB.toast(getContext(), "Error saving activity samples", Toast.LENGTH_LONG, GB.ERROR); } finally { samples.clear(); } } return null; }
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);/*w ww . j a va2 s .c o 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.wso2.carbon.connector.integration.test.verticalresponse.VerticalResponseConnectorIntegrationTest.java
/** * Positive test case for sendEmail method with optional parameters. *//*w w w.j av a2s .c om*/ @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:org.webical.test.web.component.MonthViewPanelTest.java
/** * Test rendering of the panel without events. *//* w ww .ja va 2s . c o m*/ public void testRenderingWithoutEvents() { log.debug("testRenderingWithoutEvents"); // Add an EventManager annotApplicationContextMock.putBean("eventManager", new MockEventManager()); final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek()); // render start page with a MonthViewPanel wicketTester.startPage(new ITestPageSource() { private static final long serialVersionUID = 1L; public Page getTestPage() { return new PanelTestPage(new MonthViewPanel(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, MonthViewPanel.class); // Weekday headers wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":monthHeaderRepeater", RepeatingView.class); DateFormat dateFormat = new SimpleDateFormat("E", getTestSession().getLocale()); GregorianCalendar weekCal = CalendarUtils.duplicateCalendar(currentDate); weekCal.setTime(CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek())); for (int i = 0; i < 7; ++i) { wicketTester.assertLabel(PanelTestPage.PANEL_MARKUP_ID + ":monthHeaderRepeater:headerDay" + i, dateFormat.format(weekCal.getTime())); weekCal.add(GregorianCalendar.DAY_OF_WEEK, 1); } // Set the correct dates to find the first and last day of the month GregorianCalendar monthFirstDayDate = CalendarUtils.duplicateCalendar(currentDate); monthFirstDayDate .setTime(CalendarUtils.getFirstDayOfWeekOfMonth(currentDate.getTime(), getFirstDayOfWeek())); log.debug("testRenderingWithoutEvents:monthFirstDayDate " + monthFirstDayDate.getTime()); // Assert the first day in the view wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + monthFirstDayDate.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + monthFirstDayDate.get(GregorianCalendar.DAY_OF_YEAR), MonthDayPanel.class); GregorianCalendar monthLastDayDate = CalendarUtils.duplicateCalendar(currentDate); monthLastDayDate.setTime(CalendarUtils.getLastWeekDayOfMonth(currentDate.getTime(), getFirstDayOfWeek())); log.debug("testRenderingWithoutEvents:monthLastDayDate " + monthLastDayDate.getTime()); // Assert the last day in the view wicketTester.assertComponent(PanelTestPage.PANEL_MARKUP_ID + ":monthRowRepeater:week" + monthLastDayDate.get(GregorianCalendar.WEEK_OF_YEAR) + ":monthDayRepeater:day" + monthLastDayDate.get(GregorianCalendar.DAY_OF_YEAR), MonthDayPanel.class); }
From source file:com.qut.middleware.esoe.sso.impl.AuthenticationAuthorityProcessorFuncTest.java
/** * Test method for//from www.j a va 2s .com * {@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 * PasswordProtectedTransport */ @Test public void testExecute2() 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.setIssuerID("12345-12345"); 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 basically within the same request timeframe */ expect(principal.getAuthnTimestamp()).andReturn(System.currentTimeMillis() - 200).atLeastOnce(); expect(principal.getAuthenticationContextClass()) .andReturn(AuthenticationContextConstants.passwordProtectedTransport).atLeastOnce(); expect(principal.getPrincipalAuthnIdentifier()).andReturn("beddoes").atLeastOnce(); //principal.addEntitySessionIndex((String) notNull(), (String) notNull()); TimeZone utc = new SimpleTimeZone(0, ConfigurationConstants.timeZone); GregorianCalendar cal = new GregorianCalendar(utc); // add skew offset that will keep notonorafter within allowable session range cal.add(Calendar.SECOND, 1000); expect(principal.getSessionNotOnOrAfter()) .andReturn(new XMLGregorianCalendarImpl(cal).toGregorianCalendar().getTimeInMillis() + 2000000) .atLeastOnce(); expect(sessionsProcessor.getUpdate()).andReturn(update).anyTimes(); expect(identifierGenerator.generateSAMLSessionID()).andReturn("_1234567-1234567-samlsessionid").anyTimes(); update.addEntitySessionIndex((Principal) notNull(), "1234567890", this.issuer); expect(request.getServerName()).andReturn("http://esoe-unittest.code").anyTimes(); expect(identifierGenerator.generateSAMLID()).andReturn("_1234567-1234567").once(); expect(identifierGenerator.generateSAMLID()).andReturn("_890123-890123").once(); 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)); // now validate it this.samlValidator.getResponseValidator().validate(samlResponse); tearDownMock(); }
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 w w w. j ava2 s.com 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:se.inera.axel.shs.broker.messagestore.internal.MongoMessageLogServiceIT.java
@Test(groups = "largeTests") public void listMessagesWithSince() throws Exception { MessageLogService.Filter filter = new MessageLogService.Filter(); Iterable<ShsMessageEntry> iter = messageLogService.listMessages(ShsLabelMaker.DEFAULT_TEST_FROM, filter); List<ShsMessageEntry> list = Lists.newArrayList(iter); int sizeWithoutSince = list.size(); Assert.assertTrue(sizeWithoutSince > 2, "more than 2 messages should exist"); GregorianCalendar yesterDay = new GregorianCalendar(); yesterDay.add(GregorianCalendar.DAY_OF_MONTH, -1); filter.setSince(yesterDay.getTime()); iter = messageLogService.listMessages(ShsLabelMaker.DEFAULT_TEST_FROM, filter); list = Lists.newArrayList(iter);// w ww .j av a2s .c o m int sizeWithSince = list.size(); assertEquals(sizeWithSince, sizeWithoutSince - 1, "sizeWithSince should be one less than sizeWithoutSince"); }
From source file:org.webical.test.web.component.WeekViewPanelTest.java
public void testWithoutEvents() { annotApplicationContextMock.putBean("eventManager", new MockEventManager()); final GregorianCalendar currentDate = CalendarUtils.newTodayCalendar(getFirstDayOfWeek()); // 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//from w w w . ja v a 2 s.c o m 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 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); // Assert the heading label DateFormat dateFormat = new SimpleDateFormat("E", getTestSession().getLocale()); GregorianCalendar weekCal = CalendarUtils.duplicateCalendar(currentDate); weekCal.setTime(CalendarUtils.getFirstDayOfWeek(currentDate.getTime(), getFirstDayOfWeek())); for (int i = 0; i < 7; ++i) { wicketTester.assertLabel(PanelTestPage.PANEL_MARKUP_ID + ":dayHeadingRepeater:headerDay" + i, dateFormat.format(weekCal.getTime())); weekCal.add(GregorianCalendar.DAY_OF_WEEK, 1); } }
From source file:edu.umm.radonc.ca_dash.controllers.HistogramController.java
public HistogramController() { histogram = new BarChartModel(); percentile = 50.0;//ww w . j ava2 s . c o m dstats = new SynchronizedDescriptiveStatistics(); endDate = new Date(); interval = ""; binInterval = -1; includeWeekends = false; 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 { 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"; } selectedFilters = "all-tx"; selectedFacility = new Long(-1); patientsFlag = true; scheduledFlag = false; relativeModeFlag = false; }
From source file:edu.jhuapl.openessence.web.util.Filters.java
public List<Filter> getFilters(final Map<String, String[]> parameterValues, final OeDataSource ds, final String prePullArg, final int prePullInc, final String resolution, int calWeekStartDay, final boolean adjustDate) throws ErrorMessageException { final List<Filter> filters = new ArrayList<Filter>(); for (final FilterDimension fd : ds.getFilterDimensions()) { final FieldType type = fd.getSqlType(); for (final String sfx : parmSfx.keySet()) { final String key = fd.getId() + sfx; if (!reservedParameters.contains(key)) { final String[] values = parameterValues.get(key); // No values for a filter dimension is ok if (!ArrayUtils.isEmpty(values)) { if (values.length == 1) { Object argument = ControllerUtils.formatData(key, values[0], type, false).get(key); final Relation rel = type == FieldType.TEXT ? Relation.LIKE : parmSfx.get(sfx); try { if (fd.getId().equals(prePullArg) && (rel == Relation.GTEQ)) { argument = muckDate((Date) argument, prePullInc, resolution, calWeekStartDay); }//from w w w .j a va 2 s . c o m // if end date, account for hours 00:00:00 to 23:59:59 if ((type == FieldType.DATE_TIME || type == FieldType.DATE) && (rel == Relation.LTEQ)) { GregorianCalendar x = new GregorianCalendar(); x.setTime((Date) argument); // Only perform this operation if it hasn't already been handled in a previous call. // When generating a Chart, it will go to the end of the day and adjust the filter // to be 23:59:59.999 (5/1/13 becomes 5/1/13-23:59:59.999). But, when the user // would click-through on a bar/slice, it would accidently perform this action again. // This resulted in adding another day to the query; now becoming 5/2/13 23:59:59.998. if (adjustDate) { x.add(Calendar.DATE, 1); x.add(Calendar.MILLISECOND, -1); argument = x.getTime(); } } filters.add(fd.makeFilter(rel, argument)); } catch (OeDataSourceException e) { throw new ErrorMessageException("Could not create filter", e); } } else { final Object[] arguments = new Object[values.length]; for (int i = 0; i < values.length; i++) { arguments[i] = ControllerUtils.formatData(key, values[i], type, false).get(key); } try { filters.add(fd.makeFilter(Relation.IN, arguments)); } catch (OeDataSourceException e) { throw new ErrorMessageException("Could not create filter", e); } } } } } } return filters; }