public static void testTimeZone() { System.out.println("演示时区"); String format = "yyyy-MM-dd HH:mm:ss zZZ"; // DateTime的毫秒即System的毫秒,即1970到现在的UTC的毫秒数. System.out.println(new DateTime().getMillis() + " " + System.currentTimeMillis()); // 将日期按默认时区打印 DateTime fooDate = new DateTime(1978, 6, 1, 12, 10, 8, 0); System.out.println( fooDate.toString(format) + " " + fooDate.getMillis()); // "1978-06-01 12:10:08" // 将日期按UTC时区打印 DateTime zoneWithUTC = fooDate.withZone(DateTimeZone.UTC); System.out.println( zoneWithUTC.toString(format) + " " + zoneWithUTC.getMillis()); // "1978-06-01 04:10:08", sameMills // 按不同的时区分析字符串,得到不同的时间 String dateString = "1978-06-01 12:10:08"; DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); DateTime parserResult1 = fmt.withZone(DateTimeZone.forID("US/Pacific")).parseDateTime(dateString); DateTime parserResult2 = fmt.withZone(DateTimeZone.UTC).parseDateTime(dateString); System.out.println(parserResult1.toString(format) + " " + parserResult1.getMillis()); System.out.println(parserResult2.toString(format) + " " + parserResult2.getMillis()); }
public static String formatUTCToLocal(String datetime) { String returnTimeDate = ""; DateTime dtUTC = null; DateTimeZone timezone = DateTimeZone.getDefault(); DateTimeFormatter formatDT = DateTimeFormat.forPattern("MMM dd, yyyy hh:mma"); try { DateTime dateDateTime1 = formatDT.parseDateTime(datetime); DateTime now = new DateTime(); DateTime nowUTC = new LocalDateTime(now).toDateTime(DateTimeZone.UTC); long instant = now.getMillis(); long instantUTC = nowUTC.getMillis(); long offset = instantUTC - instant; // convert to local time dtUTC = dateDateTime1.withZoneRetainFields(DateTimeZone.UTC); // dtUTC = dateDateTime1.toDateTime(timezone); dtUTC = dtUTC.plusMillis((int) offset); returnTimeDate = dtUTC.toString(formatDT); } catch (Exception e) { returnTimeDate = "null"; e.printStackTrace(); } return returnTimeDate; }
@Test public void test_yearAggregationWithoutLeapYears() { DateTimeZone utc = DateTimeZone.UTC; ListDataPointGroup dpGroup = new ListDataPointGroup("range_test"); DateTime startDate = new DateTime(2014, 1, 1, 0, 0, utc); for (DateTime date = startDate; date.isBefore(new DateTime(2015, 6, 2, 0, 0, utc)); date = date.plusMonths(1)) { dpGroup.addDataPoint(new LongDataPoint(date.getMillis(), 1)); } SumAggregator agg = new SumAggregator(new DoubleDataPointFactoryImpl()); agg.setSampling(new Sampling(1, TimeUnit.YEARS)); agg.setAlignSampling(false); agg.setStartTime(startDate.getMillis()); DataPointGroup aggregated = agg.aggregate(dpGroup); assertThat(aggregated.hasNext(), is(true)); assertThat(aggregated.next().getLongValue(), is(12L)); assertThat(aggregated.hasNext(), is(true)); assertThat(aggregated.next().getLongValue(), is(6L)); assertThat(aggregated.hasNext(), is(false)); }
private BtVodProductPricingTier tier(DateTime start, DateTime end, boolean blackout) { BtVodProductPricingTier tier = new BtVodProductPricingTier(); tier.setProductAbsoluteStart(start.getMillis()); tier.setProductAbsoluteEnd(end.getMillis()); tier.setIsBlackout(blackout); return tier; }
@Before public void createTestData() { int index = pvpLeagueIds.size(); for (String league : pvpLeagueIds) { DateTime tim = new DateTime(); tim.minusWeeks(index); index--; String userId = userIds.get(index); PvpLeagueForUser pvp = new PvpLeagueForUser( userId, league, index, index, tim.getMillis(), tim.getMillis(), index, index, index, index, tim.getMillis()); repo.save(pvp); leagues.add(pvp); log.info("Saving: {}", pvp); } }
@Override public ConnectorSplitSource getSplits( ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layoutHandle) { AtopTableLayoutHandle handle = checkType(layoutHandle, AtopTableLayoutHandle.class, "layoutHandle"); AtopTableHandle table = handle.getTableHandle(); List<ConnectorSplit> splits = new ArrayList<>(); DateTime end = DateTime.now().withZone(timeZone); for (Node node : nodeManager.getActiveDatasourceNodes(connectorId.getId())) { DateTime start = end.minusDays(maxHistoryDays - 1).withTimeAtStartOfDay(); while (start.isBefore(end)) { DateTime splitEnd = start.withTime(23, 59, 59, 999); Domain splitDomain = Domain.create( ValueSet.ofRanges( Range.range(TIMESTAMP, start.getMillis(), true, splitEnd.getMillis(), true)), false); if (handle.getStartTimeConstraint().overlaps(splitDomain) && handle.getEndTimeConstraint().overlaps(splitDomain)) { splits.add(new AtopSplit(table.getTable(), node.getHostAndPort(), start)); } start = start.plusDays(1).withTimeAtStartOfDay(); } } return new FixedSplitSource(connectorId.getId(), splits); }
public static long getDateValueFromDateDesc(String leadTime) { if (!Strings.isEmpty(leadTime)) { DateTime dateTime = new DateTime(DateTimeUtils.getDateFromDateDesc(leadTime)); DateTime todayDateTime = new DateTime(0, 12, 31, 0, 0, 0, 0); return dateTime.getMillis() - todayDateTime.getMillis(); } return 0; }
private List<Range> getUnsharedRanges(String streamOwner, String streamName) throws ClassNotFoundException, SQLException, IOException, NamingException, NoSuchAlgorithmException { /*double start = 1392883208801.0; double end = 1392936762729.0; double d = (end - start) / 24; resultRanges.add(new Range(start, start + d)); resultRanges.add(new Range(start + 2*d, start + 3*d)); resultRanges.add(new Range(start + 4*d, start + 5*d)); resultRanges.add(new Range(start + 6*d, start + 7*d)); resultRanges.add(new Range(start + 8*d, start + 9*d));*/ prepareDummyStream(streamOwner, streamName); int[] shareflags = queryUsingDummyStreamAsOtherUser(streamOwner, streamName); // dump share flags StringBuilder sb = new StringBuilder(); sb.append("flags = ["); for (int f : shareflags) { sb.append(f); sb.append(","); } sb.deleteCharAt(sb.length() - 1); sb.append("]"); Log.info(sb.toString()); // Generate unshared ranges List<Range> resultRanges = new ArrayList<Range>(); int prevflag = shareflags[0]; double curStartTime = -1; if (shareflags[0] == 0) { curStartTime = startDate.getMillis(); } for (int i = 1; i < shareflags.length; i++) { int curflag = shareflags[i]; if (prevflag == curflag) { continue; } else if (prevflag == 0 && curflag == 1) { if (curStartTime < 0) { Log.error("invalid curStartTime at " + i); } double endTime = startDate.getMillis() + i * DUMMY_STREAM_INTERVAL * 1000; resultRanges.add(new Range(curStartTime, endTime)); curStartTime = -1; } else if (prevflag == 1 && curflag == 0) { curStartTime = startDate.getMillis() + i * DUMMY_STREAM_INTERVAL * 1000; } prevflag = shareflags[i]; } if (curStartTime > 0) { double endTime = startDate.getMillis() + shareflags.length * DUMMY_STREAM_INTERVAL * 1000; resultRanges.add(new Range(curStartTime, endTime)); } return resultRanges; }
private Query getDateRangeQuery( ShapeRelation relation, DateTime from, DateTime to, boolean includeLower, boolean includeUpper) { return getLongRangeQuery( relation, from.getMillis(), to.getMillis(), includeLower, includeUpper); }
private void logProgress(final long count, final long total, final DateTime begin) { DateTime current = DateTime.now(); long duration = current.getMillis() - begin.getMillis(); int rate = (int) (count / duration) + 1; int remaining = (int) ((total - count) / rate); DateTime done = current.plusMillis(remaining); System.out.printf( "Imported %d of %d (%.2f%%). Estimated completion time: %s\n", count, total, 100.0 * count / total, done.toString("HH:mm:ss")); }
private void cleanUp() { System.out.println("Cleaning up timestamp errors..."); final List<Incident> incidents = trafficInfoService.read("incident", Incident.class); for (final Incident i : incidents) { final String message = i.getMessage(); final String createDate = i.getCreateDate(); // extract date occurred and time occurred from message final String messageValues[] = message.split(" "); final String dateTime = messageValues[0]; // System.out.println("dateTime: " + dateTime); // time and date that incident occurred final String dateTimeValues[] = dateTime.split("\\)"); final String createDateValues[] = createDate.split("T"); final String dateOccurred = createDateValues[0]; // taken from create date (need the year) final String timeOccurred = dateTimeValues[1]; final String dateOccurred2 = dateTimeValues[0]; // taken from message need the month and day final String dateOccurredValues[] = dateOccurred.split("-"); final String dateOccurredValues2[] = dateOccurred2.split("/"); final String timeOccurredValues[] = timeOccurred.split(":"); // Joda Time: year, month, day, hour, min System.out.println( String.format( "Year: %s, month: %s, day: %s, hour: %s, min: %s", Integer.parseInt(dateOccurredValues[0]), Integer.parseInt(dateOccurredValues2[1]), Integer.parseInt(dateOccurredValues2[0].substring(1)), Integer.parseInt(timeOccurredValues[0]), Integer.parseInt(timeOccurredValues[1]))); final DateTime dateTimeOccurred = new DateTime( Integer.parseInt(dateOccurredValues[0]), Integer.parseInt(dateOccurredValues2[1]), Integer.parseInt(dateOccurredValues2[0].substring(1)), Integer.parseInt(timeOccurredValues[0]), Integer.parseInt(timeOccurredValues[1])); i.setStartTimestamp(String.valueOf(dateTimeOccurred.getMillis())); System.out.println("Date: " + dateTimeOccurred); System.out.println("Date in Millis: " + dateTimeOccurred.getMillis()); trafficInfoService.update(i); } System.out.println("Total incidents size: " + incidents.size()); }
public DateTime getStartOfDate(LocalDate date) { // Get the milisecond time for the start of that date in UTC long utcStartMillis = date.toDateTimeAtStartOfDay(DateTimeZone.UTC).getMillis(); // Lookup the timezone for that time - 12 and +12 hours since timezones range from // UTC-12h to UTC+12h so the real start time will be within that range long minStartMillis = utcStartMillis - DateTimeConstants.MILLIS_PER_DAY / 2; long maxStartMillis = utcStartMillis + DateTimeConstants.MILLIS_PER_DAY / 2; TimespanSegment<DateTimeZone> minTimespan = this.queryPoint(minStartMillis); TimespanSegment<DateTimeZone> maxTimespan = this.queryPoint(maxStartMillis); DateTimeZone realTz = null; DateTime realDateStart = null; // Check if they agree if (minTimespan == maxTimespan) { // Ok, they agree so we're good, just use the consensus timezone realTz = minTimespan.getValue(); realDateStart = date.toDateTimeAtStartOfDay(realTz); } else { // The start and end timespans are different, compute the start time in each and see which if // either intersect DateTime minTzStartDT = date.toDateTimeAtStartOfDay(minTimespan.getValue()); DateTime maxTzStartDT = date.toDateTimeAtStartOfDay(maxTimespan.getValue()); // Does the earlier one fall within the timespan for the minTimezone long minTzStartMillis = minTzStartDT.getMillis(); long maxTzStartMillis = maxTzStartDT.getMillis(); if (minTimespan.isTimeInSpan(minTzStartMillis)) { // First one works, keep it realTz = minTimespan.getValue(); realDateStart = minTzStartDT; } else if (maxTimespan.isTimeInSpan(maxStartMillis)) { // Last one works, keep it realTz = maxTimespan.getValue(); realDateStart = maxTzStartDT; } else { // Something weird is going on here, complain and return GMT System.out.println( "Cant figure out start of date " + date.toString() + ", " + minTimespan + " does not contain " + minTzStartDT + " and " + maxTimespan + " does not contain " + maxTzStartDT); return (date.toDateTimeAtStartOfDay(DateTimeZone.UTC)); } } // System.out.println("Start of date "+date.toString()+", in "+realTz + ": " + realDateStart); return (realDateStart); }
@Override public Timestamp toNonNullValue(DateTime value) { DateTimeZone currentDatabaseZone = databaseZone == null ? ZoneHelper.getDefault() : databaseZone; int adjustment = TimeZone.getDefault().getOffset(value.getMillis()) - currentDatabaseZone.getOffset(null); final Timestamp timestamp = new Timestamp(value.getMillis() - adjustment); return timestamp; }
private boolean isVersionNewer(String version, String oldVersion) { // if we cannot estimate the relation between versions, we accept new records over the old ones. boolean retval = true; DateTime dt = tryDateFormat(version); DateTime dtOld = tryDateFormat(oldVersion); if (dt != null && dtOld != null) { if (dtOld.isAfter(dt.getMillis()) || dtOld.isEqual(dt.getMillis())) { retval = false; } } return retval; }
@Override public Long exec(Tuple input) throws IOException { if (input == null || input.size() < 2 || input.get(0) == null || input.get(1) == null) { return null; } DateTime startDate = (DateTime) input.get(0); DateTime endDate = (DateTime) input.get(1); // Larger date first // Subtraction may overflow return (startDate.getMillis() - endDate.getMillis()) / 60000L; }
/** * Samples a data point from the Cars Per Hour model, using the given timestamp * * @param timestamp Timestamp to simulate traffic data for. Specify in milliseconds since epoch. * Use UTC! * @return Simulated data for Cars Per Hour based on the model * @throws Exception */ public TrafficData sampleCarsPerHourModel(long timestamp) throws Exception { // Verify we have a traffic model for this segment if (carsPerHour == null) { generateModel(); } DateTime time = new DateTime(timestamp, DateTimeZone.UTC); int hour = time.getHourOfDay(); TrafficData traffic = null; // Add cars-per-hour data if (carsPerHour.containsKey(hour)) { // We have traffic data for the hour, sample it. Double sample = carsPerHour.get(hour).sample(1)[0]; if (sample <= 0) { traffic = new TrafficData(fromNode, toNode, time.getMillis() / 1000, "CARS_PER_HOUR", 0.0); } else { traffic = new TrafficData( fromNode, toNode, time.getMillis() / 1000, "CARS_PER_HOUR", (double) Math.round(sample)); } } else { // TODO: See if we have the previous hour and the next hour and interpolate the data if we do // For now, just assume that there is a random number between 0-100 cars, since all // measurements at that hour had the same amount of cars. // NOTE: Even though it says max is 101, it's actually 100, since it's exclusive for the top // bound. traffic = new TrafficData( fromNode, toNode, time.getMillis() / 1000, "CARS_PER_HOUR", (double) ThreadLocalRandom.current().nextInt(0, 101)); } if (traffic != null && traffic.isValid()) { // Traffic has data return traffic; } else { // Traffic didn't have any data throw new Exception( String.format( "No traffic model for the given timestamp: %d (Hour: %d)", time.getMillis(), time.getHourOfDay())); } }
public void testDateRangeQueryTimezone() throws IOException { assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0); long startDate = System.currentTimeMillis(); String query = "{\n" + " \"range\" : {\n" + " \"" + DATE_FIELD_NAME + "\" : {\n" + " \"gte\": \"2012-01-01\",\n" + " \"lte\": \"now\",\n" + " \"time_zone\": \"+01:00\"\n" + " }\n" + " }\n" + "}"; Query parsedQuery = parseQuery(query).toQuery(createShardContext()).rewrite(null); assertThat(parsedQuery, instanceOf(NumericRangeQuery.class)); // Min value was 2012-01-01 (UTC) so we need to remove one hour DateTime min = DateTime.parse("2012-01-01T00:00:00.000+01:00"); // Max value is when we started the test. So it should be some ms from now DateTime max = new DateTime(startDate, DateTimeZone.UTC); assertThat(((NumericRangeQuery) parsedQuery).getMin().longValue(), is(min.getMillis())); // We should not have a big difference here (should be some ms) assertThat( ((NumericRangeQuery) parsedQuery).getMax().longValue() - max.getMillis(), lessThanOrEqualTo(60000L)); query = "{\n" + " \"range\" : {\n" + " \"" + INT_FIELD_NAME + "\" : {\n" + " \"gte\": \"0\",\n" + " \"lte\": \"100\",\n" + " \"time_zone\": \"-01:00\"\n" + " }\n" + " }\n" + "}"; try { parseQuery(query).toQuery(createShardContext()); fail("A Range Query on a numeric field with a TimeZone should raise a ParsingException"); } catch (QueryShardException e) { // We expect it } }
public void testDateRangeBoundaries() throws IOException { assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0); String query = "{\n" + " \"range\" : {\n" + " \"" + DATE_FIELD_NAME + "\" : {\n" + " \"gte\": \"2014-11-05||/M\",\n" + " \"lte\": \"2014-12-08||/d\"\n" + " }\n" + " }\n" + "}\n"; Query parsedQuery = parseQuery(query).toQuery(createShardContext()).rewrite(null); assertThat(parsedQuery, instanceOf(NumericRangeQuery.class)); NumericRangeQuery rangeQuery = (NumericRangeQuery) parsedQuery; DateTime min = DateTime.parse("2014-11-01T00:00:00.000+00"); assertThat(rangeQuery.getMin().longValue(), is(min.getMillis())); assertTrue(rangeQuery.includesMin()); DateTime max = DateTime.parse("2014-12-08T23:59:59.999+00"); assertThat(rangeQuery.getMax().longValue(), is(max.getMillis())); assertTrue(rangeQuery.includesMax()); query = "{\n" + " \"range\" : {\n" + " \"" + DATE_FIELD_NAME + "\" : {\n" + " \"gt\": \"2014-11-05||/M\",\n" + " \"lt\": \"2014-12-08||/d\"\n" + " }\n" + " }\n" + "}"; parsedQuery = parseQuery(query).toQuery(createShardContext()).rewrite(null); assertThat(parsedQuery, instanceOf(NumericRangeQuery.class)); rangeQuery = (NumericRangeQuery) parsedQuery; min = DateTime.parse("2014-11-30T23:59:59.999+00"); assertThat(rangeQuery.getMin().longValue(), is(min.getMillis())); assertFalse(rangeQuery.includesMin()); max = DateTime.parse("2014-12-08T00:00:00.000+00"); assertThat(rangeQuery.getMax().longValue(), is(max.getMillis())); assertFalse(rangeQuery.includesMax()); }
@Test public void testWithConversion() throws IOException { DateTime today = new DateTime(); Map<String, Object> resultMap = (Map<String, Object>) ControllerUtil.sendAndReceive( controller, "remoteProviderSimple", "method14", a( ISODateTimeFormat.dateTime().print(today), "normalParameter", ISODateTimeFormat.date().print(today), "99.9%"), Map.class); assertThat(resultMap.get("endDate")).isEqualTo(today.getMillis()); ObjectMapper mapper = new ObjectMapper(); List<Object> expectedValue = mapper.readValue(mapper.writeValueAsString(today.toLocalDate()), List.class); Object actualValue = resultMap.get("jodaLocalDate"); assertThat((List<Object>) resultMap.get("jodaLocalDate")).isEqualTo(expectedValue); assertThat(resultMap.get("percent")).isEqualTo(0.999); assertThat(resultMap.get("normalParameter")).isEqualTo("normalParameter"); assertThat(resultMap.get("remoteAddr")).isEqualTo("127.0.0.1"); }
private void setAttachmentInfo( String volumeId, JsonNode attachment, DateTime detachTime, Resource resource) { String instanceId = null; if (attachment != null) { boolean deleteOnTermination = attachment.get(DELETE_ON_TERMINATION).getBooleanValue(); if (deleteOnTermination) { LOGGER.info( String.format("Volume %s had set the deleteOnTermination flag as true", volumeId)); } resource.setAdditionalField(DELETE_ON_TERMINATION, String.valueOf(deleteOnTermination)); instanceId = attachment.get("instanceId").getTextValue(); } // The subclass can customize the way to get the owner for a volume String owner = getOwnerEmailForResource(resource); if (owner == null && instanceId != null) { owner = instanceToOwner.get(instanceId); } resource.setOwnerEmail(owner); String metaTag = makeMetaTag(instanceId, owner, detachTime); LOGGER.info(String.format("Setting Janitor Metatag as %s for volume %s", metaTag, volumeId)); resource.setTag(JanitorMonkey.JANITOR_META_TAG, metaTag); LOGGER.info(String.format("The last detach time of volume %s is %s", volumeId, detachTime)); resource.setAdditionalField(DETACH_TIME, String.valueOf(detachTime.getMillis())); }
/** * Will determine when was the last entry point (pull from CloudStack), or even if there was any * * @return date object of the last commit, or epoch if there was none */ private DateTime whenWasLastPull() { DateTime last = new InfluxDBClient().getLastPull(); logger.trace("Getting the last pull date " + last.toString()); // get date specified by admin String date = settings.getCloudStackImportFrom(); if (date != null && !date.isEmpty()) { try { logger.trace("Admin provided us with import date preference " + date); DateTime selection = Time.getDateForTime(date); // if we are first time starting and having Epoch, change it to admin's selection // otherwise skip admin's selection and continue from the last DB entry time if (last.getMillis() == 0) { logger.debug("Setting first import date as configuration file dictates."); last = selection; } } catch (Exception ignored) { // ignoring configuration preference, as admin didn't provide correct format logger.debug("Import date selection for CloudStack ignored - use yyyy-MM-dd format"); } } return last; }
public static void testLocale() { System.out.println("演示Locale"); DateTime dateTime = new DateTime().withZone(DateTimeZone.UTC); // 打印中文与英文下不同长度的日期格式串 System.out.println("S: " + DateUtils.formatDateTime(dateTime, "SS", "zh")); System.out.println("M: " + DateUtils.formatDateTime(dateTime, "MM", "zh")); System.out.println("L: " + DateUtils.formatDateTime(dateTime, "LL", "zh")); System.out.println("XL: " + DateUtils.formatDateTime(dateTime, "FF", "zh")); System.out.println(""); System.out.println("S: " + DateUtils.formatDateTime(dateTime, "SS", "en")); System.out.println("M: " + DateUtils.formatDateTime(dateTime, "MM", "en")); System.out.println("L: " + DateUtils.formatDateTime(dateTime, "LL", "en")); System.out.println("XL: " + DateUtils.formatDateTime(dateTime, "FF", "en")); System.out.println(""); System.out.println(""); // 直接打印TimeStamp, 日期是M,时间是L DateTimeFormatter formatter = DateTimeFormat.forStyle("ML").withLocale(new Locale("zh")).withZone(DateTimeZone.UTC); System.out.println("ML Mix: " + formatter.print(dateTime.getMillis())); // 只打印日期不打印时间 System.out.println("Date only :" + DateUtils.formatDateTime(dateTime, "M-", "zh")); }
// TODO: Rename and change types and number of parameters public static TimePickerFragment newInstance(DateTime time) { TimePickerFragment fragment = new TimePickerFragment(); Bundle args = new Bundle(); args.putLong(ARG_TIME, time.getMillis()); fragment.setArguments(args); return fragment; }
protected LogoutRequest buildLogoutRequest(String user, String sessionIdx) throws SSOAgentException { LogoutRequest logoutReq = new LogoutRequestBuilder().buildObject(); logoutReq.setID(SSOAgentUtils.createID()); logoutReq.setDestination(ssoAgentConfig.getSAML2().getIdPURL()); DateTime issueInstant = new DateTime(); logoutReq.setIssueInstant(issueInstant); logoutReq.setNotOnOrAfter(new DateTime(issueInstant.getMillis() + 5 * 60 * 1000)); IssuerBuilder issuerBuilder = new IssuerBuilder(); Issuer issuer = issuerBuilder.buildObject(); issuer.setValue(ssoAgentConfig.getSAML2().getSPEntityId()); logoutReq.setIssuer(issuer); NameID nameId = new NameIDBuilder().buildObject(); nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:entity"); nameId.setValue(user); logoutReq.setNameID(nameId); SessionIndex sessionIndex = new SessionIndexBuilder().buildObject(); sessionIndex.setSessionIndex(sessionIdx); logoutReq.getSessionIndexes().add(sessionIndex); logoutReq.setReason("Single Logout"); return logoutReq; }
public Response buildResponse(SAMLSSOAuthnReqDTO authReqDTO, String sessionId) throws IdentityException { if (log.isDebugEnabled()) { log.debug( "Building SAML Response for the consumer '" + authReqDTO.getAssertionConsumerURL() + "'"); } Response response = new org.opensaml.saml2.core.impl.ResponseBuilder().buildObject(); response.setIssuer(SAMLSSOUtil.getIssuer()); response.setID(SAMLSSOUtil.createID()); response.setInResponseTo(authReqDTO.getId()); response.setDestination(authReqDTO.getAssertionConsumerURL()); response.setStatus(buildStatus(SAMLSSOConstants.StatusCodes.SUCCESS_CODE, null)); response.setVersion(SAMLVersion.VERSION_20); DateTime issueInstant = new DateTime(); DateTime notOnOrAfter = new DateTime( issueInstant.getMillis() + SAMLSSOUtil.getSAMLResponseValidityPeriod() * 60 * 1000); response.setIssueInstant(issueInstant); Assertion assertion = buildSAMLAssertion(authReqDTO, notOnOrAfter, sessionId); response.getAssertions().add(assertion); if (authReqDTO.isDoSignResponse()) { SAMLSSOUtil.setSignature( response, XMLSignature.ALGO_ID_SIGNATURE_RSA, new SignKeyDataHolder(authReqDTO.getUsername())); } return response; }
private void addDateTimeInUTC(String name, DateTime time) { long utctime = time.getZone().convertLocalToUTC(time.getMillis(), true); Calendar cal = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTimeInMillis(utctime); DateFormat format = new SimpleDateFormat(UTC_TIMEFORMAT); inputDocument.addField(name, format.format(cal.getTime())); }
@Override public ContentValues getContentValues() { ContentValues values = new ContentValues(); values.put(C_TIME, time); values.put(C_SCORE_DATE, scoreDate != null ? scoreDate.getMillis() : null); return values; }
@Test public void testMergeDay() { Result<SearchResultValue> r1 = new Result<SearchResultValue>( currTime, new SearchResultValue(ImmutableList.<SearchHit>of(new SearchHit("blah", "foo")))); Result<SearchResultValue> r2 = new Result<SearchResultValue>( currTime, new SearchResultValue(ImmutableList.<SearchHit>of(new SearchHit("blah2", "foo2")))); Result<SearchResultValue> expected = new Result<SearchResultValue>( new DateTime(QueryGranularity.DAY.truncate(currTime.getMillis())), new SearchResultValue( ImmutableList.<SearchHit>of( new SearchHit("blah", "foo"), new SearchHit("blah2", "foo2")))); Result<SearchResultValue> actual = new SearchBinaryFn( new LexicographicSearchSortSpec(), QueryGranularity.DAY, Integer.MAX_VALUE) .apply(r1, r2); Assert.assertEquals(expected.getTimestamp(), actual.getTimestamp()); assertSearchMergeResult(expected.getValue(), actual.getValue()); }
/** * Prints out information about the operating environment. This includes the operating system * name, version and architecture, the JDK version, available CPU cores, memory currently used by * the JVM process, the maximum amount of memory that may be used by the JVM, and the current time * in UTC. * * @param out output writer to which information will be written */ protected void printOperatingEnvironmentInformation(PrintWriter out) { Runtime runtime = Runtime.getRuntime(); DateTime now = new DateTime(ISOChronology.getInstanceUTC()); out.println("### Operating Environment Information"); out.println("operating_system: " + System.getProperty("os.name")); out.println("operating_system_version: " + System.getProperty("os.version")); out.println("operating_system_architecture: " + System.getProperty("os.arch")); out.println("jdk_version: " + System.getProperty("java.version")); out.println("available_cores: " + runtime.availableProcessors()); out.println("used_memory: " + runtime.totalMemory() / 1048576 + "MB"); out.println("maximum_memory: " + runtime.maxMemory() / 1048576 + "MB"); out.println("start_time: " + startTime.toString(dateFormat)); out.println("current_time: " + now.toString(dateFormat)); out.println("uptime: " + (now.getMillis() - startTime.getMillis()) + "ms"); }
public void testChangesSinceStatic() { DateTime ifModifiedSince = new DateTime(); BaseListOptions options = changesSince(ifModifiedSince); assertEquals( ImmutableList.of(ifModifiedSince.getMillis() / 1000 + ""), options.buildQueryParameters().get("changes-since")); }