public void testRewriteDateToMatchAll() throws IOException { String fieldName = randomAsciiOfLengthBetween(1, 20); RangeQueryBuilder query = new RangeQueryBuilder(fieldName) { @Override protected MappedFieldType.Relation getRelation(QueryRewriteContext queryRewriteContext) throws IOException { return Relation.WITHIN; } }; DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); query.from(queryFromValue); query.to(queryToValue); QueryShardContext queryShardContext = createShardContext(); QueryBuilder rewritten = query.rewrite(queryShardContext); assertThat(rewritten, instanceOf(RangeQueryBuilder.class)); RangeQueryBuilder rewrittenRange = (RangeQueryBuilder) rewritten; assertThat(rewrittenRange.fieldName(), equalTo(fieldName)); assertThat(rewrittenRange.from(), equalTo(null)); assertThat(rewrittenRange.to(), equalTo(null)); }
public void testRewriteDateToMatchAllWithTimezoneAndFormat() throws IOException { String fieldName = randomAsciiOfLengthBetween(1, 20); RangeQueryBuilder query = new RangeQueryBuilder(fieldName) { @Override protected MappedFieldType.Relation getRelation(QueryRewriteContext queryRewriteContext) throws IOException { return Relation.WITHIN; } }; DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); query.from(queryFromValue); query.to(queryToValue); query.timeZone(randomFrom(DateTimeZone.getAvailableIDs())); query.format("yyyy-MM-dd"); QueryShardContext queryShardContext = createShardContext(); QueryBuilder rewritten = query.rewrite(queryShardContext); assertThat(rewritten, instanceOf(RangeQueryBuilder.class)); RangeQueryBuilder rewrittenRange = (RangeQueryBuilder) rewritten; assertThat(rewrittenRange.fieldName(), equalTo(fieldName)); assertThat(rewrittenRange.from(), equalTo(null)); assertThat(rewrittenRange.to(), equalTo(null)); assertThat(rewrittenRange.timeZone(), equalTo(null)); assertThat(rewrittenRange.format(), equalTo(null)); }
public void testRewriteDateToMatchNone() throws IOException { String fieldName = randomAsciiOfLengthBetween(1, 20); RangeQueryBuilder query = new RangeQueryBuilder(fieldName) { @Override protected MappedFieldType.Relation getRelation(QueryRewriteContext queryRewriteContext) throws IOException { return Relation.DISJOINT; } }; DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); query.from(queryFromValue); query.to(queryToValue); QueryShardContext queryShardContext = createShardContext(); QueryBuilder rewritten = query.rewrite(queryShardContext); assertThat(rewritten, instanceOf(MatchNoneQueryBuilder.class)); }
public void testRewriteDateToSame() throws IOException { String fieldName = randomAsciiOfLengthBetween(1, 20); RangeQueryBuilder query = new RangeQueryBuilder(fieldName) { @Override protected MappedFieldType.Relation getRelation(QueryRewriteContext queryRewriteContext) throws IOException { return Relation.INTERSECTS; } }; DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC()); query.from(queryFromValue); query.to(queryToValue); QueryShardContext queryShardContext = createShardContext(); QueryBuilder rewritten = query.rewrite(queryShardContext); assertThat(rewritten, sameInstance(query)); }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { Assertion assertion = (Assertion) samlObject; if (Assertion.ID_ATTRIB_NAME.equals(attribute.getLocalName())) { assertion.setID(attribute.getValue()); } else if (Assertion.ISSUER_ATTRIB_NAME.equals(attribute.getLocalName())) { assertion.setIssuer(attribute.getValue()); } else if (Assertion.ISSUEINSTANT_ATTRIB_NAME.equals(attribute.getLocalName()) && !DatatypeHelper.isEmpty(attribute.getValue())) { assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (Assertion.MINORVERSION_ATTRIB_NAME.equals(attribute.getLocalName())) { if (attribute.getValue().equals("0")) { assertion.setVersion(SAMLVersion.VERSION_10); } else { assertion.setVersion(SAMLVersion.VERSION_11); } } else { super.processAttribute(samlObject, attribute); } }
/** {@inheritDoc} */ protected byte[] fetchMetadata() throws MetadataProviderException { try { validateMetadataFile(metadataFile); DateTime metadataUpdateTime = new DateTime(metadataFile.lastModified(), ISOChronology.getInstanceUTC()); if (getLastRefresh() == null || getLastUpdate() == null || metadataUpdateTime.isAfter(getLastRefresh())) { return inputstreamToByteArray(new FileInputStream(metadataFile)); } return null; } catch (IOException e) { String errMsg = "Unable to read metadata file " + metadataFile.getAbsolutePath(); log.error(errMsg, e); throw new MetadataProviderException(errMsg, e); } }
/** {@inheritDoc} */ public void doFilter(XMLObject metadata) throws FilterException { DateTime validUntil = getValidUntil(metadata); if (validUntil == null) { throw new FilterException("Metadata did not include a validUntil attribute"); } DateTime now = new DateTime(ISOChronology.getInstanceUTC()); if (maxValidityInterval > 0 && validUntil.isAfter(now)) { long validityInterval = validUntil.getMillis() - now.getMillis(); if (validityInterval > maxValidityInterval) { throw new FilterException("Metadata's validity interval, " + validityInterval + "ms, is larger than is allowed, " + maxValidityInterval + "ms."); } } }
/** * Computes the delay until the next refresh time based on the current metadata's expiration time and the refresh * interval floor. * * @param expectedExpiration the time when the metadata is expected to expire and need refreshing * * @return delay, in milliseconds, until the next refresh time */ protected long computeNextRefreshDelay(DateTime expectedExpiration) { long now = new DateTime(ISOChronology.getInstanceUTC()).getMillis(); long expireInstant = 0; if (expectedExpiration != null) { expireInstant = expectedExpiration.toDateTime(ISOChronology.getInstanceUTC()).getMillis(); } long refreshDelay = (long) ((expireInstant - now) * getRefreshDelayFactor()); // if the expiration time was null or the calculated refresh delay was less than the floor // use the floor if (refreshDelay < getMinRefreshDelay()) { refreshDelay = getMinRefreshDelay(); } return refreshDelay; }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { AffiliationDescriptor descriptor = (AffiliationDescriptor) samlObject; if (attribute.getLocalName().equals(AffiliationDescriptor.OWNER_ID_ATTRIB_NAME)) { descriptor.setOwnerID(attribute.getValue()); } else if (attribute.getLocalName().equals(AffiliationDescriptor.ID_ATTRIB_NAME)) { descriptor.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { descriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { descriptor.setCacheDuration(XMLHelper.durationToLong(attribute.getValue())); } else { QName attribQName = XMLHelper.getNodeQName(attribute); if (attribute.isId()) { descriptor.getUnknownAttributes().registerID(attribQName); } descriptor.getUnknownAttributes().put(attribQName, attribute.getValue()); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { EntityDescriptor entityDescriptor = (EntityDescriptor) samlObject; if (attribute.getLocalName().equals(EntityDescriptor.ENTITY_ID_ATTRIB_NAME)) { entityDescriptor.setEntityID(attribute.getValue()); } else if (attribute.getLocalName().equals(EntityDescriptor.ID_ATTRIB_NAME)) { entityDescriptor.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { entityDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { entityDescriptor.setCacheDuration(XMLHelper.durationToLong(attribute.getValue())); } else { QName attribQName = XMLHelper.getNodeQName(attribute); if (attribute.isId()) { entityDescriptor.getUnknownAttributes().registerID(attribQName); } entityDescriptor.getUnknownAttributes().put(attribQName, attribute.getValue()); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) samlObject; if (attribute.getLocalName().equals(EntitiesDescriptor.ID_ATTRIB_NAME)) { entitiesDescriptor.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else if (attribute.getLocalName().equals(TimeBoundSAMLObject.VALID_UNTIL_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { entitiesDescriptor.setValidUntil(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(CacheableSAMLObject.CACHE_DURATION_ATTRIB_NAME)) { entitiesDescriptor.setCacheDuration(new Long(XMLHelper.durationToLong(attribute.getValue()))); } else if (attribute.getLocalName().equals(EntitiesDescriptor.NAME_ATTRIB_NAME)) { entitiesDescriptor.setName(attribute.getValue()); } else { super.processAttribute(samlObject, attribute); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { Assertion assertion = (Assertion) samlObject; if (attribute.getLocalName().equals(Assertion.VERSION_ATTRIB_NAME)) { assertion.setVersion(SAMLVersion.valueOf(attribute.getValue())); } else if (attribute.getLocalName().equals(Assertion.ISSUE_INSTANT_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { assertion.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(Assertion.ID_ATTRIB_NAME)) { assertion.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else { super.processAttribute(samlObject, attribute); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { RequestAbstractType req = (RequestAbstractType) samlObject; if (attribute.getLocalName().equals(RequestAbstractType.VERSION_ATTRIB_NAME)) { req.setVersion(SAMLVersion.valueOf(attribute.getValue())); } else if (attribute.getLocalName().equals(RequestAbstractType.ID_ATTRIB_NAME)) { req.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else if (attribute.getLocalName().equals(RequestAbstractType.ISSUE_INSTANT_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { req.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(RequestAbstractType.DESTINATION_ATTRIB_NAME)) { req.setDestination(attribute.getValue()); } else if (attribute.getLocalName().equals(RequestAbstractType.CONSENT_ATTRIB_NAME)) { req.setConsent(attribute.getValue()); } else { super.processAttribute(samlObject, attribute); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { LogoutRequest req = (LogoutRequest) samlObject; if (attribute.getLocalName().equals(LogoutRequest.REASON_ATTRIB_NAME)) { req.setReason(attribute.getValue()); } else if (attribute.getLocalName().equals(LogoutRequest.NOT_ON_OR_AFTER_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { req.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else { super.processAttribute(samlObject, attribute); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { SubjectConfirmationData subjectCD = (SubjectConfirmationData) samlObject; if (attribute.getLocalName().equals(SubjectConfirmationData.NOT_BEFORE_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { subjectCD.setNotBefore(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(SubjectConfirmationData.NOT_ON_OR_AFTER_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { subjectCD.setNotOnOrAfter(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(SubjectConfirmationData.RECIPIENT_ATTRIB_NAME)) { subjectCD.setRecipient(attribute.getValue()); } else if (attribute.getLocalName().equals(SubjectConfirmationData.IN_RESPONSE_TO_ATTRIB_NAME)) { subjectCD.setInResponseTo(attribute.getValue()); } else if (attribute.getLocalName().equals(SubjectConfirmationData.ADDRESS_ATTRIB_NAME)) { subjectCD.setAddress(attribute.getValue()); } else { QName attribQName = XMLHelper.getNodeQName(attribute); if (attribute.isId()) { subjectCD.getUnknownAttributes().registerID(attribQName); } subjectCD.getUnknownAttributes().put(attribQName, attribute.getValue()); } }
/** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { StatusResponseType sr = (StatusResponseType) samlObject; if (attribute.getLocalName().equals(StatusResponseType.VERSION_ATTRIB_NAME)) { sr.setVersion(SAMLVersion.valueOf(attribute.getValue())); } else if (attribute.getLocalName().equals(StatusResponseType.ID_ATTRIB_NAME)) { sr.setID(attribute.getValue()); attribute.getOwnerElement().setIdAttributeNode(attribute, true); } else if (attribute.getLocalName().equals(StatusResponseType.IN_RESPONSE_TO_ATTRIB_NAME)) { sr.setInResponseTo(attribute.getValue()); } else if (attribute.getLocalName().equals(StatusResponseType.ISSUE_INSTANT_ATTRIB_NAME) && !DatatypeHelper.isEmpty(attribute.getValue())) { sr.setIssueInstant(new DateTime(attribute.getValue(), ISOChronology.getInstanceUTC())); } else if (attribute.getLocalName().equals(StatusResponseType.DESTINATION_ATTRIB_NAME)) { sr.setDestination(attribute.getValue()); } else if (attribute.getLocalName().equals(StatusResponseType.CONSENT_ATTRIB_NAME)) { sr.setConsent(attribute.getValue()); } else { super.processAttribute(samlObject, attribute); } }
@Test public void testDateAggFunction() throws Exception{ String query = new String("SELECT max(cast(HIRE_DATE as date)) as MAX_DATE, min(cast(HIRE_DATE as date)) as MIN_DATE" + " FROM `employee.json`"); String t = new Date(ISOChronology.getInstance().getDateTimeMillis(1998, 1, 1, 0)).toString(); String t1 = new Date(ISOChronology.getInstance().getDateTimeMillis(1993, 5, 1, 0)).toString(); //String t = new Date(1998, 1, 1).toString(); //String t1 = new Date(1993, 5, 1).toString(); String result = String.format("MAX_DATE="+ t + "; " + "MIN_DATE=" + t1 + "\n"); JdbcAssert.withFull("cp") .sql(query) .returns(result); }
@Test public void testParseSingleLineNoLineEnding() throws ParsingException, IOException { final Record record = parseRecord("GraphitePlaintextParserTest/testParseSingleLineNoLineEnding"); Assert.assertNotNull(record); Assert.assertNotNull(record.getAnnotations()); Assert.assertEquals(0, record.getAnnotations().size()); Assert.assertNotNull(record.getDimensions()); Assert.assertEquals(0, record.getDimensions().size()); final Map<String, ? extends Metric> map = record.getMetrics(); Assert.assertEquals(1, map.size()); final Metric metric = map.get("foo.bar"); final List<Quantity> vals = metric.getValues(); Assert.assertEquals(1, vals.size()); Assert.assertEquals(1.23d, vals.get(0).getValue(), 0.001); Assert.assertFalse(vals.get(0).getUnit().isPresent()); Assert.assertEquals(MetricType.GAUGE, metric.getType()); Assert.assertEquals(new DateTime((long) (1458229140 * 1000d), ISOChronology.getInstanceUTC()), record.getTime()); }
@Test public void testParseSingleLineWithLineEnding() throws ParsingException, IOException { final Record record = parseRecord("GraphitePlaintextParserTest/testParseSingleLineWithLineEnding"); Assert.assertNotNull(record); Assert.assertNotNull(record.getAnnotations()); Assert.assertEquals(0, record.getAnnotations().size()); Assert.assertNotNull(record.getDimensions()); Assert.assertEquals(0, record.getDimensions().size()); final Map<String, ? extends Metric> map = record.getMetrics(); Assert.assertEquals(1, map.size()); final Metric metric = map.get("foo.bar"); final List<Quantity> vals = metric.getValues(); Assert.assertEquals(1, vals.size()); Assert.assertEquals(1.23d, vals.get(0).getValue(), 0.001); Assert.assertFalse(vals.get(0).getUnit().isPresent()); Assert.assertEquals(MetricType.GAUGE, metric.getType()); Assert.assertEquals(new DateTime((long) (1458229140 * 1000d), ISOChronology.getInstanceUTC()), record.getTime()); }
/** * Converts a time value received via the Dataflow API into the corresponding * {@link Instant}. * @return the parsed time, or null if a parse error occurs */ @Nullable public static Instant fromCloudTime(String time) { Matcher matcher = TIME_PATTERN.matcher(time); if (!matcher.matches()) { return null; } int year = Integer.valueOf(matcher.group(1)); int month = Integer.valueOf(matcher.group(2)); int day = Integer.valueOf(matcher.group(3)); int hour = Integer.valueOf(matcher.group(4)); int minute = Integer.valueOf(matcher.group(5)); int second = Integer.valueOf(matcher.group(6)); int millis = computeMillis(matcher.group(7)); return new DateTime(year, month, day, hour, minute, second, millis, ISOChronology.getInstanceUTC()).toInstant(); }
/** * Normalise date in string format * * @param original string * @return normalised string */ public static String normaliseString(String original) { try { DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm") .withLocale(Locale.ROOT) .withChronology(ISOChronology.getInstanceUTC()); // and now parse it DateTime dt = formatter.parseDateTime(original); return dt.toString(); } catch (Exception ignored) { return original; } }
/** * Creates a new instance representing the number of complete standard length units * in the specified period. * <p> * This factory method converts all fields from the period to hours using standardised * durations for each field. Only those fields which have a precise duration in * the ISO UTC chronology can be converted. * <ul> * <li>One week consists of 7 days. * <li>One day consists of 24 hours. * <li>One hour consists of 60 minutes. * <li>One minute consists of 60 seconds. * <li>One second consists of 1000 milliseconds. * </ul> * Months and Years are imprecise and periods containing these values cannot be converted. * * @param period the period to get the number of hours from, must not be null * @param millisPerUnit the number of milliseconds in one standard unit of this period * @throws IllegalArgumentException if the period contains imprecise duration values */ protected static int standardPeriodIn(ReadablePeriod period, long millisPerUnit) { if (period == null) { return 0; } Chronology iso = ISOChronology.getInstanceUTC(); long duration = 0L; for (int i = 0; i < period.size(); i++) { int value = period.getValue(i); if (value != 0) { DurationField field = period.getFieldType(i).getField(iso); if (field.isPrecise() == false) { throw new IllegalArgumentException( "Cannot convert period to duration as " + field.getName() + " is not precise in the period " + period); } duration = FieldUtils.safeAdd(duration, FieldUtils.safeMultiply(field.getUnitMillis(), value)); } } return FieldUtils.safeToInt(duration / millisPerUnit); }
/** * @param standardOffset standard offset just before instant */ public long setInstant(int year, int standardOffset, int saveMillis) { int offset; if (iMode == 'w') { offset = standardOffset + saveMillis; } else if (iMode == 's') { offset = standardOffset; } else { offset = 0; } Chronology chrono = ISOChronology.getInstanceUTC(); long millis = chrono.year().set(0, year); millis = chrono.monthOfYear().set(millis, iMonthOfYear); millis = chrono.millisOfDay().set(millis, iMillisOfDay); millis = setDayOfMonth(chrono, millis); if (iDayOfWeek != 0) { millis = setDayOfWeek(chrono, millis); } // Convert from local time to UTC. return millis - offset; }
/** * Gets the chronology, which is the GJChronology if a GregorianCalendar is used, * BuddhistChronology if a BuddhistCalendar is used or ISOChronology otherwise. * The time zone specified is used in preference to that on the calendar. * * @param object the Calendar to convert, must not be null * @param zone the specified zone to use, null means default zone * @return the chronology, never null * @throws NullPointerException if the object is null * @throws ClassCastException if the object is an invalid type */ public Chronology getChronology(Object object, DateTimeZone zone) { if (object.getClass().getName().endsWith(".BuddhistCalendar")) { return BuddhistChronology.getInstance(zone); } else if (object instanceof GregorianCalendar) { GregorianCalendar gc = (GregorianCalendar) object; long cutover = gc.getGregorianChange().getTime(); if (cutover == Long.MIN_VALUE) { return GregorianChronology.getInstance(zone); } else if (cutover == Long.MAX_VALUE) { return JulianChronology.getInstance(zone); } else { return GJChronology.getInstance(zone, cutover, 4); } } else { return ISOChronology.getInstance(zone); } }
public static long parseInstant(String input, long now) { if (input.charAt(0) == '+') { return now + Long.parseLong(input.substring(1)); } if (input.charAt(0) == '-') { return now - Long.parseLong(input.substring(1)); } // try to parse just milliseconds try { return Long.parseLong(input); } catch (IllegalArgumentException e) { // pass-through } final Chronology chrono = ISOChronology.getInstanceUTC(); if (input.indexOf('/') >= 0) { return parseFullInstant(input, chrono); } return parseTodayInstant(input, chrono, now); }
protected Interval buildMidnightAdjustedInterval(LocalDateTime now) { if(start != null && end != null) { LocalDateTime earliestStartDateTime = new LocalDate(now).toLocalDateTime(start.toLocalTime()); LocalDateTime latestEndDateTime = new LocalDate(now).toLocalDateTime(end.toLocalTime()); if(isOverMidnight(earliestStartDateTime, latestEndDateTime)) { if(now.toLocalTime().isAfter(start.toLocalTime())) { // before midnight latestEndDateTime = latestEndDateTime.plusHours(24); } else if(now.toLocalTime().isBefore(end.toLocalTime())){ // after midnight, before end earliestStartDateTime = earliestStartDateTime.minusHours(24); } else { // after midnight, after end latestEndDateTime = latestEndDateTime.plusHours(24); } } return new Interval(earliestStartDateTime.toDateTime(), latestEndDateTime.toDateTime()).withChronology(ISOChronology.getInstance()); } return null; }
@Override public void appendLong(long value) { try { if (DATE.equals(columnTypes.get(field))) { // convert to midnight in default time zone long utcMillis = TimeUnit.DAYS.toMillis(value); long localMillis = ISOChronology.getInstanceUTC().getZone().getMillisKeepLocal(DateTimeZone.getDefault(), utcMillis); statement.setDate(next(), new Date(localMillis)); } else { statement.setLong(next(), value); } } catch (SQLException e) { throw new PrestoException(JDBC_ERROR, e); } }
private static DateTimeField getDateField(ISOChronology chronology, Slice unit) { String unitString = unit.toStringUtf8().toLowerCase(ENGLISH); switch (unitString) { case "day": return chronology.dayOfMonth(); case "week": return chronology.weekOfWeekyear(); case "month": return chronology.monthOfYear(); case "quarter": return QUARTER_OF_YEAR.getField(chronology); case "year": return chronology.year(); } throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "'" + unitString + "' is not a valid DATE field"); }
private static DateTimeField getTimestampField(ISOChronology chronology, Slice unit) { String unitString = unit.toStringUtf8().toLowerCase(ENGLISH); switch (unitString) { case "millisecond": return chronology.millisOfSecond(); case "second": return chronology.secondOfMinute(); case "minute": return chronology.minuteOfHour(); case "hour": return chronology.hourOfDay(); case "day": return chronology.dayOfMonth(); case "week": return chronology.weekOfWeekyear(); case "month": return chronology.monthOfYear(); case "quarter": return QUARTER_OF_YEAR.getField(chronology); case "year": return chronology.year(); } throw new PrestoException(INVALID_FUNCTION_ARGUMENT, "'" + unitString + "' is not a valid Timestamp field"); }
public void testConstructor_long_Chronology2() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, ISOChronology.getInstanceUTC()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(4, test.getDays()); assertEquals(5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); }
public void testConstructor_long_PeriodType_Chronology1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; Period test = new Period(length, PeriodType.time().withMillisRemoved(), ISOChronology.getInstance()); assertEquals(PeriodType.time().withMillisRemoved(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(0, test.getMillis()); }
public void testToDateTime_DateTimeZone() { Instant test = new Instant(TEST_TIME1); DateTime result = test.toDateTime(LONDON); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(LONDON), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toDateTime(PARIS); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(PARIS), result.getChronology()); test = new Instant(TEST_TIME1); result = test.toDateTime((DateTimeZone) null); assertEquals(test.getMillis(), result.getMillis()); assertEquals(ISOChronology.getInstance(), result.getChronology()); }
public void testGetInstantChronology_RI() { DateTime dt = new DateTime(123L, BuddhistChronology.getInstance()); assertEquals(BuddhistChronology.getInstance(), DateTimeUtils.getInstantChronology(dt)); Instant i = new Instant(123L); assertEquals(ISOChronology.getInstanceUTC(), DateTimeUtils.getInstantChronology(i)); AbstractInstant ai = new AbstractInstant() { public long getMillis() { return 0L; } public Chronology getChronology() { return null; // testing for this } }; assertEquals(ISOChronology.getInstance(), DateTimeUtils.getInstantChronology(ai)); assertEquals(ISOChronology.getInstance(), DateTimeUtils.getInstantChronology(null)); }
public void testConstructor_long_Chronology1() throws Throwable { long length = 4 * DateTimeConstants.MILLIS_PER_DAY + 5 * DateTimeConstants.MILLIS_PER_HOUR + 6 * DateTimeConstants.MILLIS_PER_MINUTE + 7 * DateTimeConstants.MILLIS_PER_SECOND + 8; MutablePeriod test = new MutablePeriod(length, ISOChronology.getInstance()); assertEquals(PeriodType.standard(), test.getPeriodType()); assertEquals(0, test.getYears()); assertEquals(0, test.getMonths()); assertEquals(0, test.getWeeks()); assertEquals(0, test.getDays()); assertEquals((4 * 24) + 5, test.getHours()); assertEquals(6, test.getMinutes()); assertEquals(7, test.getSeconds()); assertEquals(8, test.getMillis()); }
/** * Refreshes the metadata from its source. * * @throws ResolverException thrown is there is a problem retrieving and processing the metadata */ public synchronized void refresh() throws ResolverException { final DateTime now = new DateTime(ISOChronology.getInstanceUTC()); final String mdId = getMetadataIdentifier(); long refreshDelay = 0; log.debug("Beginning refresh of metadata from '{}'", mdId); try { byte[] mdBytes = fetchMetadata(); if (mdBytes == null) { log.debug("Metadata from '{}' has not changed since last refresh", mdId); } else { log.debug("Processing new metadata from '{}'", mdId); final Value information = parse(mdBytes); final Key id = getKey(information); log.info("Parsed entity information for {}", id); final JsonBackingStore newBackingStore = new JsonBackingStore(); List<Value> allInformation = new ArrayList<>(); allInformation.add(information); newBackingStore.getIndexedInformation().put(id, allInformation); newBackingStore.getOrderedInformation().add(information); setBackingStore(newBackingStore); lastUpdate = now; } } catch (Throwable t) { log.error("Error occurred while attempting to refresh metadata from '" + mdId + "'", t); refreshDelay = minRefreshDelay; if (t instanceof Exception) { throw new ResolverException((Exception) t); } else { throw new ResolverException(String.format("Saw an error of type '%s' with message '%s'", t.getClass().getName(), t.getMessage())); } } finally { scheduleNextRefresh(refreshDelay); lastRefresh = now; } }
/** * Schedules the next refresh. If the given delay is 0, then {@link maxRefreshDelay} is used. * @param delay The delay before the next refresh. */ protected void scheduleNextRefresh(final long delay) { refreshMetadataTask = new RefreshMetadataTask(); long refreshDelay = delay; if (delay == 0) { refreshDelay = maxRefreshDelay; } nextRefresh = new DateTime(ISOChronology.getInstanceUTC()).plus(refreshDelay); final long nextRefreshDelay = nextRefresh.getMillis() - System.currentTimeMillis(); taskTimer.schedule(refreshMetadataTask, nextRefreshDelay); log.info("Next refresh cycle for metadata provider '{}' will occur on '{}' ('{}' local time)", new Object[] {getMetadataIdentifier(), nextRefresh, nextRefresh.toDateTime(DateTimeZone.getDefault()),}); }
public void testHighlightQueryRewriteDatesWithNow() throws Exception { assertAcked(client().admin().indices().prepareCreate("index-1").addMapping("type", "d", "type=date", "field", "type=text,store=true,term_vector=with_positions_offsets") .setSettings("index.number_of_replicas", 0, "index.number_of_shards", 2) .get()); DateTime now = new DateTime(ISOChronology.getInstanceUTC()); indexRandom(true, client().prepareIndex("index-1", "type", "1").setSource("d", now, "field", "hello world"), client().prepareIndex("index-1", "type", "2").setSource("d", now.minusDays(1), "field", "hello"), client().prepareIndex("index-1", "type", "3").setSource("d", now.minusDays(2), "field", "world")); ensureSearchable("index-1"); for (int i = 0; i < 5; i++) { final SearchResponse r1 = client().prepareSearch("index-1") .addSort("d", SortOrder.DESC) .setTrackScores(true) .highlighter(highlight() .field("field") .preTags("<x>") .postTags("</x>") ).setQuery(QueryBuilders.boolQuery().must( QueryBuilders.rangeQuery("d").gte("now-12h").lte("now").includeLower(true).includeUpper(true).boost(1.0f)) .should(QueryBuilders.termQuery("field", "hello"))) .get(); assertSearchResponse(r1); assertThat(r1.getHits().getTotalHits(), equalTo(1L)); assertHighlight(r1, 0, "field", 0, 1, equalTo("<x>hello</x> world")); } }
/** {@inheritDoc} */ public DateTime getLastModifiedTime() throws ResourceException { try { return super.getLastModifiedTime(); } catch (ResourceException e) { log.warn("HTTP resource '{}' was inaccessible for getLastModifiedTime(), trying backing file '{}'", getLocation(), resourceFile.getAbsolutePath()); long lastModifiedTime = resourceFile.lastModified(); if (lastModifiedTime == 0) { throw new ResourceException("URL resource is not reachable and backing file is not readable"); } return new DateTime(lastModifiedTime, ISOChronology.getInstanceUTC()); } }