private static double toDoubleValue(Object o) { if (o instanceof Number) { return ((Number) o).doubleValue(); } else if (o instanceof ReadableInstant) { // Dates are exposed in scripts as ReadableDateTimes but aggregations want them to be numeric return ((ReadableInstant) o).getMillis(); } else if (o instanceof Boolean) { // We do expose boolean fields as boolean in scripts, however aggregations still expect // that scripts return the same internal representation as regular fields, so boolean // values in scripts need to be converted to a number, and the value formatter will // make sure of using true/false in the key_as_string field return ((Boolean) o).booleanValue() ? 1.0 : 0.0; } else { throw new AggregationExecutionException("Unsupported script value [" + o + "], expected a number, date, or boolean"); } }
private static long toLongValue(Object o) { if (o instanceof Number) { return ((Number) o).longValue(); } else if (o instanceof ReadableInstant) { // Dates are exposed in scripts as ReadableDateTimes but aggregations want them to be numeric return ((ReadableInstant) o).getMillis(); } else if (o instanceof Boolean) { // We do expose boolean fields as boolean in scripts, however aggregations still expect // that scripts return the same internal representation as regular fields, so boolean // values in scripts need to be converted to a number, and the value formatter will // make sure of using true/false in the key_as_string field return ((Boolean) o).booleanValue() ? 1L : 0L; } else { throw new AggregationExecutionException("Unsupported script value [" + o + "], expected a number, date, or boolean"); } }
protected static Map<Class<?>, IndexType> createBasicMappings() { Map<Class<?>, IndexType> map = new LinkedHashMap<>(); map.put(Short.class, IndexType.SmallDecimal); map.put(Integer.class, IndexType.SmallDecimal); map.put(short.class, IndexType.SmallDecimal); map.put(int.class, IndexType.SmallDecimal); map.put(AtomicInteger.class, IndexType.SmallDecimal); map.put(AtomicBoolean.class, IndexType.Identifier); map.put(boolean.class, IndexType.Identifier); map.put(Boolean.class, IndexType.Identifier); map.put(Enum.class, IndexType.Identifier); map.put(UUID.class, IndexType.Identifier); map.put(Number.class, IndexType.BigDecimal); map.put(long.class, IndexType.BigDecimal); map.put(float.class, IndexType.BigDecimal); map.put(double.class, IndexType.BigDecimal); map.put(CharSequence.class, IndexType.Text); map.put(ReadableInstant.class, IndexType.Date); map.put(Date.class, IndexType.Date); map.put(GeoPoint.class, IndexType.GeoPoint); return map; }
@Test public void shouldTakeTypeInheritenceIntoAccountWhenGettingBestTransformerWhenConsideringDestination() { ObjectToDateTime transformer = new ObjectToDateTime(); transformerManager.register(Object.class, DateTime.class, transformer); assertThat(transformerManager.getTransformer(String.class, ReadableInstant.class), is(nullValue())); assertThat(transformerManager.getTransformer(Long.class, ReadableInstant.class), is(nullValue())); ETransformer<? super String, ? extends ReadableInstant> stringToDateTime = transformerManager.getBestTransformer(String.class, ReadableInstant.class); assertThat(stringToDateTime, is(notNullValue())); assertThat(stringToDateTime.from("2014-06-05T00:00:00.000Z").compareTo(new DateTime(2014, 6, 5, 0, 0, 0).withZoneRetainFields(DateTimeZone.UTC)), is(0)); ETransformer<? super Long, ? extends ReadableInstant> longToDateTime = transformerManager.getBestTransformer(Long.class, ReadableInstant.class); assertThat(longToDateTime, is(notNullValue())); assertThat(longToDateTime.from(123456L).compareTo(new DateTime(123456)), is(0)); }
@Test public void shouldCacheBestTransformerForFasterLaterLookups() { ObjectToDateTime registered = new ObjectToDateTime(); transformerManager.register(Object.class, DateTime.class, registered); ETransformer<? super String, ? extends ReadableInstant> found = transformerManager.getBestTransformer(String.class, ReadableInstant.class); ETransformer<? super String, ? extends ReadableInstant> cached = transformerManager.getFromCache(String.class, ReadableInstant.class); assertThat(cached, is(notNullValue())); assertThat(cached, is(sameInstance((Object) registered))); assertThat(cached, is(sameInstance((Object) found))); // inject another instance into the cache ObjectToDateTime newInstance = new ObjectToDateTime(); transformerManager.addToCache(String.class, ReadableInstant.class, newInstance); ETransformer<? super String, ? extends ReadableInstant> found2 = transformerManager.getBestTransformer(String.class, ReadableInstant.class); assertThat(found2, sameInstance((Object) newInstance)); }
@Test public void shouldClearConvertorCacheWhenNewTransformersRegistered() { ObjectToDateTime registered = new ObjectToDateTime(); transformerManager.register(Object.class, DateTime.class, registered); ETransformer<? super String, ? extends ReadableInstant> found = transformerManager.getBestTransformer(String.class, ReadableInstant.class); ETransformer<? super String, ? extends ReadableInstant> cached = transformerManager.getFromCache(String.class, ReadableInstant.class); assertThat(found, is((Object) registered)); assertThat(cached, is((Object) registered)); StringToDateTime registered2 = new StringToDateTime(); transformerManager.register(String.class, DateTime.class, registered2); ETransformer<? super String, ? extends ReadableInstant> found2 = transformerManager.getBestTransformer(String.class, ReadableInstant.class); ETransformer<? super String, ? extends ReadableInstant> cached2 = transformerManager.getFromCache(String.class, ReadableInstant.class); assertThat(found2, is((Object) registered2)); assertThat(cached2, is((Object) registered2)); }
@Test public void shouldUnregisterPreviouslyRegisteredTransformerAndClearCache() { ObjectToDateTime registered = new ObjectToDateTime(); transformerManager.register(Object.class, DateTime.class, registered); ETransformer<? super String, ? extends ReadableInstant> found = transformerManager.getBestTransformer(String.class, ReadableInstant.class); ETransformer<? super String, ? extends ReadableInstant> cached = transformerManager.getFromCache(String.class, ReadableInstant.class); assertThat(found, is((Object) registered)); assertThat(cached, is((Object) registered)); transformerManager.unregister(Object.class, DateTime.class); ETransformer<? super String, ? extends ReadableInstant> found2 = transformerManager.getBestTransformer(String.class, ReadableInstant.class); ETransformer<? super String, ? extends ReadableInstant> cached2 = transformerManager.getFromCache(String.class, ReadableInstant.class); assertThat(found2, is(nullValue())); assertThat(cached2, is(nullValue())); }
private static ReadableInstant[] getInterval(int beforeOrAfter, ReadableInstant now, LastRun lastRun, int timeType) { ReadableInstant[] res = new ReadableInstant[2]; switch (beforeOrAfter) { case TIME_BEFORE_NOW: // Before now, starting from lastRun, depending on timeType res[0] = timeType == DbTimeView.SCHEDULED_TIME ? lastRun.scheduled : lastRun.deadline; if (res[0] == null) { res[0] = now; } res[1] = now; break; case TIME_FROM_NOW: res[0] = now; res[1] = null; break; default: throw new IllegalArgumentException("Before or after now?"); } return res; }
private String getAsStringValue(FacesContext facesContext, UIComponent uiComponent, Object value) { if (facesContext == null) { throw new NullPointerException("facesContext"); } if (uiComponent == null) { throw new NullPointerException("uiComponent"); } if (value == null) { return ""; } if (value instanceof String) { return (String) value; } DateTimeFormatter format = getDateFormat(uiComponent); try { return format.print((ReadableInstant) value); } catch (Exception e) { throw new ConverterException("Cannot convert value '" + value + "'"); } }
@Test public void garbageCollectionTimeAfterEndOfGlobalWindowWithLateness() { FixedWindows windowFn = FixedWindows.of(Duration.standardMinutes(5)); Duration allowedLateness = Duration.millis(Long.MAX_VALUE); WindowingStrategy<?, ?> strategy = WindowingStrategy.globalDefault() .withWindowFn(windowFn) .withAllowedLateness(allowedLateness); IntervalWindow window = windowFn.assignWindow(new Instant(-100)); assertThat( window.maxTimestamp().plus(allowedLateness), Matchers.<ReadableInstant>greaterThan(GlobalWindow.INSTANCE.maxTimestamp())); assertThat( LateDataUtils.garbageCollectionTime(window, strategy), equalTo(GlobalWindow.INSTANCE.maxTimestamp())); }
public static DateTime getFirstWarningTime( int timeType, OrgDateTime orgDateTime, ReadableInstant fromTime, ReadableInstant beforeTime, OrgInterval defaultTimeOfDay, OrgInterval defaultWarningPeriod) { List<DateTime> times = OrgDateTimeUtils.getTimesInInterval( orgDateTime, fromTime, beforeTime, false, 1); for (DateTime time : times) { if (!orgDateTime.hasTime()) { time = time.plusHours(9); // TODO: Move to preferences } return time; } return null; }
/** * Compares this object with the specified object for ascending * millisecond instant order. This ordering is inconsistent with * equals, as it ignores the Chronology. * <p> * All ReadableInstant instances are accepted. * * @param other a readable instant to check against * @return negative value if this is less, 0 if equal, or positive value if greater * @throws NullPointerException if the object is null * @throws ClassCastException if the object type is not supported */ public int compareTo(ReadableInstant other) { if (this == other) { return 0; } long otherMillis = other.getMillis(); long thisMillis = getMillis(); // cannot do (thisMillis - otherMillis) as can overflow if (thisMillis == otherMillis) { return 0; } if (thisMillis < otherMillis) { return -1; } else { return 1; } }
public ExitStatus afterStep(StepExecution stepExecution) { logger.debug("After Step " + currentStep.getStepName()); try { Url u = new Url(); u.setLastmod(ISODateTimeFormat.dateTime().print((ReadableInstant) null)); u.setLoc(new URL(portalBaseUrl +"/" + sitemapDir + "/" + currentFile.getFilename())); sitemapNames.add(u); } catch (MalformedURLException e) { logger.error("Unable create Url for sitemap", e); } //reset counts to nulls to support beforeStep() currentStep = null; currentFile = null; chunkOfFile = 0; commitSize = 0; return stepExecution.getExitStatus(); }
public void beforeChunk() { //Check sizes (MB & count) & if over limit if (FileUtils.sizeOf(currentFile.getFile()) >= MAX_SITEMAP_LENGTH || (chunkOfFile * commitSize) >= MAX_URL_COUNT){ logger.debug("Creating a new file"); try { Url u = new Url(); u.setLastmod(ISODateTimeFormat.dateTime().print((ReadableInstant) null)); u.setLoc(new URL(portalBaseUrl + "/sitemap/" + currentFile.getFilename())); sitemapNames.add(u); } catch (MalformedURLException e) { logger.error("Unable create Url for sitemap", e); } //close & open writer with new name staxWriter.close(); currentFile = new FileSystemResource(sitemapSpoolDir + "/"+ currentStep.getStepName() + ++fileCount + ".xml"); logger.debug("Open:" + currentFile.isOpen()); logger.debug("Writable:" + currentFile.isWritable()); staxWriter.setResource((Resource) currentFile); staxWriter.open(currentStep.getExecutionContext()); chunkOfFile = 0; } }
public void testBigHashtable() { Converter[] array = new Converter[] { c1, c2, c3, c4, }; ConverterSet set = new ConverterSet(array); set.select(Boolean.class); set.select(Character.class); set.select(Byte.class); set.select(Short.class); set.select(Integer.class); set.select(Long.class); set.select(Float.class); set.select(Double.class); set.select(null); set.select(Calendar.class); set.select(GregorianCalendar.class); set.select(DateTime.class); set.select(DateMidnight.class); set.select(ReadableInstant.class); set.select(ReadableDateTime.class); set.select(ReadWritableInstant.class); // 16 set.select(ReadWritableDateTime.class); set.select(DateTime.class); assertEquals(4, set.size()); }
public void testGetInstantConverter() { InstantConverter c = ConverterManager.getInstance().getInstantConverter(new Long(0L)); assertEquals(Long.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new DateTime()); assertEquals(ReadableInstant.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(""); assertEquals(String.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new Date()); assertEquals(Date.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(new GregorianCalendar()); assertEquals(Calendar.class, c.getSupportedType()); c = ConverterManager.getInstance().getInstantConverter(null); assertEquals(null, c.getSupportedType()); try { ConverterManager.getInstance().getInstantConverter(Boolean.TRUE); fail(); } catch (IllegalArgumentException ex) {} }
public ExchangeOutputConverterSet( ExchangeUnitOutputAttributeSet attributeSet) { nodeInputConverters = new NodeInputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant>( attributeSet.getNodeInputAttributes(), CsvFormatUtil.mmddyyyyFormatTimeInstant); nodeOutputConverters = new NodeOutputAttributeDefaultConverters<ExchangeUnit, DonorEdge, ReadableInstant, Interval>( attributeSet.getNodeOutputAttributes(), CsvFormatUtil.mmddyyyyFormatTimeInstant, CsvFormatUtil.numDays); exchangeInputDefaultConverter = new ExchangeInputAttributeDefaultConverters( attributeSet.getExchangeInputAttributes()); exchangeOutputDefaultConverter = new ExchangeOutputAttributeDefaultConverters( attributeSet.getExchangeOutputAttributes()); personInputAttributeDefaultConverters = new PersonInputAttributeDefaultConverters( attributeSet.getPersonInputAttributes()); receiverInputAttributeDefaultConverters = new ReceiverInputAttributeDefaultConverters( attributeSet.getReceiverInputAttributes()); }
private static MultiPeriodCyclePackingInputs<ExchangeUnit, DonorEdge, ReadableInstant> generateDefaultInputs() { ProblemData problemData = new ProblemData(dateString); Map<ExchangeUnit, ReasonsInvalid> removed = DataCleaner.cleanProblemData( problemData, EnumSet.allOf(ReasonToCleanDonor.class), EnumSet.allOf(ReasonToCleanReceiver.class)); DataCleaner.assessHistoricMatching(problemData, removed); // the system begins in the preexisting state at time start, i.e. those that // arrive // before start but have not yet been matched are waiting. DataMultiPeriodConverter converterOld = new DataMultiPeriodConverter( problemData, start, end); // the system begins empty at time start, but then has the same arrivals as // above. // DataMultiPeriodConverter converterFresh = new // DataMultiPeriodConverter(problemData,start,end,true); MultiPeriodCyclePackingInputs<ExchangeUnit, DonorEdge, ReadableInstant> inputs = converterOld .getMultiPeriodPackingInputs(); // contains pair match power info. ExchangeUnitAuxiliaryInputStatistics auxiliaryInput = Queries .getAuxiliaryStatisticsWithVPra(inputs); inputs.setAuxiliaryInputStatistics(auxiliaryInput); return inputs; }
private void unknownValue(Object value) throws IOException { if (value == null) { nullValue(); return; } Writer writer = WRITERS.get(value.getClass()); if (writer != null) { writer.write(this, value); } else if (value instanceof Path) { //Path implements Iterable<Path> and causes endless recursion and a StackOverFlow if treated as an Iterable here value((Path) value); } else if (value instanceof Map) { map((Map) value); } else if (value instanceof Iterable) { value((Iterable<?>) value); } else if (value instanceof Object[]) { values((Object[]) value); } else if (value instanceof Calendar) { value((Calendar) value); } else if (value instanceof ReadableInstant) { value((ReadableInstant) value); } else if (value instanceof BytesReference) { value((BytesReference) value); } else if (value instanceof ToXContent) { value((ToXContent) value); } else { // This is a "value" object (like enum, DistanceUnit, etc) just toString() it // (yes, it can be misleading when toString a Java class, but really, jackson should be used in that case) value(Objects.toString(value)); } }
/** * Notice: when serialization a map, the stream out map with the stream in map maybe have the * different key-value orders, they will maybe have different stream order. * If want to keep stream out map and stream in map have the same stream order when stream, * can use {@code writeMapWithConsistentOrder} */ public void writeGenericValue(@Nullable Object value) throws IOException { if (value == null) { writeByte((byte) -1); return; } final Class type; if (value instanceof List) { type = List.class; } else if (value instanceof Object[]) { type = Object[].class; } else if (value instanceof Map) { type = Map.class; } else if (value instanceof ReadableInstant) { type = ReadableInstant.class; } else if (value instanceof BytesReference) { type = BytesReference.class; } else { type = value.getClass(); } final Writer writer = WRITERS.get(type); if (writer != null) { writer.write(this, value); } else { throw new IOException("can not write type [" + type + "]"); } }
@Override public Printer<?> getPrinter(DateTimeFormat annotation, Class<?> fieldType) { DateTimeFormatter formatter = getFormatter(annotation, fieldType); if (ReadablePartial.class.isAssignableFrom(fieldType)) { return new ReadablePartialPrinter(formatter); } else if (ReadableInstant.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType)) { // assumes Calendar->ReadableInstant converter is registered return new ReadableInstantPrinter(formatter); } else { // assumes Date->Long converter is registered return new MillisecondInstantPrinter(formatter); } }
@Override public void registerFormatters(FormatterRegistry registry) { JodaTimeConverters.registerConverters(registry); DateTimeFormatter dateFormatter = getFormatter(Type.DATE); DateTimeFormatter timeFormatter = getFormatter(Type.TIME); DateTimeFormatter dateTimeFormatter = getFormatter(Type.DATE_TIME); addFormatterForFields(registry, new ReadablePartialPrinter(dateFormatter), new LocalDateParser(dateFormatter), LocalDate.class); addFormatterForFields(registry, new ReadablePartialPrinter(timeFormatter), new LocalTimeParser(timeFormatter), LocalTime.class); addFormatterForFields(registry, new ReadablePartialPrinter(dateTimeFormatter), new LocalDateTimeParser(dateTimeFormatter), LocalDateTime.class); addFormatterForFields(registry, new ReadableInstantPrinter(dateTimeFormatter), new DateTimeParser(dateTimeFormatter), ReadableInstant.class); // In order to retain backwards compatibility we only register Date/Calendar // types when a user defined formatter is specified (see SPR-10105) if (this.formatters.containsKey(Type.DATE_TIME)) { addFormatterForFields(registry, new ReadableInstantPrinter(dateTimeFormatter), new DateTimeParser(dateTimeFormatter), Date.class, Calendar.class); } registry.addFormatterForFieldAnnotation(new JodaDateTimeFormatAnnotationFormatterFactory()); }
@Override public InstanceAdminLogApi.LogList searchLogs(final long tenantId, final long startEventId, final int count, final String email, final ReadableInstant startDate, final ReadableInstant endDate) throws Exception { try (final Connection conn = adminDS.getConnection()) { return new InstanceAdminLogApi.LogList( tenantQueries.tenantLogs(conn, tenantId, startEventId, count, startDate, endDate, email == null ? "" : email)); } }
/** * Converts a {@link ReadableInstant} into a Dateflow API time value. */ public static String toCloudTime(ReadableInstant instant) { // Note that since Joda objects use millisecond resolution, we always // produce either no fractional seconds or fractional seconds with // millisecond resolution. // Translate the ReadableInstant to a DateTime with ISOChronology. DateTime time = new DateTime(instant); int millis = time.getMillisOfSecond(); if (millis == 0) { return String.format("%04d-%02d-%02dT%02d:%02d:%02dZ", time.getYear(), time.getMonthOfYear(), time.getDayOfMonth(), time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute()); } else { return String.format("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ", time.getYear(), time.getMonthOfYear(), time.getDayOfMonth(), time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute(), millis); } }