Java Examples for java.time.OffsetDateTime

The following java examples will help you to understand the usage of java.time.OffsetDateTime. These source code samples are taken from different open source projects.

Example 1
Project: j-master  File: StatementsTest.java View source code
/**
     * Helper method for *SetObject* tests.
     * Validate the test data contained in the given ResultSet with following structure:
     * 1 - `id` INT
     * 2 - `ot1` VARCHAR
     * 3 - `ot2` BLOB
     * 4 - `odt1` VARCHAR
     * 5 - `odt2` BLOB
     * 
     * Additionally validate support for the types java.time.Offset[Date]Time in ResultSet.getObject().
     * 
     * @param tableName
     * @param expectedRowCount
     * @throws Exception
     */
private void validateTestDataOffsetDTTypes(String tableName, int expectedRowCount) throws Exception {
    // Offset[Date]Time are supported via object serialization too.
    Connection testConn = getConnectionWithProps("autoDeserialize=true");
    Statement testStmt = testConn.createStatement();
    this.rs = testStmt.executeQuery("SELECT * FROM " + tableName);
    int rowCount = 0;
    while (rs.next()) {
        String row = "Row " + rs.getInt(1);
        assertEquals(++rowCount, rs.getInt(1));
        assertEquals(row, testOffsetTime, this.rs.getObject(2, OffsetTime.class));
        assertEquals(row, testOffsetTime, this.rs.getObject(3, OffsetTime.class));
        assertEquals(row, testOffsetDateTime, this.rs.getObject(4, OffsetDateTime.class));
        assertEquals(row, testOffsetDateTime, this.rs.getObject(5, OffsetDateTime.class));
        assertEquals(row, rowCount, this.rs.getInt("id"));
        assertEquals(row, testOffsetTime, this.rs.getObject("ot1", OffsetTime.class));
        assertEquals(row, testOffsetTime, this.rs.getObject("ot2", OffsetTime.class));
        assertEquals(row, testOffsetDateTime, this.rs.getObject("odt1", OffsetDateTime.class));
        assertEquals(row, testOffsetDateTime, this.rs.getObject("odt2", OffsetDateTime.class));
    }
    assertEquals(expectedRowCount, rowCount);
    testConn.close();
}
Example 2
Project: assertj-core-master  File: BDDSoftAssertionsTest.java View source code
@Test
public void should_be_able_to_catch_exceptions_thrown_by_all_proxied_methods() throws URISyntaxException {
    try {
        softly.then(BigDecimal.ZERO).isEqualTo(BigDecimal.ONE);
        softly.then(Boolean.FALSE).isTrue();
        softly.then(false).isTrue();
        softly.then(new boolean[] { false }).isEqualTo(new boolean[] { true });
        softly.then(new Byte((byte) 0)).isEqualTo((byte) 1);
        softly.then((byte) 2).inHexadecimal().isEqualTo((byte) 3);
        softly.then(new byte[] { 4 }).isEqualTo(new byte[] { 5 });
        softly.then(new Character((char) 65)).isEqualTo(new Character((char) 66));
        softly.then((char) 67).isEqualTo((char) 68);
        softly.then(new char[] { 69 }).isEqualTo(new char[] { 70 });
        softly.then(new StringBuilder("a")).isEqualTo(new StringBuilder("b"));
        softly.then(Object.class).isEqualTo(String.class);
        softly.then(parseDatetime("1999-12-31T23:59:59")).isEqualTo(parseDatetime("2000-01-01T00:00:01"));
        softly.then(new Double(6.0d)).isEqualTo(new Double(7.0d));
        softly.then(8.0d).isEqualTo(9.0d);
        softly.then(new double[] { 10.0d }).isEqualTo(new double[] { 11.0d });
        softly.then(new File("a")).overridingErrorMessage("expected:<File(b)> but was:<File(a)>").isEqualTo(new File("b"));
        softly.then(new Float(12f)).isEqualTo(new Float(13f));
        softly.then(14f).isEqualTo(15f);
        softly.then(new float[] { 16f }).isEqualTo(new float[] { 17f });
        softly.then(new ByteArrayInputStream(new byte[] { (byte) 65 })).hasSameContentAs(new ByteArrayInputStream(new byte[] { (byte) 66 }));
        softly.then(new Integer(20)).isEqualTo(new Integer(21));
        softly.then(22).isEqualTo(23);
        softly.then(new int[] { 24 }).isEqualTo(new int[] { 25 });
        softly.then((Iterable<String>) Lists.newArrayList("26")).isEqualTo(Lists.newArrayList("27"));
        softly.then(Lists.newArrayList("28").iterator()).contains("29");
        softly.then(Lists.newArrayList("30")).isEqualTo(Lists.newArrayList("31"));
        softly.then(new Long(32L)).isEqualTo(new Long(33L));
        softly.then(34L).isEqualTo(35L);
        softly.then(new long[] { 36L }).isEqualTo(new long[] { 37L });
        softly.then(Maps.mapOf(MapEntry.entry("38", "39"))).isEqualTo(Maps.mapOf(MapEntry.entry("40", "41")));
        softly.then(new Short((short) 42)).isEqualTo(new Short((short) 43));
        softly.then((short) 44).isEqualTo((short) 45);
        softly.then(new short[] { (short) 46 }).isEqualTo(new short[] { (short) 47 });
        softly.then("48").isEqualTo("49");
        softly.then(new Object() {

            @Override
            public String toString() {
                return "50";
            }
        }).isEqualTo(new Object() {

            @Override
            public String toString() {
                return "51";
            }
        });
        softly.then(new Object[] { new Object() {

            @Override
            public String toString() {
                return "52";
            }
        } }).isEqualTo(new Object[] { new Object() {

            @Override
            public String toString() {
                return "53";
            }
        } });
        final IllegalArgumentException illegalArgumentException = new IllegalArgumentException("IllegalArgumentException message");
        softly.then(illegalArgumentException).hasMessage("NullPointerException message");
        softly.thenThrownBy(new ThrowingCallable() {

            @Override
            public void call() throws Exception {
                throw new Exception("something was wrong");
            }
        }).hasMessage("something was good");
        softly.then(Optional.of("not empty")).isEqualTo("empty");
        // TODO should be caught : softly.assertThat(Optional.of("not empty")).isEmpty();
        softly.then(OptionalInt.of(0)).isEqualTo(1);
        softly.then(OptionalDouble.of(0.0)).isEqualTo(1.0);
        softly.then(OptionalLong.of(0L)).isEqualTo(1L);
        softly.then(new URI("http://assertj.org")).hasPort(8888);
        softly.then(LocalTime.of(12, 0)).isEqualTo(LocalTime.of(13, 0));
        softly.then(OffsetTime.of(12, 0, 0, 0, ZoneOffset.UTC)).isEqualTo(OffsetTime.of(13, 0, 0, 0, ZoneOffset.UTC));
        softly.then(OffsetDateTime.MIN).isEqualTo(LocalDateTime.MAX);
        // softly.then(completedFuture("done")).hasFailed();
        softly.then((Predicate<String>)  s -> s.equals("something")).accepts("something else");
        softly.then((IntPredicate)  s -> s == 1).accepts(2);
        softly.then((LongPredicate)  s -> s == 1).accepts(2);
        softly.then((DoublePredicate)  s -> s == 1).accepts(2.0);
        softly.assertAll();
        fail("Should not reach here");
    } catch (SoftAssertionError e) {
        List<String> errors = e.getErrors();
        assertThat(errors).hasSize(51);
        assertThat(errors.get(0)).startsWith("expected:<[1]> but was:<[0]>");
        assertThat(errors.get(1)).startsWith("expected:<[tru]e> but was:<[fals]e>");
        assertThat(errors.get(2)).startsWith("expected:<[tru]e> but was:<[fals]e>");
        assertThat(errors.get(3)).startsWith("expected:<[[tru]e]> but was:<[[fals]e]>");
        assertThat(errors.get(4)).startsWith("expected:<[1]> but was:<[0]>");
        assertThat(errors.get(5)).startsWith("expected:<0x0[3]> but was:<0x0[2]>");
        assertThat(errors.get(6)).startsWith("expected:<[[5]]> but was:<[[4]]>");
        assertThat(errors.get(7)).startsWith("expected:<'[B]'> but was:<'[A]'>");
        assertThat(errors.get(8)).startsWith("expected:<'[D]'> but was:<'[C]'>");
        assertThat(errors.get(9)).startsWith("expected:<['[F]']> but was:<['[E]']>");
        assertThat(errors.get(10)).startsWith("expected:<[b]> but was:<[a]>");
        assertThat(errors.get(11)).startsWith("expected:<java.lang.[String]> but was:<java.lang.[Object]>");
        assertThat(errors.get(12)).startsWith("expected:<[2000-01-01T00:00:01].000> but was:<[1999-12-31T23:59:59].000>");
        assertThat(errors.get(13)).startsWith("expected:<[7].0> but was:<[6].0>");
        assertThat(errors.get(14)).startsWith("expected:<[9].0> but was:<[8].0>");
        assertThat(errors.get(15)).startsWith("expected:<[1[1].0]> but was:<[1[0].0]>");
        assertThat(errors.get(16)).startsWith("expected:<File(b)> but was:<File(a)>");
        assertThat(errors.get(17)).startsWith("expected:<1[3].0f> but was:<1[2].0f>");
        assertThat(errors.get(18)).startsWith("expected:<1[5].0f> but was:<1[4].0f>");
        assertThat(errors.get(19)).startsWith("expected:<[1[7].0f]> but was:<[1[6].0f]>");
        assertThat(errors.get(20)).startsWith(format("%nInputStreams do not have same content:%n%n" + "Changed content at line 1:%n" + "expecting:%n" + "  [\"B\"]%n" + "but was:%n" + "  [\"A\"]%n"));
        assertThat(errors.get(21)).startsWith("expected:<2[1]> but was:<2[0]>");
        assertThat(errors.get(22)).startsWith("expected:<2[3]> but was:<2[2]>");
        assertThat(errors.get(23)).startsWith("expected:<[2[5]]> but was:<[2[4]]>");
        assertThat(errors.get(24)).startsWith("expected:<[\"2[7]\"]> but was:<[\"2[6]\"]>");
        assertThat(errors.get(25)).startsWith(format("%nExpecting:%n" + " <[\"28\"]>%n" + "to contain:%n" + " <[\"29\"]>%n" + "but could not find:%n" + " <[\"29\"]>%n"));
        assertThat(errors.get(26)).startsWith("expected:<[\"3[1]\"]> but was:<[\"3[0]\"]>");
        assertThat(errors.get(27)).startsWith("expected:<3[3]L> but was:<3[2]L>");
        assertThat(errors.get(28)).startsWith("expected:<3[5]L> but was:<3[4]L>");
        assertThat(errors.get(29)).startsWith("expected:<[3[7]L]> but was:<[3[6]L]>");
        assertThat(errors.get(30)).startsWith("expected:<{\"[40\"=\"41]\"}> but was:<{\"[38\"=\"39]\"}>");
        assertThat(errors.get(31)).startsWith("expected:<4[3]> but was:<4[2]>");
        assertThat(errors.get(32)).startsWith("expected:<4[5]> but was:<4[4]>");
        assertThat(errors.get(33)).startsWith("expected:<[4[7]]> but was:<[4[6]]>");
        assertThat(errors.get(34)).startsWith("expected:<\"4[9]\"> but was:<\"4[8]\">");
        assertThat(errors.get(35)).startsWith("expected:<5[1]> but was:<5[0]>");
        assertThat(errors.get(36)).startsWith("expected:<[5[3]]> but was:<[5[2]]>");
        assertThat(errors.get(37)).startsWith(format("%nExpecting message:%n" + " <\"NullPointerException message\">%n" + "but was:%n" + " <\"IllegalArgumentException message\">"));
        assertThat(errors.get(38)).startsWith(format("%nExpecting message:%n" + " <\"something was good\">%n" + "but was:%n" + " <\"something was wrong\">"));
        assertThat(errors.get(39)).startsWith("expected:<[\"empty\"]> but was:<[Optional[not empty]]>");
        assertThat(errors.get(40)).startsWith("expected:<[1]> but was:<[OptionalInt[0]]>");
        assertThat(errors.get(41)).startsWith("expected:<[1.0]> but was:<[OptionalDouble[0.0]]>");
        assertThat(errors.get(42)).startsWith("expected:<[1L]> but was:<[OptionalLong[0]]>");
        assertThat(errors.get(43)).contains(format("%nExpecting port of"));
        assertThat(errors.get(44)).startsWith("expected:<1[3]:00> but was:<1[2]:00>");
        assertThat(errors.get(45)).startsWith("expected:<1[3]:00Z> but was:<1[2]:00Z>");
        assertThat(errors.get(46)).startsWith("expected:<[+999999999-12-31T23:59:59.999999999]> but was:<[-999999999-01-01T00:00+18:00]>");
        assertThat(errors.get(47)).startsWith(String.format("%nExpecting:%n  <given predicate>%n" + "to accept <\"something else\"> but it did not."));
        assertThat(errors.get(48)).startsWith(String.format("%nExpecting:%n  <given predicate>%n" + "to accept <2> but it did not."));
        assertThat(errors.get(49)).startsWith(String.format("%nExpecting:%n  <given predicate>%n" + "to accept <2L> but it did not."));
        assertThat(errors.get(50)).startsWith(String.format("%nExpecting:%n  <given predicate>%n" + "to accept <2.0> but it did not."));
    }
}
Example 3
Project: threeten-jpa-master  File: TimestamptzConverter.java View source code
// Byte 0: Century, offset is 100 (value - 100 is century)
// Byte 1: Decade, offset is 100 (value - 100 is decade)
// Byte 2: Month UTC
// Byte 3: Day UTC
// Byte 4: Hour UTC, offset is 1 (value-1 is UTC hour)
// Byte 5: Minute UTC, offset is 1 (value-1 is UTC Minute)
// Byte 6: Second, offset is 1 (value-1 is seconds)
// Byte 7: nanoseconds (most significant bit)
// Byte 8: nanoseconds
// Byte 9: nanoseconds
// Byte 10: nanoseconds (least significant bit)
// Byte 11: Hour UTC-offset of Timezone, offset is 20 (value-20 is UTC-hour offset)
// Byte 12: Minute UTC-offset of Timezone, offset is 60 (value-60 is UTC-minute offset)
/**
   * Converts {@link OffsetDateTime} to {@link TIMESTAMPTZ}.
   *
   * @param attribute the value to be converted, possibly {@code null}
   * @return the converted data, possibly {@code null}
   */
public static TIMESTAMPTZ offsetDateTimeToTimestamptz(OffsetDateTime attribute) {
    if (attribute == null) {
        return null;
    }
    byte[] bytes = newTimestamptzBuffer();
    ZonedDateTime utc = attribute.atZoneSameInstant(UTC);
    writeDateTime(bytes, utc.toLocalDateTime());
    ZoneOffset offset = attribute.getOffset();
    writeZoneOffset(bytes, offset);
    return new TIMESTAMPTZ(bytes);
}
Example 4
Project: edison-microservice-master  File: JobServiceTest.java View source code
@Test
public void shouldStopJob() {
    OffsetDateTime now = OffsetDateTime.now(clock);
    Clock earlierClock = offset(clock, Duration.of(-1, MINUTES));
    JobInfo jobInfo = JobInfo.newJobInfo("superId", "superType", earlierClock, HOSTNAME);
    when(jobRepository.findOne("superId")).thenReturn(Optional.of(jobInfo));
    jobService.stopJob("superId");
    JobInfo expected = jobInfo.copy().setStatus(JobInfo.JobStatus.OK).setStopped(now).setLastUpdated(now).build();
    verify(jobMetaService).releaseRunLock("superType");
    verify(jobRepository).createOrUpdate(expected);
}
Example 5
Project: Gaffer-master  File: CommonTimeUtil.java View source code
/**
     * Place a time value (a Java {@link Long} representing the number of
     * milliseconds since the start of the Unix epoch) in a {@link TimeBucket}.
     *
     * @param time   the time, in milliseconds since the start of the Unix epoch
     * @param bucket the time bucket to place the time value into
     * @return the value of the time bucket
     */
public static long timeToBucket(final long time, final TimeBucket bucket) {
    final OffsetDateTime dateTime = Instant.ofEpochMilli(time).atOffset(ZoneOffset.UTC);
    final long timeBucket;
    switch(bucket) {
        case SECOND:
            timeBucket = dateTime.truncatedTo(SECONDS).toInstant().toEpochMilli();
            break;
        case MINUTE:
            timeBucket = dateTime.truncatedTo(MINUTES).toInstant().toEpochMilli();
            break;
        case HOUR:
            timeBucket = dateTime.truncatedTo(HOURS).toInstant().toEpochMilli();
            break;
        case DAY:
            timeBucket = dateTime.truncatedTo(DAYS).toInstant().toEpochMilli();
            break;
        case WEEK:
            timeBucket = dateTime.with(firstDayOfWeek()).truncatedTo(DAYS).toInstant().toEpochMilli();
            break;
        case MONTH:
            timeBucket = dateTime.with(firstDayOfMonth()).truncatedTo(DAYS).toInstant().toEpochMilli();
            break;
        default:
            timeBucket = time;
    }
    return timeBucket;
}
Example 6
Project: dropwizard-master  File: OffsetDateTimeMapperTest.java View source code
@Test
public void mapColumnByName() throws Exception {
    final Instant now = OffsetDateTime.now().toInstant();
    when(resultSet.getTimestamp("name")).thenReturn(Timestamp.from(now));
    OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, "name", null);
    assertThat(actual).isEqualTo(OffsetDateTime.ofInstant(now, ZoneId.systemDefault()));
}
Example 7
Project: hprose-java-master  File: OffsetDateTimeUnserializer.java View source code
@Override
public OffsetDateTime unserialize(Reader reader, int tag, Type type) throws IOException {
    OffsetDateTimeConverter converter = OffsetDateTimeConverter.instance;
    switch(tag) {
        case TagString:
            return OffsetDateTime.parse(ReferenceReader.readString(reader));
        case TagDate:
            return converter.convertTo(ReferenceReader.readDateTime(reader));
        case TagTime:
            return converter.convertTo(ReferenceReader.readTime(reader));
        case TagEmpty:
            return null;
    }
    return super.unserialize(reader, tag, type);
}
Example 8
Project: pyramus-master  File: StudentRESTService.java View source code
@Path("/studentGroups")
@POST
@RESTPermit(StudentGroupPermissions.CREATE_STUDENTGROUP)
public Response createStudentGroup(fi.otavanopisto.pyramus.rest.model.StudentGroup entity) {
    String name = entity.getName();
    String description = entity.getDescription();
    OffsetDateTime beginDate = entity.getBeginDate();
    if (StringUtils.isBlank(name)) {
        return Response.status(Status.BAD_REQUEST).build();
    }
    StudentGroup studentGroup = studentGroupController.createStudentGroup(name, description, toDate(beginDate), sessionController.getUser());
    for (String tag : entity.getTags()) {
        studentGroupController.createStudentGroupTag(studentGroup, tag);
    }
    return Response.ok(objectFactory.createModel(studentGroup)).build();
}
Example 9
Project: web-framework-master  File: OffsetDateTimeMapperTest.java View source code
@Test
public void mapColumnByName() throws Exception {
    final Instant now = OffsetDateTime.now().toInstant();
    when(resultSet.getTimestamp("name")).thenReturn(Timestamp.from(now));
    OffsetDateTime actual = new OffsetDateTimeMapper().mapColumn(resultSet, "name", null);
    assertThat(actual).isEqualTo(OffsetDateTime.ofInstant(now, ZoneId.systemDefault()));
}
Example 10
Project: SimpleFlatMapper-master  File: SettableDataSetterFactoryTest.java View source code
@Test
public void testJava8TimeODT() throws Exception {
    Setter<SettableByIndexData, OffsetDateTime> setter = factory.getSetter(newPM(OffsetDateTime.class, DataType.timestamp()));
    OffsetDateTime ldt = OffsetDateTime.now();
    setter.set(statement, ldt);
    setter.set(statement, null);
    verify(statement).setDate(0, Date.from(ldt.toInstant()));
    verify(statement).setToNull(0);
}
Example 11
Project: spring-framework-master  File: DateTimeFormatterRegistrar.java View source code
@Override
public void registerFormatters(FormatterRegistry registry) {
    DateTimeConverters.registerConverters(registry);
    DateTimeFormatter df = getFormatter(Type.DATE);
    DateTimeFormatter tf = getFormatter(Type.TIME);
    DateTimeFormatter dtf = getFormatter(Type.DATE_TIME);
    // Efficient ISO_LOCAL_* variants for printing since they are twice as fast...
    registry.addFormatterForFieldType(LocalDate.class, new TemporalAccessorPrinter(df == DateTimeFormatter.ISO_DATE ? DateTimeFormatter.ISO_LOCAL_DATE : df), new TemporalAccessorParser(LocalDate.class, df));
    registry.addFormatterForFieldType(LocalTime.class, new TemporalAccessorPrinter(tf == DateTimeFormatter.ISO_TIME ? DateTimeFormatter.ISO_LOCAL_TIME : tf), new TemporalAccessorParser(LocalTime.class, tf));
    registry.addFormatterForFieldType(LocalDateTime.class, new TemporalAccessorPrinter(dtf == DateTimeFormatter.ISO_DATE_TIME ? DateTimeFormatter.ISO_LOCAL_DATE_TIME : dtf), new TemporalAccessorParser(LocalDateTime.class, dtf));
    registry.addFormatterForFieldType(ZonedDateTime.class, new TemporalAccessorPrinter(dtf), new TemporalAccessorParser(ZonedDateTime.class, dtf));
    registry.addFormatterForFieldType(OffsetDateTime.class, new TemporalAccessorPrinter(dtf), new TemporalAccessorParser(OffsetDateTime.class, dtf));
    registry.addFormatterForFieldType(OffsetTime.class, new TemporalAccessorPrinter(tf), new TemporalAccessorParser(OffsetTime.class, tf));
    registry.addFormatterForFieldType(Instant.class, new InstantFormatter());
    registry.addFormatterForFieldType(Period.class, new PeriodFormatter());
    registry.addFormatterForFieldType(Duration.class, new DurationFormatter());
    registry.addFormatterForFieldType(YearMonth.class, new YearMonthFormatter());
    registry.addFormatterForFieldType(MonthDay.class, new MonthDayFormatter());
    registry.addFormatterForFieldAnnotation(new Jsr310DateTimeFormatAnnotationFormatterFactory());
}
Example 12
Project: be-worktajm-master  File: TestUtil.java View source code
/**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);
    return mapper.writeValueAsBytes(object);
}
Example 13
Project: codegen-master  File: TypeCategoryTest.java View source code
@Test
public void Java8() {
    assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.Instant"));
    assertEquals(TypeCategory.DATE, TypeCategory.get("java.time.LocalDate"));
    assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.LocalDateTime"));
    assertEquals(TypeCategory.TIME, TypeCategory.get("java.time.LocalTime"));
    assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.OffsetDateTime"));
    assertEquals(TypeCategory.TIME, TypeCategory.get("java.time.OffsetTime"));
    assertEquals(TypeCategory.DATETIME, TypeCategory.get("java.time.ZonedDateTime"));
}
Example 14
Project: droolsjbpm-integration-master  File: XStreamMarshallerTest.java View source code
@Test
public void testMarshallDateObject() {
    String expectedString = "<date-object>\n" + "  <localDate>2017-01-01</localDate>\n" + "  <localDateTime>2017-01-01T10:10:10</localDateTime>\n" + "  <localTime>10:10:10</localTime>\n" + "  <offsetDateTime>2017-01-01T10:10:10+01:00</offsetDateTime>\n" + "</date-object>";
    Set<Class<?>> extraClasses = new HashSet<Class<?>>();
    extraClasses.add(DateObject.class);
    Marshaller marshaller = MarshallerFactory.getMarshaller(extraClasses, MarshallingFormat.XSTREAM, getClass().getClassLoader());
    DateObject dateObject = new DateObject();
    dateObject.setLocalDate(LocalDate.of(2017, 1, 1));
    dateObject.setLocalDateTime(LocalDateTime.of(2017, 1, 1, 10, 10, 10));
    dateObject.setLocalTime(LocalTime.of(10, 10, 10));
    dateObject.setOffsetDateTime(OffsetDateTime.of(LocalDateTime.of(2017, 1, 1, 10, 10, 10), ZoneOffset.ofHours(1)));
    String dateObjectString = marshaller.marshall(dateObject);
    assertNotNull(dateObjectString);
    assertEquals(expectedString, dateObjectString);
}
Example 15
Project: droolsjbpm-knowledge-master  File: OffsetDateTimeXStreamConverter.java View source code
@Override
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    String offsetDateTimeString = reader.getValue();
    try {
        return OffsetDateTime.from(formatter.parse(offsetDateTimeString));
    } catch (DateTimeException e) {
        throw new IllegalStateException("Failed to convert string (" + offsetDateTimeString + ") to type (" + OffsetDateTime.class.getName() + ").");
    }
}
Example 16
Project: ebean-master  File: DefaultTypeManager.java View source code
private void initialiseJavaTimeTypes(JsonConfig.DateTime mode, ServerConfig config) {
    if (java7Present) {
        typeMap.put(java.nio.file.Path.class, new ScalarTypePath());
    }
    if (config.getClassLoadConfig().isJavaTimePresent()) {
        logger.debug("Registering java.time data types");
        typeMap.put(java.time.LocalDate.class, new ScalarTypeLocalDate());
        typeMap.put(java.time.LocalDateTime.class, new ScalarTypeLocalDateTime(mode));
        typeMap.put(OffsetDateTime.class, new ScalarTypeOffsetDateTime(mode));
        typeMap.put(ZonedDateTime.class, new ScalarTypeZonedDateTime(mode));
        typeMap.put(Instant.class, new ScalarTypeInstant(mode));
        typeMap.put(DayOfWeek.class, new ScalarTypeDayOfWeek());
        typeMap.put(Month.class, new ScalarTypeMonth());
        typeMap.put(Year.class, new ScalarTypeYear());
        typeMap.put(YearMonth.class, new ScalarTypeYearMonthDate());
        typeMap.put(MonthDay.class, new ScalarTypeMonthDay());
        typeMap.put(OffsetTime.class, new ScalarTypeOffsetTime());
        typeMap.put(ZoneId.class, new ScalarTypeZoneId());
        typeMap.put(ZoneOffset.class, new ScalarTypeZoneOffset());
        boolean localTimeNanos = config.isLocalTimeWithNanos();
        typeMap.put(java.time.LocalTime.class, (localTimeNanos) ? new ScalarTypeLocalTimeWithNanos() : new ScalarTypeLocalTime());
        boolean durationNanos = config.isDurationWithNanos();
        typeMap.put(Duration.class, (durationNanos) ? new ScalarTypeDurationWithNanos() : new ScalarTypeDuration());
    }
}
Example 17
Project: egd-web-master  File: TestUtil.java View source code
/**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);
    return mapper.writeValueAsBytes(object);
}
Example 18
Project: fixture-factory-master  File: DateTimeTransformerTest.java View source code
@Test
public void transformCalendarToOffsetDateTime() {
    Calendar value = Calendar.getInstance(TimeZone.getDefault());
    OffsetDateTime offsetDateTime = value.toInstant().atZone(ZoneId.systemDefault()).toOffsetDateTime();
    OffsetDateTime transform = new DateTimeTransformer().transform(value, OffsetDateTime.class);
    assertNotNull("OffsetDateTime should not be null", transform);
    assertEquals("OffsetDateTimes should be equal", offsetDateTime, transform);
}
Example 19
Project: jdbi-master  File: BuiltInArgumentFactory.java View source code
private static Map<Class<?>, ArgBuilder<?>> createInternalBuilders() {
    final Map<Class<?>, ArgBuilder<?>> map = new IdentityHashMap<>();
    register(map, BigDecimal.class, Types.NUMERIC, PreparedStatement::setBigDecimal);
    register(map, Blob.class, Types.BLOB, PreparedStatement::setBlob);
    register(map, Boolean.class, Types.BOOLEAN, PreparedStatement::setBoolean);
    register(map, boolean.class, Types.BOOLEAN, PreparedStatement::setBoolean);
    register(map, Byte.class, Types.TINYINT, PreparedStatement::setByte);
    register(map, byte.class, Types.TINYINT, PreparedStatement::setByte);
    register(map, byte[].class, Types.VARBINARY, PreparedStatement::setBytes);
    register(map, Character.class, Types.CHAR, stringifyValue(PreparedStatement::setString));
    register(map, char.class, Types.CHAR, stringifyValue(PreparedStatement::setString));
    register(map, Clob.class, Types.CLOB, PreparedStatement::setClob);
    register(map, Double.class, Types.DOUBLE, PreparedStatement::setDouble);
    register(map, double.class, Types.DOUBLE, PreparedStatement::setDouble);
    register(map, Float.class, Types.FLOAT, PreparedStatement::setFloat);
    register(map, float.class, Types.FLOAT, PreparedStatement::setFloat);
    register(map, Inet4Address.class, Types.OTHER, ( p,  i,  v) -> p.setString(i, v.getHostAddress()));
    register(map, Inet6Address.class, Types.OTHER, ( p,  i,  v) -> p.setString(i, v.getHostAddress()));
    register(map, Integer.class, Types.INTEGER, PreparedStatement::setInt);
    register(map, int.class, Types.INTEGER, PreparedStatement::setInt);
    register(map, java.util.Date.class, Types.TIMESTAMP, ( p,  i,  v) -> p.setTimestamp(i, new Timestamp(v.getTime())));
    register(map, Long.class, Types.INTEGER, PreparedStatement::setLong);
    register(map, long.class, Types.INTEGER, PreparedStatement::setLong);
    register(map, Short.class, Types.SMALLINT, PreparedStatement::setShort);
    register(map, short.class, Types.SMALLINT, PreparedStatement::setShort);
    register(map, java.sql.Date.class, Types.DATE, PreparedStatement::setDate);
    register(map, String.class, STR_BUILDER);
    register(map, Time.class, Types.TIME, PreparedStatement::setTime);
    register(map, Timestamp.class, Types.TIMESTAMP, PreparedStatement::setTimestamp);
    register(map, URL.class, Types.DATALINK, PreparedStatement::setURL);
    register(map, URI.class, Types.VARCHAR, stringifyValue(PreparedStatement::setString));
    register(map, UUID.class, Types.VARCHAR, PreparedStatement::setObject);
    register(map, Instant.class, Types.TIMESTAMP, ( p,  i,  v) -> p.setTimestamp(i, Timestamp.from(v)));
    register(map, LocalDate.class, Types.TIMESTAMP, ( p,  i,  v) -> p.setTimestamp(i, Timestamp.valueOf(v.atStartOfDay())));
    register(map, LocalDateTime.class, Types.TIMESTAMP, ( p,  i,  v) -> p.setTimestamp(i, Timestamp.valueOf(v)));
    register(map, OffsetDateTime.class, Types.TIMESTAMP, ( p,  i,  v) -> p.setTimestamp(i, Timestamp.from(v.toInstant())));
    register(map, ZonedDateTime.class, Types.TIMESTAMP, ( p,  i,  v) -> p.setTimestamp(i, Timestamp.from(v.toInstant())));
    register(map, LocalTime.class, Types.TIME, ( p,  i,  v) -> p.setTime(i, Time.valueOf(v)));
    return Collections.unmodifiableMap(map);
}
Example 20
Project: jhipster-neo4j-app-master  File: TestUtil.java View source code
/**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);
    return mapper.writeValueAsBytes(object);
}
Example 21
Project: keywhiz-master  File: AclDAO.java View source code
protected void allowAccess(Configuration configuration, long secretId, long groupId) {
    long now = OffsetDateTime.now().toEpochSecond();
    boolean assigned = 0 < DSL.using(configuration).fetchCount(ACCESSGRANTS, ACCESSGRANTS.SECRETID.eq(secretId).and(ACCESSGRANTS.GROUPID.eq(groupId)));
    if (assigned) {
        return;
    }
    DSL.using(configuration).insertInto(ACCESSGRANTS).set(ACCESSGRANTS.SECRETID, secretId).set(ACCESSGRANTS.GROUPID, groupId).set(ACCESSGRANTS.CREATEDAT, now).set(ACCESSGRANTS.UPDATEDAT, now).execute();
}
Example 22
Project: mongo-jackson-codec-master  File: OffsetDateTimeDeserializer.java View source code
@Override
public OffsetDateTime deserialize(BsonParser bsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    if (bsonParser.getCurrentToken() != JsonToken.VALUE_EMBEDDED_OBJECT || bsonParser.getCurrentBsonType() != BsonConstants.TYPE_DATETIME) {
        throw ctxt.mappingException(Date.class);
    }
    Object obj = bsonParser.getEmbeddedObject();
    if (obj == null) {
        return null;
    }
    Date dt = (Date) obj;
    return Instant.ofEpochMilli(dt.getTime()).atOffset(ZoneOffset.UTC);
}
Example 23
Project: muikku-master  File: WorkspaceRESTService.java View source code
private WorkspaceStudent createRestModel(UserEntity userEntity, User user, WorkspaceUser workspaceUser, boolean userArchived) {
    SchoolDataIdentifier userIdentifier = new SchoolDataIdentifier(user.getIdentifier(), user.getSchoolDataSource());
    String firstName = user.getFirstName();
    String lastName = user.getLastName();
    String studyProgrammeName = user.getStudyProgrammeName();
    OffsetDateTime enrolmentTime = workspaceUser.getEnrolmentTime();
    return new WorkspaceStudent(workspaceUser.getIdentifier().toId(), userEntity != null ? userEntity.getId() : null, userIdentifier.toId(), firstName, lastName, studyProgrammeName, enrolmentTime != null ? Date.from(enrolmentTime.toInstant()) : null, userArchived);
}
Example 24
Project: Neo4JHipster-master  File: TestUtil.java View source code
/**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);
    return mapper.writeValueAsBytes(object);
}
Example 25
Project: onos-master  File: IetfSystemManager.java View source code
@Override
public void setCurrentDatetime(OffsetDateTime date, NetconfSession session) throws NetconfException {
    String xmlQueryStr = getSetCurrentDatetimeBuilder(date);
    log.info("Sending <get> query on NETCONF session " + session.getSessionId() + ":\n" + xmlQueryStr);
    String xmlResult = session.doWrappedRpc(xmlQueryStr);
    log.info("Result from NETCONF RPC <set-current-datetime>: {}", xmlResult);
}
Example 26
Project: querydsl-master  File: SelectBase.java View source code
@Test
@ExcludeIn({ CUBRID, DB2, DERBY, HSQLDB, POSTGRESQL, SQLITE, TERADATA })
public void dates() {
    long ts = ((long) Math.floor(System.currentTimeMillis() / 1000)) * 1000;
    long tsDate = new org.joda.time.LocalDate(ts).toDateMidnight().getMillis();
    long tsTime = new org.joda.time.LocalTime(ts).getMillisOfDay();
    List<Object> data = Lists.newArrayList();
    data.add(Constants.date);
    data.add(Constants.time);
    data.add(new java.util.Date(ts));
    data.add(new java.util.Date(tsDate));
    data.add(new java.util.Date(tsTime));
    data.add(new java.sql.Timestamp(ts));
    data.add(new java.sql.Timestamp(tsDate));
    data.add(new java.sql.Date(110, 0, 1));
    data.add(new java.sql.Date(tsDate));
    data.add(new java.sql.Time(0, 0, 0));
    data.add(new java.sql.Time(12, 30, 0));
    data.add(new java.sql.Time(23, 59, 59));
    //data.add(new java.sql.Time(tsTime));
    data.add(new DateTime(ts));
    data.add(new DateTime(tsDate));
    data.add(new DateTime(tsTime));
    data.add(new LocalDateTime(ts));
    data.add(new LocalDateTime(tsDate));
    data.add(new LocalDateTime(2014, 3, 30, 2, 0));
    data.add(new LocalDate(2010, 1, 1));
    data.add(new LocalDate(ts));
    data.add(new LocalDate(tsDate));
    data.add(new LocalTime(0, 0, 0));
    data.add(new LocalTime(12, 30, 0));
    data.add(new LocalTime(23, 59, 59));
    data.add(new LocalTime(ts));
    data.add(new LocalTime(tsTime));
    java.time.Instant javaInstant = java.time.Instant.now().truncatedTo(java.time.temporal.ChronoUnit.SECONDS);
    java.time.LocalDateTime javaDateTime = java.time.LocalDateTime.ofInstant(javaInstant, java.time.ZoneId.of("Z"));
    java.time.LocalDate javaDate = javaDateTime.toLocalDate();
    java.time.LocalTime javaTime = javaDateTime.toLocalTime();
    //java.time.Instant
    data.add(javaInstant);
    //java.time.LocalDateTime
    data.add(javaDateTime);
    //java.time.LocalDate
    data.add(javaDate);
    //java.time.LocalTime
    data.add(javaTime);
    //java.time.OffsetDateTime
    data.add(javaDateTime.atOffset(java.time.ZoneOffset.UTC));
    //java.time.OffsetTime
    data.add(javaTime.atOffset(java.time.ZoneOffset.UTC));
    //java.time.ZonedDateTime
    data.add(javaDateTime.atZone(java.time.ZoneId.of("Z")));
    Map<Object, Object> failures = Maps.newIdentityHashMap();
    for (Object dt : data) {
        Object dt2 = firstResult(Expressions.constant(dt));
        if (!dt.equals(dt2)) {
            failures.put(dt, dt2);
        }
    }
    if (!failures.isEmpty()) {
        for (Map.Entry<Object, Object> entry : failures.entrySet()) {
            System.out.println(entry.getKey().getClass().getName() + ": " + entry.getKey() + " != " + entry.getValue());
        }
        Assert.fail("Failed with " + failures);
    }
}
Example 27
Project: schemas-master  File: TimeIntervalUnitTests.java View source code
@Test
public void ofStartDateTimeAndEndDateTimeShouldConstructTimeInterval() throws Exception {
    OffsetDateTime startDateTime = OffsetDateTime.now().minusDays(1);
    OffsetDateTime endDateTime = OffsetDateTime.now();
    TimeInterval timeInterval = TimeInterval.ofStartDateTimeAndEndDateTime(startDateTime, endDateTime);
    assertThat(timeInterval, notNullValue());
    assertThat(timeInterval.getStartDateTime(), equalTo(startDateTime));
    assertThat(timeInterval.getEndDateTime(), equalTo(endDateTime));
    assertThat(timeInterval.getDuration(), nullValue());
    assertThat(timeInterval.getDate(), nullValue());
    assertThat(timeInterval.getPartOfDay(), nullValue());
}
Example 28
Project: shimmer-master  File: IHealthShim.java View source code
@Override
protected ResponseEntity<ShimDataResponse> getData(OAuth2RestOperations restTemplate, ShimDataRequest shimDataRequest) throws ShimException {
    final IHealthDataTypes dataType;
    try {
        dataType = valueOf(shimDataRequest.getDataTypeKey().trim().toUpperCase());
    } catch (NullPointerExceptionIllegalArgumentException |  e) {
        throw new ShimException("Null or Invalid data type parameter: " + shimDataRequest.getDataTypeKey() + " in shimDataRequest, cannot retrieve data.");
    }
    OffsetDateTime now = OffsetDateTime.now();
    OffsetDateTime startDate = shimDataRequest.getStartDateTime() == null ? now.minusDays(1) : shimDataRequest.getStartDateTime();
    OffsetDateTime endDate = shimDataRequest.getEndDateTime() == null ? now.plusDays(1) : shimDataRequest.getEndDateTime();
    /*
            The physical activity point handles start and end datetimes differently than the other endpoints. It
            requires use to include the range until the beginning of the next day.
         */
    if (dataType == PHYSICAL_ACTIVITY) {
        endDate = endDate.plusDays(1);
    }
    // SC and SV values are client-based keys that are unique to each endpoint within a project
    String scValue = getScValue();
    List<String> svValues = getSvValues(dataType);
    List<JsonNode> responseEntities = newArrayList();
    int i = 0;
    // requests to each of these endpoints, map the responses separately and then combine them
    for (String endPoint : dataType.getEndPoint()) {
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(API_URL);
        // Need to use a dummy userId if we haven't authenticated yet. This is the case where we are using
        // getData to trigger Spring to conduct the OAuth exchange
        String userId = "uk";
        if (shimDataRequest.getAccessParameters() != null) {
            OAuth2AccessToken token = SerializationUtils.deserialize(shimDataRequest.getAccessParameters().getSerializedToken());
            userId = Preconditions.checkNotNull((String) token.getAdditionalInformation().get("UserID"));
            uriBuilder.queryParam("access_token", token.getValue());
        }
        uriBuilder.path("/user/").path(userId + "/").path(endPoint).queryParam("client_id", restTemplate.getResource().getClientId()).queryParam("client_secret", restTemplate.getResource().getClientSecret()).queryParam("start_time", startDate.toEpochSecond()).queryParam("end_time", endDate.toEpochSecond()).queryParam("locale", "default").queryParam("sc", scValue).queryParam("sv", svValues.get(i));
        ResponseEntity<JsonNode> responseEntity;
        try {
            URI url = uriBuilder.build().encode().toUri();
            responseEntity = restTemplate.getForEntity(url, JsonNode.class);
        } catch (HttpClientErrorExceptionHttpServerErrorException |  e) {
            logger.error("A request for iHealth data failed.", e);
            throw e;
        }
        if (shimDataRequest.getNormalize()) {
            IHealthDataPointMapper mapper;
            switch(dataType) {
                case PHYSICAL_ACTIVITY:
                    mapper = new IHealthPhysicalActivityDataPointMapper();
                    break;
                case BLOOD_GLUCOSE:
                    mapper = new IHealthBloodGlucoseDataPointMapper();
                    break;
                case BLOOD_PRESSURE:
                    mapper = new IHealthBloodPressureDataPointMapper();
                    break;
                case BODY_WEIGHT:
                    mapper = new IHealthBodyWeightDataPointMapper();
                    break;
                case BODY_MASS_INDEX:
                    mapper = new IHealthBodyMassIndexDataPointMapper();
                    break;
                case STEP_COUNT:
                    mapper = new IHealthStepCountDataPointMapper();
                    break;
                case SLEEP_DURATION:
                    mapper = new IHealthSleepDurationDataPointMapper();
                    break;
                case HEART_RATE:
                    // there are two different mappers for heart rate because the data can come from two endpoints
                    if (endPoint == "bp.json") {
                        mapper = new IHealthBloodPressureEndpointHeartRateDataPointMapper();
                        break;
                    } else if (endPoint == "spo2.json") {
                        mapper = new IHealthBloodOxygenEndpointHeartRateDataPointMapper();
                        break;
                    }
                case OXYGEN_SATURATION:
                    mapper = new IHealthOxygenSaturationDataPointMapper();
                    break;
                default:
                    throw new UnsupportedOperationException();
            }
            responseEntities.addAll(mapper.asDataPoints(singletonList(responseEntity.getBody())));
        } else {
            responseEntities.add(responseEntity.getBody());
        }
        i++;
    }
    return ResponseEntity.ok().body(ShimDataResponse.result(SHIM_KEY, responseEntities));
}
Example 29
Project: vert.x-master  File: VertxLoggerFormatter.java View source code
@Override
public String format(final LogRecord record) {
    OffsetDateTime date = fromMillis(record.getMillis());
    StringBuilder sb = new StringBuilder();
    // Minimize memory allocations here.
    sb.append("[").append(Thread.currentThread().getName()).append("] ");
    sb.append(date.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)).append(" ");
    sb.append(record.getLevel()).append(" [");
    sb.append(record.getLoggerName()).append("]").append("  ");
    sb.append(record.getMessage());
    sb.append(Utils.LINE_SEPARATOR);
    if (record.getThrown() != null) {
        try {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            record.getThrown().printStackTrace(pw);
            pw.close();
            sb.append(sw.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return sb.toString();
}
Example 30
Project: wonder-master  File: ERRestTest.java View source code
public void testPrimitivesToJSON() {
    NSDictionary<String, Object> dict = new NSDictionary<>("Mike", "String");
    String output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"String\":\"Mike\"}\n", output);
    dict = new NSDictionary<>(Integer.valueOf(32), "int");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"int\":32}\n", output);
    dict = new NSDictionary<>(Boolean.TRUE, "boolean");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"boolean\":true}\n", output);
    dict = new NSDictionary<>(Long.valueOf(100000000000L), "long");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"long\":100000000000}\n", output);
    dict = new NSDictionary<>(Short.valueOf((short) 100), "short");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"short\":100}\n", output);
    dict = new NSDictionary<>(Float.valueOf(100.5f), "float");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"float\":100.5}\n", output);
    dict = new NSDictionary<>(Double.valueOf(100.5), "double");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"double\":100.5}\n", output);
    dict = new NSDictionary<>(new NSTimestamp(1301584117085L), "timestamp");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"timestamp\":\"2011-03-31T15:08:37Z\"}\n", output);
    dict = new NSDictionary<>(new Date(1301584117085L), "date");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"date\":\"2011-03-31T15:08:37Z\"}\n", output);
    dict = new NSDictionary<>(NSKeyValueCoding.NullValue, "nullValue");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"nullValue\":null}\n", output);
    dict = new NSDictionary<>(LocalDate.of(2016, Month.AUGUST, 1), "localDate");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"localDate\":\"2016-08-01\"}\n", output);
    dict = new NSDictionary<>(LocalDateTime.of(2016, Month.AUGUST, 1, 12, 5, 8), "localDateTime");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"localDateTime\":\"2016-08-01T12:05:08\"}\n", output);
    dict = new NSDictionary<>(LocalTime.of(12, 5, 8), "localTime");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"localTime\":\"12:05:08\"}\n", output);
    dict = new NSDictionary<>(OffsetDateTime.of(2016, 8, 1, 12, 5, 8, 0, ZoneOffset.UTC), "offsetDateTime");
    output = ERXRestFormat.json().toString(dict);
    assertEquals("{\"offsetDateTime\":\"2016-08-01T12:05:08Z\"}\n", output);
}
Example 31
Project: avaje-ebeanorm-examples-master  File: CustomerFindVersions.java View source code
@Ignore
@Test
public void oracle_findVersionsBetween() throws SQLException {
    LoggedSql.start();
    long epochStart = OffsetDateTime.now().minusMinutes(250).toInstant().toEpochMilli();
    Timestamp start = new Timestamp(epochStart);
    long epochEnd = OffsetDateTime.now().minusMinutes(3).toInstant().toEpochMilli();
    Timestamp end = new Timestamp(epochEnd);
    List<Version<Customer>> customerVersions = Customer.find.query().where().idEq(21).findVersionsBetween(start, end);
    for (Version<Customer> customerVersion : customerVersions) {
        Customer bean = customerVersion.getBean();
        Map<String, ValuePair> diff = customerVersion.getDiff();
        Timestamp effectiveStart = customerVersion.getStart();
        Timestamp effectiveEnd = customerVersion.getEnd();
        assertThat(bean).isNotNull();
        assertThat(diff).isNotNull();
        assertThat(effectiveStart).isNotNull();
    //assertThat(effectiveEnd).isNotNull();
    }
    List<String> loggedSql = LoggedSql.stop();
    assertThat(loggedSql).hasSize(1);
    assertThat(customerVersions).isNotNull();
    String sqlSelect = loggedSql.get(0);
    // select clause prefixed with lower and upper bounds
    assertThat(sqlSelect.contains("select versions_starttime c0, versions_endtime c1,")).isTrue();
    // from the with_history view
    assertThat(sqlSelect.contains(" from customer versions between timestamp ? and ? t0 where t0.id = ?")).isTrue();
    // appends order by lower bound desc
    assertThat(sqlSelect.contains(" order by t0.id, versions_starttime desc")).isTrue();
}
Example 32
Project: avaje-ebeanorm-master  File: CustomerFindVersions.java View source code
@Ignore
@Test
public void oracle_findVersionsBetween() throws SQLException {
    LoggedSql.start();
    long epochStart = OffsetDateTime.now().minusMinutes(250).toInstant().toEpochMilli();
    Timestamp start = new Timestamp(epochStart);
    long epochEnd = OffsetDateTime.now().minusMinutes(3).toInstant().toEpochMilli();
    Timestamp end = new Timestamp(epochEnd);
    List<Version<Customer>> customerVersions = Customer.find.query().where().idEq(21).findVersionsBetween(start, end);
    for (Version<Customer> customerVersion : customerVersions) {
        Customer bean = customerVersion.getBean();
        Map<String, ValuePair> diff = customerVersion.getDiff();
        Timestamp effectiveStart = customerVersion.getStart();
        Timestamp effectiveEnd = customerVersion.getEnd();
        assertThat(bean).isNotNull();
        assertThat(diff).isNotNull();
        assertThat(effectiveStart).isNotNull();
    //assertThat(effectiveEnd).isNotNull();
    }
    List<String> loggedSql = LoggedSql.stop();
    assertThat(loggedSql).hasSize(1);
    assertThat(customerVersions).isNotNull();
    String sqlSelect = loggedSql.get(0);
    // select clause prefixed with lower and upper bounds
    assertThat(sqlSelect.contains("select versions_starttime c0, versions_endtime c1,")).isTrue();
    // from the with_history view
    assertThat(sqlSelect.contains(" from customer versions between timestamp ? and ? t0 where t0.id = ?")).isTrue();
    // appends order by lower bound desc
    assertThat(sqlSelect.contains(" order by t0.id, versions_starttime desc")).isTrue();
}
Example 33
Project: hibernate-orm-master  File: CriteriaQueryTypeQueryAdapter.java View source code
@Override
public QueryImplementor<X> setParameter(Parameter<OffsetDateTime> param, OffsetDateTime value, TemporalType temporalType) {
    final ExplicitParameterInfo parameterInfo = resolveParameterInfo(param);
    if (parameterInfo.isNamed()) {
        jpqlQuery.setParameter(parameterInfo.getName(), value, temporalType);
    } else {
        jpqlQuery.setParameter(parameterInfo.getPosition(), value, temporalType);
    }
    return this;
}
Example 34
Project: jadira-master  File: TimestampColumnOffsetTimeMapper.java View source code
@Override
public OffsetTime fromNonNullValue(Timestamp value) {
    ZoneId currentDatabaseZone = getDatabaseZone() == null ? getDefaultZoneOffset() : getDatabaseZone();
    ZoneId currentJavaZone = javaZone == null ? getDefaultZoneOffset() : javaZone;
    OffsetDateTime dateTime = OffsetDateTime.ofInstant(Instant.ofEpochMilli(value.getTime()), currentDatabaseZone);
    dateTime = dateTime.with(ChronoField.NANO_OF_SECOND, value.getNanos()).atZoneSameInstant(currentJavaZone).toOffsetDateTime();
    OffsetTime time = dateTime.toOffsetTime();
    return time;
}
Example 35
Project: javacuriosities-master  File: Lesson05TimeZoneAndOffsetClasses.java View source code
public static void main(String[] args) throws Exception {
    LocalDateTime currentLocalDateTime = LocalDateTime.now();
    Set<String> allZones = ZoneId.getAvailableZoneIds();
    List<String> zoneList = new ArrayList<String>(allZones);
    Collections.sort(zoneList);
    System.out.println("Original: " + currentLocalDateTime);
    for (String zone : zoneList) {
        ZoneId zoneId = ZoneId.of(zone);
        ZonedDateTime zonedDateTime = currentLocalDateTime.atZone(zoneId);
        ZoneOffset offset = zonedDateTime.getOffset();
        if (offset.getTotalSeconds() != 0) {
            System.out.println(offset + " -> " + zonedDateTime);
        }
    }
    // ZonedDateTime
    LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
    ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
    ZonedDateTime departureFlight = ZonedDateTime.of(leaving, leavingZone);
    // El vuelo dura 10 horas y 50 minutos, el total es 650 minutos
    ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
    ZonedDateTime arrivalFlight = departureFlight.withZoneSameInstant(arrivingZone).plusMinutes(650);
    System.out.println("Departure at America/Los_Angeles: " + departureFlight);
    System.out.println("Current Time at Asia/Tokyo: " + departureFlight.withZoneSameInstant(arrivingZone));
    System.out.println("Arrival: " + arrivalFlight);
    // OffsetDateTime
    LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
    ZoneOffset offset = ZoneOffset.of("-08:00");
    OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
    System.out.println("Date based on offset: " + offsetDate);
}
Example 36
Project: junit5-master  File: DefaultArgumentConverterTests.java View source code
@Test
void convertsStringsToJavaTimeInstances() {
    assertConverts("1970-01-01T00:00:00Z", Instant.class, Instant.ofEpochMilli(0));
    assertConverts("2017-03-14", LocalDate.class, LocalDate.of(2017, 3, 14));
    assertConverts("2017-03-14T12:34:56.789", LocalDateTime.class, LocalDateTime.of(2017, 3, 14, 12, 34, 56, 789_000_000));
    assertConverts("12:34:56.789", LocalTime.class, LocalTime.of(12, 34, 56, 789_000_000));
    assertConverts("2017-03-14T12:34:56.789Z", OffsetDateTime.class, OffsetDateTime.of(2017, 3, 14, 12, 34, 56, 789_000_000, ZoneOffset.UTC));
    assertConverts("12:34:56.789Z", OffsetTime.class, OffsetTime.of(12, 34, 56, 789_000_000, ZoneOffset.UTC));
    assertConverts("2017", Year.class, Year.of(2017));
    assertConverts("2017-03", YearMonth.class, YearMonth.of(2017, 3));
    assertConverts("2017-03-14T12:34:56.789Z", ZonedDateTime.class, ZonedDateTime.of(2017, 3, 14, 12, 34, 56, 789_000_000, ZoneOffset.UTC));
}
Example 37
Project: mybatis-3-master  File: Jsr310TypeHandlerRegistryTest.java View source code
@Test
public void testFor_v1_0_0() throws ClassNotFoundException {
    assertThat(getTypeHandler("java.time.Instant")).isInstanceOf(InstantTypeHandler.class);
    assertThat(getTypeHandler("java.time.LocalDateTime")).isInstanceOf(LocalDateTimeTypeHandler.class);
    assertThat(getTypeHandler("java.time.LocalDate")).isInstanceOf(LocalDateTypeHandler.class);
    assertThat(getTypeHandler("java.time.LocalTime")).isInstanceOf(LocalTimeTypeHandler.class);
    assertThat(getTypeHandler("java.time.OffsetDateTime")).isInstanceOf(OffsetDateTimeTypeHandler.class);
    assertThat(getTypeHandler("java.time.OffsetTime")).isInstanceOf(OffsetTimeTypeHandler.class);
    assertThat(getTypeHandler("java.time.ZonedDateTime")).isInstanceOf(ZonedDateTimeTypeHandler.class);
}
Example 38
Project: omh-dsu-ri-master  File: DataPointController.java View source code
/**
     * Reads data points.
     *
     * @param schemaNamespace the namespace of the schema the data points conform to
     * @param schemaName the name of the schema the data points conform to
     * @param schemaVersion the version of the schema the data points conform to
     * @param createdOnOrAfter the earliest creation timestamp of the data points to return, inclusive
     * @param createdBefore the latest creation timestamp of the data points to return, exclusive
     * @param offset the number of data points to skip
     * @param limit the number of data points to return
     * @return a list of matching data points
     */
// TODO confirm if HEAD handling needs anything additional
// only allow clients with read scope to read data points
@PreAuthorize("#oauth2.clientHasRole('" + CLIENT_ROLE + "') and #oauth2.hasScope('" + DATA_POINT_READ_SCOPE + "')")
// TODO look into any meaningful @PostAuthorize filtering
@RequestMapping(value = "/dataPoints", method = { HEAD, GET }, produces = APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Iterable<DataPoint>> readDataPoints(@RequestParam(value = SCHEMA_NAMESPACE_PARAMETER) final String schemaNamespace, @RequestParam(value = SCHEMA_NAME_PARAMETER) final String schemaName, // TODO make this optional and update all associated code
@RequestParam(value = SCHEMA_VERSION_PARAMETER) final String schemaVersion, // TODO replace with Optional<> in Spring MVC 4.1
@RequestParam(value = CREATED_ON_OR_AFTER_PARAMETER, required = false) final OffsetDateTime createdOnOrAfter, @RequestParam(value = CREATED_BEFORE_PARAMETER, required = false) final OffsetDateTime createdBefore, @RequestParam(value = RESULT_OFFSET_PARAMETER, defaultValue = "0") final Integer offset, @RequestParam(value = RESULT_LIMIT_PARAMETER, defaultValue = DEFAULT_RESULT_LIMIT) final Integer limit, Authentication authentication) {
    // TODO add validation or explicitly comment that this is handled using exception translators
    // determine the user associated with the access token to restrict the search accordingly
    String endUserId = getEndUserId(authentication);
    DataPointSearchCriteria searchCriteria = new DataPointSearchCriteria(endUserId, schemaNamespace, schemaName, schemaVersion);
    if (createdOnOrAfter != null && createdBefore != null) {
        searchCriteria.setCreationTimestampRange(Range.closedOpen(createdOnOrAfter, createdBefore));
    } else if (createdOnOrAfter != null) {
        searchCriteria.setCreationTimestampRange(Range.atLeast(createdOnOrAfter));
    } else if (createdBefore != null) {
        searchCriteria.setCreationTimestampRange(Range.lessThan(createdBefore));
    }
    Iterable<DataPoint> dataPoints = dataPointService.findBySearchCriteria(searchCriteria, offset, limit);
    HttpHeaders headers = new HttpHeaders();
    return new ResponseEntity<>(dataPoints, headers, OK);
}
Example 39
Project: sample-data-generator-master  File: AbstractDataPointGeneratorImpl.java View source code
/**
     * @param measure a measure
     * @return a data point corresponding to the specified measure
     */
public DataPoint<T> newDataPoint(T measure) {
    TimeInterval effectiveTimeInterval = measure.getEffectiveTimeFrame().getTimeInterval();
    OffsetDateTime effectiveEndDateTime;
    if (effectiveTimeInterval != null) {
        if (effectiveTimeInterval.getEndDateTime() != null) {
            effectiveEndDateTime = effectiveTimeInterval.getEndDateTime();
        } else {
            // use the duration to calculate the end date time of the interval
            if (effectiveTimeInterval.getDuration() != null) {
                BiFunction<OffsetDateTime, Long, OffsetDateTime> plusFunction;
                switch(effectiveTimeInterval.getDuration().getTypedUnit()) {
                    case SECOND:
                        plusFunction = OffsetDateTime::plusSeconds;
                        break;
                    case MINUTE:
                        plusFunction = OffsetDateTime::plusMinutes;
                        break;
                    case HOUR:
                        plusFunction = OffsetDateTime::plusHours;
                        break;
                    case DAY:
                        plusFunction = OffsetDateTime::plusDays;
                        break;
                    case WEEK:
                        plusFunction = OffsetDateTime::plusWeeks;
                        break;
                    case MONTH:
                        plusFunction = OffsetDateTime::plusMonths;
                        break;
                    case YEAR:
                        plusFunction = OffsetDateTime::plusYears;
                        break;
                    default:
                        throw new IllegalStateException("A time interval duration type isn't supported.");
                }
                effectiveEndDateTime = plusFunction.apply(effectiveTimeInterval.getStartDateTime(), effectiveTimeInterval.getDuration().getValue().longValue());
            } else {
                throw new IllegalStateException("An end date time can't be calculated without a duration.");
            }
        }
    } else {
        // if this is a point in time measure
        effectiveEndDateTime = measure.getEffectiveTimeFrame().getDateTime();
    }
    DataPointAcquisitionProvenance acquisitionProvenance = new DataPointAcquisitionProvenance.Builder(sourceName).setModality(SENSED).setSourceCreationDateTime(effectiveEndDateTime).build();
    DataPointHeader header = new DataPointHeader.Builder(randomUUID().toString(), measure.getSchemaId(), effectiveEndDateTime.plusMinutes(1)).setAcquisitionProvenance(acquisitionProvenance).setUserId(userId).build();
    return new DataPoint<>(header, measure);
}
Example 40
Project: avaje-ebeanorm-typequery-master  File: PropertyTypeMap.java View source code
private void addJava8Types() {
    try {
        Class.forName("java.time.Instant");
    } catch (ClassNotFoundException e) {
        return;
    }
    addType(java.time.DayOfWeek.class);
    addType(java.time.Duration.class);
    addType(java.time.Instant.class);
    addType(java.time.LocalDate.class);
    addType(java.time.LocalDateTime.class);
    addType(java.time.LocalTime.class);
    addType(java.time.Month.class);
    addType(java.time.MonthDay.class);
    addType(java.time.OffsetDateTime.class);
    addType(java.time.OffsetTime.class);
    addType(java.time.Year.class);
    addType(java.time.YearMonth.class);
    addType(java.time.ZoneId.class);
    addType(java.time.ZoneOffset.class);
}
Example 41
Project: bonita-ui-designer-master  File: ContractDeserializerTest.java View source code
@Test
public void deserialize_a_serialized_contract_json_document_into_a_contract_object() throws Exception {
    Contract aSimpleContract = aSimpleContract();
    byte[] serializedContract = new ObjectMapper().writeValueAsBytes(aSimpleContract);
    ContractDeserializer contractDeserializer = new ContractDeserializer();
    Contract contract = contractDeserializer.deserialize(new JsonFactory(new ObjectMapper()).createParser(serializedContract), null);
    assertThat(contract.getInput()).extracting("name", "type").containsExactly(tuple("name", String.class.getName()), tuple("isValid", Boolean.class.getName()), tuple("ticket", NodeContractInput.class.getName()));
    assertThat(find(contract.getInput(), instanceOf(NodeContractInput.class)).getInput()).extracting("name", "type").containsExactly(tuple("title", String.class.getName()), tuple("creationDate", Date.class.getName()), tuple("creationLocalDate", LocalDate.class.getName()), tuple("creationLocalDateTime", LocalDateTime.class.getName()), tuple("creationOffsetDateTime", OffsetDateTime.class.getName()), tuple("updateTime", Long.class.getName()));
}
Example 42
Project: clc-java-sdk-master  File: GroupMonitoringStatsBy.java View source code
@SuppressWarnings("unchecked")
protected List<MonitoringStatsEntry> aggregate(List<MonitoringStatsEntry> plainEntries) {
    return plainEntries.stream().map( entry -> {
        List<OffsetDateTime> timestamps = ((List<OffsetDateTime>) entry.getStatistics().stream().map( e -> ((MonitoringEntry) e).getTimestamp()).distinct().collect(toList()));
        List<MonitoringEntry> resultEntries = timestamps.stream().map( time -> aggregateMonitoringEntry(entry, time)).collect(toList());
        return new MonitoringStatsEntry(entry.getEntity(), resultEntries);
    }).collect(toList());
}
Example 43
Project: datacollector-master  File: TestSyslogDecoder.java View source code
@Test
public void testRfc5424DateParsing() throws Exception {
    final String[] examples = { "1985-04-12T23:20:50.52Z", "1985-04-12T19:20:50.52-04:00", "2003-10-11T22:14:15.003Z", "2003-08-24T05:14:15.000003-07:00", "2012-04-13T11:11:11-08:00", "2012-04-13T08:08:08.0001+00:00", "2012-04-13T08:08:08.251+00:00" };
    SyslogDecoder decoder = new SyslogDecoder(StandardCharsets.UTF_8, getSystemClock());
    DateTimeFormatter parser = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    for (String example : examples) {
        assertEquals("Problem parsing date string: " + example, OffsetDateTime.parse(example, parser).toInstant().toEpochMilli(), decoder.parseRfc5424Date(example));
    }
}
Example 44
Project: felix-master  File: ConverterImpl.java View source code
public void addStandardRules(ConverterBuilder cb) {
    cb.rule(new Rule<Calendar, String>( f -> f.getTime().toInstant().toString()) {
    });
    cb.rule(new Rule<String, Calendar>( f -> {
        Calendar cc = Calendar.getInstance();
        cc.setTime(Date.from(Instant.parse(f)));
        return cc;
    }) {
    });
    cb.rule(new Rule<Calendar, Long>( f -> f.getTime().getTime()) {
    });
    cb.rule(new Rule<Long, Calendar>( f -> new Calendar.Builder().setInstant(f).build()) {
    });
    cb.rule(new Rule<Character, Boolean>( c -> c.charValue() != 0) {
    });
    cb.rule(new Rule<Boolean, Character>( b -> b.booleanValue() ? (char) 1 : (char) 0) {
    });
    cb.rule(new Rule<String, Character>( f -> f.length() > 0 ? f.charAt(0) : 0) {
    });
    cb.rule(new Rule<String, Class<?>>(this::loadClassUnchecked) {
    });
    cb.rule(new Rule<Date, Long>(Date::getTime) {
    });
    cb.rule(new Rule<Long, Date>( f -> new Date(f)) {
    });
    cb.rule(new Rule<Date, String>( f -> f.toInstant().toString()) {
    });
    cb.rule(new Rule<String, Date>( f -> Date.from(Instant.parse(f))) {
    });
    cb.rule(new Rule<String, LocalDateTime>(LocalDateTime::parse) {
    });
    cb.rule(new Rule<String, LocalDate>(LocalDate::parse) {
    });
    cb.rule(new Rule<String, LocalTime>(LocalTime::parse) {
    });
    cb.rule(new Rule<String, OffsetDateTime>(OffsetDateTime::parse) {
    });
    cb.rule(new Rule<String, OffsetTime>(OffsetTime::parse) {
    });
    cb.rule(new Rule<String, Pattern>(Pattern::compile) {
    });
    cb.rule(new Rule<String, UUID>(UUID::fromString) {
    });
    cb.rule(new Rule<String, ZonedDateTime>(ZonedDateTime::parse) {
    });
}
Example 45
Project: hibernate-search-master  File: ElasticsearchIndexNullAsIT.java View source code
@Test
public void testOffsetDateTime() throws Exception {
    /* Elasticsearch only accepts years in the range [-292275054,292278993]
		 */
    OffsetDateTime value = OffsetDateTime.of(221998, Month.FEBRUARY.getValue(), 12, 13, 05, 33, 7, ZoneOffset.of("+01:00"));
    Sample sample = new Sample(1L, "OffsetDateTime example");
    sample.offsetDateTime = value;
    assertNullFieldIndexingAndQuerying("offsetDateTime", value, sample);
}
Example 46
Project: jackson-datatype-jsr310-master  File: TestOffsetDateTimeSerialization.java View source code
@Test
public void testSerializationAsTimestamp01Nanoseconds() throws Exception {
    OffsetDateTime date = OffsetDateTime.ofInstant(Instant.ofEpochSecond(0L), Z1);
    String value = MAPPER.writer().with(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).with(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS).writeValueAsString(date);
    assertEquals("The value is not correct.", "0.0", value);
}
Example 47
Project: jBloomberg-master  File: BloombergUtilsTest.java View source code
/**
     * We simply ignore the data type as it may be wrong. Instead check on the parts that are present in the Datetime object.
     */
@Test(groups = "unit", dataProvider = "datatypes")
public void getSpecificObjectOf_dates(Schema.Datatype datatype) {
    Element mockElement;
    mockElement = new MockUp<Element>() {

        @Mock
        public Schema.Datatype datatype() {
            return datatype;
        }

        @Mock
        public Datetime getValueAsDatetime() {
            return new Datetime(2017, 1, 1);
        }
    }.getMockInstance();
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement).getClass(), LocalDate.class);
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement), LocalDate.of(2017, 1, 1));
    mockElement = new MockUp<Element>() {

        @Mock
        public Schema.Datatype datatype() {
            return datatype;
        }

        @Mock
        public Datetime getValueAsDatetime() {
            return new Datetime(2017, 1, 1, 13, 0, 0, 0);
        }
    }.getMockInstance();
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement).getClass(), OffsetDateTime.class);
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement), OffsetDateTime.of(2017, 1, 1, 13, 0, 0, 0, ZoneOffset.UTC));
    mockElement = new MockUp<Element>() {

        @Mock
        public Schema.Datatype datatype() {
            return datatype;
        }

        @Mock
        public Datetime getValueAsDatetime() {
            Datetime dt = new Datetime(2017, 1, 1, 13, 0, 0, 0);
            dt.setTimezoneOffsetMinutes(60);
            return dt;
        }
    }.getMockInstance();
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement).getClass(), OffsetDateTime.class);
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement), OffsetDateTime.of(2017, 1, 1, 13, 0, 0, 0, ZoneOffset.ofHours(1)));
    mockElement = new MockUp<Element>() {

        @Mock
        public Schema.Datatype datatype() {
            return datatype;
        }

        @Mock
        public Datetime getValueAsDatetime() {
            Datetime dt = new Datetime(13, 0, 0, 0);
            return dt;
        }
    }.getMockInstance();
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement).getClass(), OffsetTime.class);
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement), OffsetTime.of(13, 0, 0, 0, ZoneOffset.UTC));
    mockElement = new MockUp<Element>() {

        @Mock
        public Schema.Datatype datatype() {
            return datatype;
        }

        @Mock
        public Datetime getValueAsDatetime() {
            Datetime dt = new Datetime(13, 0, 0, 0);
            dt.setTimezoneOffsetMinutes(60);
            return dt;
        }
    }.getMockInstance();
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement).getClass(), OffsetTime.class);
    assertEquals(BloombergUtils.getSpecificObjectOf(mockElement), OffsetTime.of(13, 0, 0, 0, ZoneOffset.ofHours(1)));
}
Example 48
Project: jbpm-master  File: IntermediateEventTest.java View source code
@Test(timeout = 10000)
public void testTimerBoundaryEventDateISO() throws Exception {
    CountDownProcessEventListener countDownListener = new CountDownProcessEventListener("TimerEvent", 1);
    KieBase kbase = createKnowledgeBaseWithoutDumper("BPMN2-TimerBoundaryEventDateISO.bpmn2");
    ksession = createKnowledgeSession(kbase);
    ksession.addEventListener(countDownListener);
    ksession.getWorkItemManager().registerWorkItemHandler("MyTask", new DoNothingWorkItemHandler());
    HashMap<String, Object> params = new HashMap<String, Object>();
    OffsetDateTime plusTwoSeconds = OffsetDateTime.now().plusSeconds(2);
    params.put("date", plusTwoSeconds.toString());
    ProcessInstance processInstance = ksession.startProcess("TimerBoundaryEvent", params);
    assertProcessInstanceActive(processInstance);
    countDownListener.waitTillCompleted();
    ksession = restoreSession(ksession, true);
    assertProcessInstanceFinished(processInstance, ksession);
}
Example 49
Project: junit-quickcheck-master  File: OffsetDateTimePropertyParameterTypesTest.java View source code
@Property
public void shouldHold(@InRange(min = "01/01/2012T00:00:00.0+01:00", max = "12/31/2012T23:59:59.999999999+01:00", format = "MM/dd/yyyy'T'HH:mm:ss.nxxx") OffsetDateTime t) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy'T'HH:mm:ss.nxxx");
    assertThat(t, allOf(greaterThanOrEqualTo(OffsetDateTime.parse("01/01/2012T00:00:00.0+01:00", formatter)), lessThanOrEqualTo(OffsetDateTime.parse("12/31/2012T23:59:59.999999999+01:00", formatter))));
}
Example 50
Project: mybatis-java-time-master  File: TimeTest.java View source code
@Test(priority = 1, dataProvider = "date")
public void dateGet(long id, LocalDateTime localdt, OffsetDateTime offsetdt, ZonedDateTime zoneddt) {
    TimeRow row = mapper.get(id);
    if (id % 10 == 0) {
        assertThat(row.getLocaldt()).isNull();
        assertThat(row.getOffsetdt()).isNull();
        assertThat(row.getZoneddt()).isNull();
    } else {
        assertThat(row.getLocaldt()).isEqualTo(localdt);
        assertThat(row.getOffsetdt().isEqual(offsetdt)).isTrue();
        assertThat(row.getZoneddt().isEqual(zoneddt)).isTrue();
    }
}
Example 51
Project: OpenTripPlanner-master  File: SegmentSpeedSample.java View source code
/** Get a speed estimate in meters per second for the time specified (in milliseconds since the epoch) */
public double getSpeed(long time) {
    if (hourBins == null)
        return decodeSpeed(average);
    // figure out the hour bin
    Instant instant = Instant.ofEpochMilli(time);
    OffsetDateTime dt = instant.atOffset(ZoneOffset.UTC);
    // 0 (Monday) to 6 (Sunday) after subtraction
    int day = DayOfWeek.from(dt).getValue() - 1;
    int hour = dt.getHour();
    int hourBin = day * 24 + hour;
    return decodeSpeed(hourBins[hourBin]);
}
Example 52
Project: optaplanner-master  File: DefaultPlannerBenchmark.java View source code
public void benchmarkingStarted() {
    if (startingSystemTimeMillis >= 0L) {
        throw new IllegalStateException("This benchmark has already ran before.");
    }
    startingSystemTimeMillis = System.currentTimeMillis();
    plannerBenchmarkResult.setStartingTimestamp(OffsetDateTime.now());
    List<SolverBenchmarkResult> solverBenchmarkResultList = plannerBenchmarkResult.getSolverBenchmarkResultList();
    if (ConfigUtils.isEmptyCollection(solverBenchmarkResultList)) {
        throw new IllegalArgumentException("The solverBenchmarkResultList (" + solverBenchmarkResultList + ") cannot be empty.");
    }
    initBenchmarkDirectoryAndSubdirectories();
    plannerBenchmarkResult.initSystemProperties();
    logger.info("Benchmarking started: parallelBenchmarkCount ({})" + " for problemCount ({}), solverCount ({}), totalSubSingleCount ({}).", plannerBenchmarkResult.getParallelBenchmarkCount(), plannerBenchmarkResult.getUnifiedProblemBenchmarkResultList().size(), solverBenchmarkResultList.size(), plannerBenchmarkResult.getTotalSubSingleCount());
}
Example 53
Project: pgjdbc-master  File: PgResultSet.java View source code
public <T> T getObject(int columnIndex, Class<T> type) throws SQLException {
    if (type == null) {
        throw new SQLException("type is null");
    }
    int sqlType = getSQLType(columnIndex);
    if (type == BigDecimal.class) {
        if (sqlType == Types.NUMERIC || sqlType == Types.DECIMAL) {
            return type.cast(getBigDecimal(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == String.class) {
        if (sqlType == Types.CHAR || sqlType == Types.VARCHAR) {
            return type.cast(getString(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Boolean.class) {
        if (sqlType == Types.BOOLEAN || sqlType == Types.BIT) {
            boolean booleanValue = getBoolean(columnIndex);
            if (wasNull()) {
                return null;
            }
            return type.cast(booleanValue);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Integer.class) {
        if (sqlType == Types.SMALLINT || sqlType == Types.INTEGER) {
            int intValue = getInt(columnIndex);
            if (wasNull()) {
                return null;
            }
            return type.cast(intValue);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Long.class) {
        if (sqlType == Types.BIGINT) {
            long longValue = getLong(columnIndex);
            if (wasNull()) {
                return null;
            }
            return type.cast(longValue);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Float.class) {
        if (sqlType == Types.REAL) {
            float floatValue = getFloat(columnIndex);
            if (wasNull()) {
                return null;
            }
            return type.cast(floatValue);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Double.class) {
        if (sqlType == Types.FLOAT || sqlType == Types.DOUBLE) {
            double doubleValue = getDouble(columnIndex);
            if (wasNull()) {
                return null;
            }
            return type.cast(doubleValue);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Date.class) {
        if (sqlType == Types.DATE) {
            return type.cast(getDate(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Time.class) {
        if (sqlType == Types.TIME) {
            return type.cast(getTime(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Timestamp.class) {
        if (sqlType == Types.TIMESTAMP || //#if mvn.project.property.postgresql.jdbc.spec >= "JDBC4.2"
        sqlType == Types.TIMESTAMP_WITH_TIMEZONE) //#endif
        {
            return type.cast(getTimestamp(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Calendar.class) {
        if (sqlType == Types.TIMESTAMP || //#if mvn.project.property.postgresql.jdbc.spec >= "JDBC4.2"
        sqlType == Types.TIMESTAMP_WITH_TIMEZONE) //#endif
        {
            Timestamp timestampValue = getTimestamp(columnIndex);
            Calendar calendar = Calendar.getInstance(getDefaultCalendar().getTimeZone());
            calendar.setTimeInMillis(timestampValue.getTime());
            return type.cast(calendar);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Blob.class) {
        if (sqlType == Types.BLOB || sqlType == Types.BINARY || sqlType == Types.BIGINT) {
            return type.cast(getBlob(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Clob.class) {
        if (sqlType == Types.CLOB || sqlType == Types.BIGINT) {
            return type.cast(getClob(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == NClob.class) {
        if (sqlType == Types.NCLOB) {
            return type.cast(getNClob(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == Array.class) {
        if (sqlType == Types.ARRAY) {
            return type.cast(getArray(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == SQLXML.class) {
        if (sqlType == Types.SQLXML) {
            return type.cast(getSQLXML(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == UUID.class) {
        return type.cast(getObject(columnIndex));
    } else if (type == InetAddress.class) {
        Object addressString = getObject(columnIndex);
        if (addressString == null) {
            return null;
        }
        try {
            return type.cast(InetAddress.getByName(((PGobject) addressString).getValue()));
        } catch (UnknownHostException e) {
            throw new SQLException("could not create inet address from string '" + addressString + "'");
        }
    // JSR-310 support
    //#if mvn.project.property.postgresql.jdbc.spec >= "JDBC4.2"
    } else if (type == LocalDate.class) {
        if (sqlType == Types.DATE) {
            Date dateValue = getDate(columnIndex);
            if (wasNull()) {
                return null;
            }
            long time = dateValue.getTime();
            if (time == PGStatement.DATE_POSITIVE_INFINITY) {
                return type.cast(LocalDate.MAX);
            }
            if (time == PGStatement.DATE_NEGATIVE_INFINITY) {
                return type.cast(LocalDate.MIN);
            }
            return type.cast(dateValue.toLocalDate());
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == LocalTime.class) {
        if (sqlType == Types.TIME) {
            return type.cast(getLocalTime(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == LocalDateTime.class) {
        if (sqlType == Types.TIMESTAMP) {
            return type.cast(getLocalDateTime(columnIndex));
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    } else if (type == OffsetDateTime.class) {
        if (sqlType == Types.TIMESTAMP_WITH_TIMEZONE || sqlType == Types.TIMESTAMP) {
            Timestamp timestampValue = getTimestamp(columnIndex);
            if (wasNull()) {
                return null;
            }
            long time = timestampValue.getTime();
            if (time == PGStatement.DATE_POSITIVE_INFINITY) {
                return type.cast(OffsetDateTime.MAX);
            }
            if (time == PGStatement.DATE_NEGATIVE_INFINITY) {
                return type.cast(OffsetDateTime.MIN);
            }
            // Postgres stores everything in UTC and does not keep original time zone
            OffsetDateTime offsetDateTime = OffsetDateTime.ofInstant(timestampValue.toInstant(), ZoneOffset.UTC);
            return type.cast(offsetDateTime);
        } else {
            throw new SQLException("conversion to " + type + " from " + sqlType + " not supported");
        }
    //#endif
    } else if (PGobject.class.isAssignableFrom(type)) {
        Object object;
        if (isBinary(columnIndex)) {
            object = connection.getObject(getPGType(columnIndex), null, this_row[columnIndex - 1]);
        } else {
            object = connection.getObject(getPGType(columnIndex), getString(columnIndex), null);
        }
        return type.cast(object);
    }
    throw new SQLException("unsupported conversion to " + type);
}
Example 54
Project: Planner-master  File: SegmentSpeedSample.java View source code
/** Get a speed estimate in meters per second for the time specified (in milliseconds since the epoch) */
public double getSpeed(long time) {
    if (hourBins == null)
        return decodeSpeed(average);
    // figure out the hour bin
    Instant instant = Instant.ofEpochMilli(time);
    OffsetDateTime dt = instant.atOffset(ZoneOffset.UTC);
    // 0 (Monday) to 6 (Sunday) after subtraction
    int day = DayOfWeek.from(dt).getValue() - 1;
    int hour = dt.getHour();
    int hourBin = day * 24 + hour;
    return decodeSpeed(hourBins[hourBin]);
}
Example 55
Project: requery-master  File: TimeConversionsTest.java View source code
@Test
public void testInsertReadDateTime() {
    Event event = new Event();
    UUID id = UUID.randomUUID();
    LocalDateTime localDateTimeNow = LocalDateTime.now().withNano(0);
    OffsetDateTime offsetDateTimeNow = OffsetDateTime.now(ZoneId.systemDefault()).withNano(0);
    ZonedDateTime zonedDateTimeNow = ZonedDateTime.now(ZoneId.systemDefault()).withNano(0);
    event.setId(id);
    event.setLocalDateTime(localDateTimeNow);
    event.setOffsetDateTime(offsetDateTimeNow);
    event.setZonedDateTime(zonedDateTimeNow);
    data.insert(event);
    event = data.findByKey(Event.class, id);
    Assert.assertEquals(localDateTimeNow, event.getLocalDateTime());
    Assert.assertEquals(offsetDateTimeNow, event.getOffsetDateTime());
    Assert.assertEquals(zonedDateTimeNow.toInstant(), event.getZonedDateTime().toInstant());
}
Example 56
Project: hibernate-semantic-query-master  File: OffsetTimeJavaDescriptor.java View source code
@Override
public <X> OffsetTime wrap(X value, WrapperOptions options) {
    if (value == null) {
        return null;
    }
    if (OffsetTime.class.isInstance(value)) {
        return (OffsetTime) value;
    }
    if (Time.class.isInstance(value)) {
        return ((Time) value).toLocalTime().atOffset(OffsetDateTime.now().getOffset());
    }
    if (Timestamp.class.isInstance(value)) {
        final Timestamp ts = (Timestamp) value;
        return OffsetTime.ofInstant(ts.toInstant(), ZoneId.systemDefault());
    }
    if (Date.class.isInstance(value)) {
        final Date date = (Date) value;
        return OffsetTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
    if (Long.class.isInstance(value)) {
        return OffsetTime.ofInstant(Instant.ofEpochMilli((Long) value), ZoneId.systemDefault());
    }
    if (Calendar.class.isInstance(value)) {
        final Calendar calendar = (Calendar) value;
        return OffsetTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId());
    }
    throw unknownWrap(value.getClass());
}
Example 57
Project: java-neo4j-client-master  File: RestConnectionImpl.java View source code
@Override
public void flush() {
    try {
        LOG.debug("Flushing to [{}]", activeTransactionEndpointUrl);
        JSONObject jsonResult = execute(activeTransactionEndpointUrl);
        this.activeTransactionEndpointUrl = jsonResult.getString("commit").replace("/commit", "");
        this.transactionExpires = OffsetDateTime.parse(jsonResult.getJSONObject("transaction").getString("expires"), FORMATTER);
        this.statements.clear();
        LOG.debug("Next endpoint is now: [{}] which expires at: [{}]", activeTransactionEndpointUrl, transactionExpires);
    } catch (IOException e) {
        close();
        throw new Neo4jClientException(e);
    } catch (JSONException e) {
        close();
        throw new Neo4jClientException("Error when processing JSON response.", e);
    }
}
Example 58
Project: jqiita-master  File: QiitaClient.java View source code
@SuppressWarnings("unchecked")
public <T> T resource(Class<T> clazz) {
    RestAdapter builder = (RestAdapter) objectCache.computeIfAbsent(getKey(RestAdapter.class, accessToken), ( key) -> {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").registerTypeAdapter(OffsetDateTime.class, new OffsetDateTimeConverter()).setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        return new RestAdapter.Builder().setEndpoint(host + "/api/" + API_VERSION).setConverter(new GsonConverter(gson)).setLogLevel(RestAdapter.LogLevel.valueOf(logLevel)).setErrorHandler(new QiitaErrorHandler()).setRequestInterceptor(( request) -> {
            if (accessToken != null && !accessToken.isEmpty()) {
                request.addHeader("Authorization", "Bearer " + accessToken);
            }
        }).build();
    });
    return (T) objectCache.computeIfAbsent(getKey(clazz, accessToken), ( key) -> builder.create(clazz));
}
Example 59
Project: openjdk-master  File: TCKZonedDateTime.java View source code
@Test
public void test_with_adjuster_OffsetDateTime_validOffsetNotInOverlap() {
    // ODT will be a valid ZDT for the zone, so must be retained exactly
    OffsetDateTime odt = TEST_LOCAL_2008_06_30_11_30_59_500.atOffset(OFFSET_0200);
    ZonedDateTime zdt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atZone(ZONE_PARIS);
    ZonedDateTime test = zdt.with(odt);
    assertEquals(test.toOffsetDateTime(), odt);
}
Example 60
Project: Vortex-master  File: AutoMod.java View source code
public boolean startRaidMode(Guild guild, Message iniator) {
    if (raidmode.keySet().contains(guild.getId()))
        return false;
    raidmode.put(guild.getId(), new StringBuilder("Disabled Raid Mode. Users kicked:\n"));
    if (iniator == null) {
        scheduleRaidModeCheck(guild);
        modlog.logEmbed(guild, new EmbedBuilder().setColor(guild.getSelfMember().getColor()).setDescription("Raid mode automatically enabled. Verification will be set to maximum if possible, and any user that joins will be kicked.").setTimestamp(OffsetDateTime.now()).setFooter(guild.getJDA().getSelfUser().getName() + " automod", guild.getJDA().getSelfUser().getEffectiveAvatarUrl()).build());
    } else
        modlog.logCommand(iniator);
    try {
        guild.getManager().setVerificationLevel(Guild.VerificationLevel.HIGH).queue();
    } catch (PermissionException ex) {
    }
    return true;
}
Example 61
Project: openjdk8-jdk-master  File: TCKZonedDateTime.java View source code
@Test
public void test_with_adjuster_OffsetDateTime_validOffsetNotInOverlap() {
    // ODT will be a valid ZDT for the zone, so must be retained exactly
    OffsetDateTime odt = TEST_LOCAL_2008_06_30_11_30_59_500.atOffset(OFFSET_0200);
    ZonedDateTime zdt = TEST_PARIS_OVERLAP_2008_10_26_02_30.atZone(ZONE_PARIS);
    ZonedDateTime test = zdt.with(odt);
    assertEquals(test.toOffsetDateTime(), odt);
}
Example 62
Project: ddf-master  File: TestFederation.java View source code
/**
     * Tests that ddf will redownload a product if the remote metacard has changed
     *
     * @throws Exception
     */
@Test
public void testCacheIsUpdatedIfRemoteProductChanges() throws Exception {
    String filename = "product5.txt";
    String metacardId = generateUniqueMetacardId();
    String resourceData = getResourceData(metacardId);
    Action response = new ChunkedContent.ChunkedContentBuilder(resourceData).build();
    cswServer.whenHttp().match(post("/services/csw"), withPostBodyContaining("GetRecords"), withPostBodyContaining(metacardId)).then(ok(), contentType("text/xml"), bytesContent(getCswQueryResponse(metacardId).getBytes()));
    cswServer.whenHttp().match(Condition.get("/services/csw"), Condition.parameter("request", "GetRecordById"), Condition.parameter("id", metacardId)).then(getCswRetrievalHeaders(filename), response);
    String restUrl = REST_PATH.getUrl() + "sources/" + CSW_STUB_SOURCE_ID + "/" + metacardId + "?transform=resource";
    // Download product twice, and change metacard on stub server between calls.
    when().get(restUrl).then().assertThat().contentType("text/plain").body(is(resourceData));
    cswServer.whenHttp().match(post("/services/csw"), withPostBodyContaining("GetRecords"), withPostBodyContaining(metacardId)).then(ok(), contentType("text/xml"), bytesContent(getCswQueryResponse(metacardId, OffsetDateTime.now()).getBytes()));
    when().get(restUrl).then().assertThat().contentType("text/plain").body(is(resourceData));
    cswServer.verifyHttp().times(2, Condition.uri("/services/csw"), Condition.parameter("request", "GetRecordById"), Condition.parameter("id", metacardId));
}
Example 63
Project: fastjson-master  File: ParserConfig.java View source code
public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
    ObjectDeserializer derializer = deserializers.get(type);
    if (derializer != null) {
        return derializer;
    }
    if (type == null) {
        type = clazz;
    }
    derializer = deserializers.get(type);
    if (derializer != null) {
        return derializer;
    }
    {
        JSONType annotation = clazz.getAnnotation(JSONType.class);
        if (annotation != null) {
            Class<?> mappingTo = annotation.mappingTo();
            if (mappingTo != Void.class) {
                return getDeserializer(mappingTo, mappingTo);
            }
        }
    }
    if (type instanceof WildcardType || type instanceof TypeVariable || type instanceof ParameterizedType) {
        derializer = deserializers.get(clazz);
    }
    if (derializer != null) {
        return derializer;
    }
    String className = clazz.getName();
    className = className.replace('$', '.');
    if (//
    className.startsWith("java.awt.") && AwtCodec.support(clazz)) {
        if (!awtError) {
            try {
                deserializers.put(Class.forName("java.awt.Point"), AwtCodec.instance);
                deserializers.put(Class.forName("java.awt.Font"), AwtCodec.instance);
                deserializers.put(Class.forName("java.awt.Rectangle"), AwtCodec.instance);
                deserializers.put(Class.forName("java.awt.Color"), AwtCodec.instance);
            } catch (Throwable e) {
                awtError = true;
            }
            derializer = AwtCodec.instance;
        }
    }
    if (!jdk8Error) {
        try {
            if (className.startsWith("java.time.")) {
                deserializers.put(Class.forName("java.time.LocalDateTime"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.LocalDate"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.LocalTime"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.ZonedDateTime"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.OffsetDateTime"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.OffsetTime"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.ZoneOffset"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.ZoneRegion"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.ZoneId"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.Period"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.Duration"), Jdk8DateCodec.instance);
                deserializers.put(Class.forName("java.time.Instant"), Jdk8DateCodec.instance);
                derializer = deserializers.get(clazz);
            } else if (className.startsWith("java.util.Optional")) {
                deserializers.put(Class.forName("java.util.Optional"), OptionalCodec.instance);
                deserializers.put(Class.forName("java.util.OptionalDouble"), OptionalCodec.instance);
                deserializers.put(Class.forName("java.util.OptionalInt"), OptionalCodec.instance);
                deserializers.put(Class.forName("java.util.OptionalLong"), OptionalCodec.instance);
                derializer = deserializers.get(clazz);
            }
        } catch (Throwable e) {
            jdk8Error = true;
        }
    }
    if (className.equals("java.nio.file.Path")) {
        deserializers.put(clazz, MiscCodec.instance);
    }
    if (clazz == Map.Entry.class) {
        deserializers.put(clazz, MiscCodec.instance);
    }
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    try {
        for (AutowiredObjectDeserializer autowired : ServiceLoader.load(AutowiredObjectDeserializer.class, classLoader)) {
            for (Type forType : autowired.getAutowiredFor()) {
                deserializers.put(forType, autowired);
            }
        }
    } catch (Exception ex) {
    }
    if (derializer == null) {
        derializer = deserializers.get(type);
    }
    if (derializer != null) {
        return derializer;
    }
    if (clazz.isEnum()) {
        derializer = new EnumDeserializer(clazz);
    } else if (clazz.isArray()) {
        derializer = ObjectArrayCodec.instance;
    } else if (clazz == Set.class || clazz == HashSet.class || clazz == Collection.class || clazz == List.class || clazz == ArrayList.class) {
        derializer = CollectionCodec.instance;
    } else if (Collection.class.isAssignableFrom(clazz)) {
        derializer = CollectionCodec.instance;
    } else if (Map.class.isAssignableFrom(clazz)) {
        derializer = MapDeserializer.instance;
    } else if (Throwable.class.isAssignableFrom(clazz)) {
        derializer = new ThrowableDeserializer(this, clazz);
    } else {
        derializer = createJavaBeanDeserializer(clazz, type);
    }
    putDeserializer(type, derializer);
    return derializer;
}
Example 64
Project: javamoney-lib-master  File: USFederalReserveRateReadingHandler.java View source code
@Override
public void characters(char ch[], int start, int length) throws SAXException {
    if (this.descriptionNode) {
        this.description = new String(ch, start, length);
    } else if (this.dcDateNode) {
        this.localDate = OffsetDateTime.parse(new String(ch, start, length)).toLocalDate();
    } else if (this.cbValueNode && this.currencyCode != null) {
        String rateStr = new String(ch, start, length);
        CurrencyUnit currencyUnit = null;
        boolean inverse = false;
        if (USFederalReserveRateProvider.BASE_CURRENCY_CODE.equals(this.currencyCode)) {
            currencyUnit = CURRENCIES_BY_NAME.get(description);
        } else {
            currencyUnit = Monetary.getCurrency(this.currencyCode);
            inverse = true;
        }
        if (currencyUnit != null) {
            if (!"ND".equals(rateStr)) {
                addRate(currencyUnit, this.localDate, BigDecimal.valueOf(Double.parseDouble(rateStr)), inverse);
            }
        }
        this.currencyCode = null;
        this.localDate = null;
        this.description = null;
    }
    super.characters(ch, start, length);
}
Example 65
Project: mssql-jdbc-master  File: SQLServerBulkCopy.java View source code
private void writeColumnToTdsWriter(TDSWriter tdsWriter, int bulkPrecision, int bulkScale, int bulkJdbcType, // should it be destNullable instead?
boolean bulkNullable, int srcColOrdinal, int destColOrdinal, boolean isStreaming, Object colValue) throws SQLServerException {
    SSType destSSType = destColumnMetadata.get(destColOrdinal).ssType;
    bulkPrecision = validateSourcePrecision(bulkPrecision, bulkJdbcType, destColumnMetadata.get(destColOrdinal).precision);
    CryptoMetadata sourceCryptoMeta = srcColumnMetadata.get(srcColOrdinal).cryptoMeta;
    if (((null != destColumnMetadata.get(destColOrdinal).encryptionType) && copyOptions.isAllowEncryptedValueModifications()) || // if destination is encrypted send varbinary explicitly(needed for unencrypted source)
    (null != destColumnMetadata.get(destColOrdinal).cryptoMeta)) {
        bulkJdbcType = java.sql.Types.VARBINARY;
    } else /*
         * if source is encrypted and destination is unenecrypted, use destination sql type to send since there is no way of finding if source is
         * encrypted without accessing the resultset, send destination type if source resultset set is of type SQLServer and encryption is enabled
         */
    if (null != sourceCryptoMeta) {
        bulkJdbcType = destColumnMetadata.get(destColOrdinal).jdbcType;
        bulkScale = destColumnMetadata.get(destColOrdinal).scale;
    } else if (null != sourceBulkRecord) {
        // SQL Server does the conversion. If destination is encrypted, then temporal types can not be sent as varchar.
        switch(bulkJdbcType) {
            case java.sql.Types.DATE:
            case java.sql.Types.TIME:
            case java.sql.Types.TIMESTAMP:
            case microsoft.sql.Types.DATETIMEOFFSET:
                bulkJdbcType = java.sql.Types.VARCHAR;
                break;
            default:
                break;
        }
    }
    try {
        // We are sending the data using JDBCType and not using SSType as SQL Server will automatically do the conversion.
        switch(bulkJdbcType) {
            case java.sql.Types.INTEGER:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x04);
                    }
                    tdsWriter.writeInt((int) colValue);
                }
                break;
            case java.sql.Types.SMALLINT:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x02);
                    }
                    tdsWriter.writeShort(((Number) colValue).shortValue());
                }
                break;
            case java.sql.Types.BIGINT:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x08);
                    }
                    tdsWriter.writeLong((long) colValue);
                }
                break;
            case java.sql.Types.BIT:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x01);
                    }
                    tdsWriter.writeByte((byte) (((Boolean) colValue).booleanValue() ? 1 : 0));
                }
                break;
            case java.sql.Types.TINYINT:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x01);
                    }
                    // TINYINT JDBC type is returned as a short in getObject.
                    // MYSQL returns TINYINT as an Integer. Convert it to a Number to get the short value.
                    tdsWriter.writeByte((byte) ((((Number) colValue).shortValue()) & 0xFF));
                }
                break;
            case java.sql.Types.DOUBLE:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x08);
                    }
                    tdsWriter.writeDouble((double) colValue);
                }
                break;
            case java.sql.Types.REAL:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (bulkNullable) {
                        tdsWriter.writeByte((byte) 0x04);
                    }
                    tdsWriter.writeReal((float) colValue);
                }
                break;
            case microsoft.sql.Types.MONEY:
            case microsoft.sql.Types.SMALLMONEY:
            case java.sql.Types.DECIMAL:
            case java.sql.Types.NUMERIC:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    /*
                         * if the precision that user provides is smaller than the precision of the actual value, the driver assumes the precision
                         * that user provides is the correct precision, and throws exception
                         */
                    if (bulkPrecision < Util.getValueLengthBaseOnJavaType(colValue, JavaType.of(colValue), null, null, JDBCType.of(bulkJdbcType))) {
                        MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
                        Object[] msgArgs = { SSType.DECIMAL };
                        throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET, null);
                    }
                    tdsWriter.writeBigDecimal((BigDecimal) colValue, bulkJdbcType, bulkPrecision, bulkScale);
                }
                break;
            case microsoft.sql.Types.GUID:
            case java.sql.Types.LONGVARCHAR:
            // Fixed-length, non-Unicode string data.
            case java.sql.Types.CHAR:
            case // Variable-length, non-Unicode string data.
            java.sql.Types.VARCHAR:
                if (// PLP
                isStreaming) {
                    // so that if the source data source does not have streaming enabled, the smaller size data will still work.
                    if (null == colValue) {
                        writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                    } else {
                        // Send length as unknown.
                        tdsWriter.writeLong(PLPInputStream.UNKNOWN_PLP_LEN);
                        try {
                            // Read and Send the data as chunks
                            // VARBINARYMAX --- only when streaming.
                            Reader reader = null;
                            if (colValue instanceof Reader) {
                                reader = (Reader) colValue;
                            } else {
                                reader = new StringReader(colValue.toString());
                            }
                            if ((SSType.BINARY == destSSType) || (SSType.VARBINARY == destSSType) || (SSType.VARBINARYMAX == destSSType) || (SSType.IMAGE == destSSType)) {
                                tdsWriter.writeNonUnicodeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, true, null);
                            } else {
                                SQLCollation destCollation = destColumnMetadata.get(destColOrdinal).collation;
                                if (null != destCollation) {
                                    tdsWriter.writeNonUnicodeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, false, destCollation.getCharset());
                                } else {
                                    tdsWriter.writeNonUnicodeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, false, null);
                                }
                            }
                            reader.close();
                        } catch (IOException e) {
                            throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
                        }
                    }
                } else // Non-PLP
                {
                    if (null == colValue) {
                        writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                    } else {
                        String colValueStr = colValue.toString();
                        if ((SSType.BINARY == destSSType) || (SSType.VARBINARY == destSSType)) {
                            byte[] bytes = null;
                            try {
                                bytes = ParameterUtils.HexToBin(colValueStr);
                            } catch (SQLServerException e) {
                                throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
                            }
                            tdsWriter.writeShort((short) bytes.length);
                            tdsWriter.writeBytes(bytes);
                        } else {
                            tdsWriter.writeShort((short) (colValueStr.length()));
                            // converting string into destination collation using Charset
                            SQLCollation destCollation = destColumnMetadata.get(destColOrdinal).collation;
                            if (null != destCollation) {
                                tdsWriter.writeBytes(colValueStr.getBytes(destColumnMetadata.get(destColOrdinal).collation.getCharset()));
                            } else {
                                tdsWriter.writeBytes(colValueStr.getBytes());
                            }
                        }
                    }
                }
                break;
            /*
                 * The length value associated with these data types is specified within a USHORT. see MS-TDS.pdf page 38. However, nchar(n)
                 * nvarchar(n) supports n = 1 .. 4000 (see MSDN SQL 2014, SQL 2016 Transact-SQL) NVARCHAR/NCHAR/LONGNVARCHAR is not compatible with
                 * BINARY/VARBINARY as specified in enum UpdaterConversion of DataTypes.java
                 */
            case java.sql.Types.LONGNVARCHAR:
            case java.sql.Types.NCHAR:
            case java.sql.Types.NVARCHAR:
                if (isStreaming) {
                    // so that if the source data source does not have streaming enabled, the smaller size data will still work.
                    if (null == colValue) {
                        writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                    } else {
                        // Send length as unknown.
                        tdsWriter.writeLong(PLPInputStream.UNKNOWN_PLP_LEN);
                        try {
                            // Read and Send the data as chunks.
                            Reader reader = null;
                            if (colValue instanceof Reader) {
                                reader = (Reader) colValue;
                            } else {
                                reader = new StringReader(colValue.toString());
                            }
                            // writeReader is unicode.
                            tdsWriter.writeReader(reader, DataTypes.UNKNOWN_STREAM_LENGTH, true);
                            reader.close();
                        } catch (IOException e) {
                            throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
                        }
                    }
                } else {
                    if (null == colValue) {
                        writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                    } else {
                        int stringLength = colValue.toString().length();
                        byte[] typevarlen = new byte[2];
                        typevarlen[0] = (byte) (2 * stringLength & 0xFF);
                        typevarlen[1] = (byte) ((2 * stringLength >> 8) & 0xFF);
                        tdsWriter.writeBytes(typevarlen);
                        tdsWriter.writeString(colValue.toString());
                    }
                }
                break;
            case java.sql.Types.LONGVARBINARY:
            case java.sql.Types.BINARY:
            case java.sql.Types.VARBINARY:
                if (// PLP
                isStreaming) {
                    // does not support streaming data.
                    if (null == colValue) {
                        writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                    } else {
                        // Send length as unknown.
                        tdsWriter.writeLong(PLPInputStream.UNKNOWN_PLP_LEN);
                        try {
                            // Read and Send the data as chunks
                            InputStream iStream = null;
                            if (colValue instanceof InputStream) {
                                iStream = (InputStream) colValue;
                            } else {
                                if (colValue instanceof byte[]) {
                                    iStream = new ByteArrayInputStream((byte[]) colValue);
                                } else
                                    iStream = new ByteArrayInputStream(ParameterUtils.HexToBin(colValue.toString()));
                            }
                            // We do not need to check for null values here as it is already checked above.
                            tdsWriter.writeStream(iStream, DataTypes.UNKNOWN_STREAM_LENGTH, true);
                            iStream.close();
                        } catch (IOException e) {
                            throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
                        }
                    }
                } else // Non-PLP
                {
                    if (null == colValue) {
                        writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                    } else {
                        byte[] srcBytes;
                        if (colValue instanceof byte[]) {
                            srcBytes = (byte[]) colValue;
                        } else {
                            try {
                                srcBytes = ParameterUtils.HexToBin(colValue.toString());
                            } catch (SQLServerException e) {
                                throw new SQLServerException(SQLServerException.getErrString("R_unableRetrieveSourceData"), e);
                            }
                        }
                        tdsWriter.writeShort((short) srcBytes.length);
                        tdsWriter.writeBytes(srcBytes);
                    }
                }
                break;
            case microsoft.sql.Types.DATETIME:
            case microsoft.sql.Types.SMALLDATETIME:
            case java.sql.Types.TIMESTAMP:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    switch(destSSType) {
                        case SMALLDATETIME:
                            if (bulkNullable)
                                tdsWriter.writeByte((byte) 0x04);
                            tdsWriter.writeSmalldatetime(colValue.toString());
                            break;
                        case DATETIME:
                            if (bulkNullable)
                                tdsWriter.writeByte((byte) 0x08);
                            tdsWriter.writeDatetime(colValue.toString());
                            break;
                        default:
                            // DATETIME2
                            if (bulkNullable) {
                                if (2 >= bulkScale)
                                    tdsWriter.writeByte((byte) 0x06);
                                else if (4 >= bulkScale)
                                    tdsWriter.writeByte((byte) 0x07);
                                else
                                    tdsWriter.writeByte((byte) 0x08);
                            }
                            String timeStampValue = colValue.toString();
                            tdsWriter.writeTime(java.sql.Timestamp.valueOf(timeStampValue), bulkScale);
                            // Send only the date part
                            tdsWriter.writeDate(timeStampValue.substring(0, timeStampValue.lastIndexOf(' ')));
                    }
                }
                break;
            case java.sql.Types.DATE:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    tdsWriter.writeByte((byte) 0x03);
                    tdsWriter.writeDate(colValue.toString());
                }
                break;
            case java.sql.Types.TIME:
                // values are read as java.sql.Types.TIMESTAMP if srcJdbcType is java.sql.Types.TIME
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (2 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x03);
                    else if (4 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x04);
                    else
                        tdsWriter.writeByte((byte) 0x05);
                    tdsWriter.writeTime((java.sql.Timestamp) colValue, bulkScale);
                }
                break;
            case // java.sql.Types.TIME_WITH_TIMEZONE
            2013:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (2 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x08);
                    else if (4 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x09);
                    else
                        tdsWriter.writeByte((byte) 0x0A);
                    tdsWriter.writeOffsetTimeWithTimezone((OffsetTime) colValue, bulkScale);
                }
                break;
            case // java.sql.Types.TIMESTAMP_WITH_TIMEZONE
            2014:
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (2 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x08);
                    else if (4 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x09);
                    else
                        tdsWriter.writeByte((byte) 0x0A);
                    tdsWriter.writeOffsetDateTimeWithTimezone((OffsetDateTime) colValue, bulkScale);
                }
                break;
            case microsoft.sql.Types.DATETIMEOFFSET:
                // We can safely cast the result set to a SQLServerResultSet as the DatetimeOffset type is only available in the JDBC driver.
                if (null == colValue) {
                    writeNullToTdsWriter(tdsWriter, bulkJdbcType, isStreaming);
                } else {
                    if (2 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x08);
                    else if (4 >= bulkScale)
                        tdsWriter.writeByte((byte) 0x09);
                    else
                        tdsWriter.writeByte((byte) 0x0A);
                    tdsWriter.writeDateTimeOffset(colValue, bulkScale, destSSType);
                }
                break;
            default:
                MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_BulkTypeNotSupported"));
                Object[] msgArgs = { JDBCType.of(bulkJdbcType).toString().toLowerCase(Locale.ENGLISH) };
                SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, true);
        }
    // End of switch
    } catch (ClassCastException ex) {
        MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
        Object[] msgArgs = { colValue.getClass().getSimpleName(), JDBCType.of(bulkJdbcType) };
        throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, ex);
    }
}
Example 66
Project: drools-master  File: ParserHelper.java View source code
public static Type determineTypeFromClass(Class<?> clazz) {
    if (clazz == null) {
        return BuiltInType.UNKNOWN;
    } else if (Number.class.isAssignableFrom(clazz)) {
        return BuiltInType.NUMBER;
    } else if (String.class.isAssignableFrom(clazz)) {
        return BuiltInType.STRING;
    } else if (LocalDate.class.isAssignableFrom(clazz)) {
        return BuiltInType.DATE;
    } else if (LocalTime.class.isAssignableFrom(clazz) || OffsetTime.class.isAssignableFrom(clazz)) {
        return BuiltInType.TIME;
    } else if (ZonedDateTime.class.isAssignableFrom(clazz) || OffsetDateTime.class.isAssignableFrom(clazz) || LocalDateTime.class.isAssignableFrom(clazz)) {
        return BuiltInType.DATE_TIME;
    } else if (Duration.class.isAssignableFrom(clazz) || Period.class.isAssignableFrom(clazz)) {
        return BuiltInType.DURATION;
    } else if (Boolean.class.isAssignableFrom(clazz)) {
        return BuiltInType.BOOLEAN;
    } else if (UnaryTest.class.isAssignableFrom(clazz)) {
        return BuiltInType.UNARY_TEST;
    } else if (Range.class.isAssignableFrom(clazz)) {
        return BuiltInType.RANGE;
    } else if (FEELFunction.class.isAssignableFrom(clazz)) {
        return BuiltInType.FUNCTION;
    } else if (List.class.isAssignableFrom(clazz)) {
        return BuiltInType.LIST;
    } else if (Map.class.isAssignableFrom(clazz)) {
        // TODO not so sure about this one..
        return BuiltInType.CONTEXT;
    }
    return JavaBackedType.of(clazz);
}
Example 67
Project: error-prone-master  File: WellKnownMutability.java View source code
// TODO(b/35724557): share this list with other code analyzing types for immutability
// TODO(cushon): generate this at build-time to get type-safety without added compile-time deps
private static ImmutableMap<String, ImmutableAnnotationInfo> getBootstrapClasses() {
    return new Builder().addAll(Primitives.allPrimitiveTypes()).addAll(Primitives.allWrapperTypes()).add("com.google.protobuf.ByteString").add("com.google.protobuf.Descriptors$Descriptor").add("com.google.protobuf.Descriptors$EnumDescriptor").add("com.google.protobuf.Descriptors$EnumValueDescriptor").add("com.google.protobuf.Descriptors$FieldDescriptor").add("com.google.protobuf.Descriptors$FileDescriptor").add("com.google.protobuf.Descriptors$ServiceDescriptor").add("com.google.protobuf.Extension").add("com.google.protobuf.ExtensionRegistry$ExtensionInfo").add("com.google.re2j.Pattern").add(com.google.common.base.CharMatcher.class).add(com.google.common.base.Converter.class).add(com.google.common.base.Joiner.class).add(com.google.common.base.Optional.class, "T").add(com.google.common.base.Splitter.class).add(com.google.common.collect.ImmutableBiMap.class, "K", "V").add(com.google.common.collect.ImmutableCollection.class, "E").add(com.google.common.collect.ImmutableList.class, "E").add(com.google.common.collect.ImmutableListMultimap.class, "K", "V").add(com.google.common.collect.ImmutableMap.class, "K", "V").add(com.google.common.collect.ImmutableMultimap.class, "K", "V").add(com.google.common.collect.ImmutableMultiset.class, "E").add(com.google.common.collect.ImmutableRangeMap.class, "K", "V").add(com.google.common.collect.ImmutableRangeSet.class, "C").add(com.google.common.collect.ImmutableSet.class, "E").add(com.google.common.collect.ImmutableSetMultimap.class, "K", "V").add(com.google.common.collect.ImmutableSortedMap.class, "K", "V").add(com.google.common.collect.ImmutableSortedMultiset.class, "E").add(com.google.common.collect.ImmutableSortedSet.class, "E").add(com.google.common.collect.ImmutableTable.class, "R", "C", "V").add(com.google.common.collect.Range.class, "C").add(com.google.common.graph.ImmutableGraph.class, "N").add(com.google.common.graph.ImmutableNetwork.class, "N", "E").add(com.google.common.graph.ImmutableValueGraph.class, "N", "V").add(com.google.common.hash.HashCode.class).add(com.google.common.io.BaseEncoding.class).add(com.google.common.net.MediaType.class).add(com.google.common.primitives.UnsignedLong.class).add(java.lang.Class.class).add(java.lang.String.class).add(java.lang.annotation.Annotation.class).add(java.math.BigDecimal.class).add(java.math.BigInteger.class).add(java.net.InetAddress.class).add(java.net.URI.class).add(java.util.Locale.class).add(java.util.regex.Pattern.class).add("android.net.Uri").add("java.util.Optional", "T").add("java.time.Duration").add("java.time.Instant").add("java.time.LocalDate").add("java.time.LocalDateTime").add("java.time.LocalTime").add("java.time.MonthDay").add("java.time.OffsetDateTime").add("java.time.OffsetTime").add("java.time.Period").add("java.time.Year").add("java.time.YearMonth").add("java.time.ZoneId").add("java.time.ZoneOffset").add("java.time.ZonedDateTime").add("java.time.chrono.AbstractChronology").add("java.time.chrono.ChronoLocalDate").add("java.time.chrono.ChronoLocalDateTime", "D").add("java.time.chrono.ChronoPeriod").add("java.time.chrono.ChronoZonedDateTime", "D").add("java.time.chrono.Chronology").add("java.time.chrono.Era").add("java.time.chrono.HijrahChronology").add("java.time.chrono.HijrahDate").add("java.time.chrono.IsoChronology").add("java.time.chrono.JapaneseChronology").add("java.time.chrono.JapaneseDate").add("java.time.chrono.JapaneseEra").add("java.time.chrono.MinguoChronology").add("java.time.chrono.MinguoDate").add("java.time.chrono.ThaiBuddhistChronology").add("java.time.chrono.ThaiBuddhistDate").add("java.time.format.DateTimeFormatter").add("java.time.format.DecimalStyle").add("java.time.temporal.TemporalField").add("java.time.temporal.TemporalUnit").add("java.time.temporal.ValueRange").add("java.time.temporal.WeekFields").add("java.time.zone.ZoneOffsetTransition").add("java.time.zone.ZoneOffsetTransitionRule").add("java.time.zone.ZoneRules").add("java.time.zone.ZoneRulesProvider").add("org.joda.time.DateTime").add("org.joda.time.DateTimeZone").add("org.joda.time.Duration").add("org.joda.time.Instant").add("org.joda.time.LocalDate").add("org.joda.time.LocalDateTime").add("org.joda.time.Period").add("org.joda.time.format.DateTimeFormatter").build();
}
Example 68
Project: java8-backports-master  File: TCKOffsetDateTime.java View source code
// -----------------------------------------------------------------------
// now()
// -----------------------------------------------------------------------
@Test(groups = { "tck" })
public void now() {
    OffsetDateTime expected = OffsetDateTime.now(Clock.systemDefaultZone());
    OffsetDateTime test = OffsetDateTime.now();
    long diff = Math.abs(test.getTime().toNanoOfDay() - expected.getTime().toNanoOfDay());
    if (diff >= 100000000) {
        // may be date change
        expected = OffsetDateTime.now(Clock.systemDefaultZone());
        test = OffsetDateTime.now();
        diff = Math.abs(test.getTime().toNanoOfDay() - expected.getTime().toNanoOfDay());
    }
    // less than 0.1 secs
    assertTrue(diff < 100000000);
}
Example 69
Project: jfxtras-master  File: AgendaRenderTest.java View source code
@Test
public void renderRegularAppointmentOffset() {
    TestUtil.runThenWaitForPaintPulse(() -> {
        ZoneOffset offset = ZonedDateTime.now().getOffset();
        agenda.appointments().add(new Agenda.AppointmentImplTemporal().withStartTemporal(OffsetDateTime.of(LocalDateTime.of(2014, 1, 1, 10, 0), offset)).withEndTemporal(OffsetDateTime.of(LocalDateTime.of(2014, 1, 1, 12, 0), offset)).withAppointmentGroup(appointmentGroupMap.get("group01")));
    });
    Node n = find("#AppointmentRegularBodyPane2014-01-01/0");
    //AssertNode.generateSource("n", n, null, false, jfxtras.test.AssertNode.A.XYWH);
    new AssertNode(n).assertXYWH(0.5, 419.5, 125.0, 84.0, 0.01);
//TestUtil.sleep(3000);
}
Example 70
Project: kie-wb-common-master  File: DataObjectFormModelHandlerTest.java View source code
@Test
public void dataTypesGenerateCorrectFieldDefinitions() {
    //all possible types of data object fields - expected field types couples
    Map<String, List<String>> expectedFieldTypes = new HashMap<>();
    expectedFieldTypes.put(DecimalBoxFieldDefinition.class.getSimpleName(), Arrays.asList(BigDecimal.class.getName(), Double.class.getName(), Float.class.getName(), double.class.getName(), float.class.getName()));
    expectedFieldTypes.put(IntegerBoxFieldDefinition.class.getSimpleName(), Arrays.asList(BigInteger.class.getName(), Byte.class.getName(), Integer.class.getName(), Long.class.getName(), Short.class.getName(), byte.class.getName(), int.class.getName(), long.class.getName(), short.class.getName()));
    expectedFieldTypes.put(CheckBoxFieldDefinition.class.getSimpleName(), Arrays.asList(Boolean.class.getName(), boolean.class.getName()));
    expectedFieldTypes.put(TextBoxFieldDefinition.class.getSimpleName(), Arrays.asList(String.class.getName()));
    expectedFieldTypes.put(CharacterBoxFieldDefinition.class.getSimpleName(), Arrays.asList(Character.class.getName(), char.class.getName()));
    expectedFieldTypes.put(DatePickerFieldDefinition.class.getSimpleName(), Collections.singletonList(Date.class.getName()));
    //TODO: Update after JBPM-5911 is fixed (move date-types from SubFormFieldType to DatePickerFieldType)
    expectedFieldTypes.put(SubFormFieldDefinition.class.getSimpleName(), Arrays.asList(LocalDate.class.getName(), LocalDateTime.class.getName(), OffsetDateTime.class.getName(), LocalTime.class.getName(), NESTED_CLASSNAME));
    expectedFieldTypes.put(MultipleSubFormFieldDefinition.class.getSimpleName(), Collections.singletonList(NESTED_CLASSNAME));
    List<FieldDefinition> formModelFields = handler.getAllFormModelFields();
    formFieldsShouldNotBeGeneratedForPersistenceId(formModelFields);
    listsOfBasicDataTypesShouldBeExcludedFromTheFormFields(formModelFields);
    for (FieldDefinition field : formModelFields) {
        String dataType = field.getStandaloneClassName();
        String fieldDefinition = field.getClass().getSimpleName();
        assertTrue(expectedFieldTypes.get(fieldDefinition).contains(dataType));
    }
}
Example 71
Project: vertx-jdbc-client-master  File: JDBCStatementHelper.java View source code
public static Object convertSqlValue(Object value) throws SQLException {
    if (value == null) {
        return null;
    }
    // valid json types are just returned as is
    if (value instanceof Boolean || value instanceof String || value instanceof byte[]) {
        return value;
    }
    // numeric values
    if (value instanceof Number) {
        if (value instanceof BigDecimal) {
            BigDecimal d = (BigDecimal) value;
            if (d.scale() == 0) {
                return ((BigDecimal) value).toBigInteger();
            } else {
                // we might loose precision here
                return ((BigDecimal) value).doubleValue();
            }
        }
        return value;
    }
    // temporal values
    if (value instanceof Time) {
        return ((Time) value).toLocalTime().atOffset(ZoneOffset.UTC).format(ISO_LOCAL_TIME);
    }
    if (value instanceof Date) {
        return ((Date) value).toLocalDate().format(ISO_LOCAL_DATE);
    }
    if (value instanceof Timestamp) {
        return OffsetDateTime.ofInstant(((Timestamp) value).toInstant(), ZoneOffset.UTC).format(ISO_OFFSET_DATE_TIME);
    }
    // large objects
    if (value instanceof Clob) {
        Clob c = (Clob) value;
        try {
            // result might be truncated due to downcasting to int
            return c.getSubString(1, (int) c.length());
        } finally {
            try {
                c.free();
            } catch (AbstractMethodErrorSQLFeatureNotSupportedException |  e) {
            }
        }
    }
    if (value instanceof Blob) {
        Blob b = (Blob) value;
        try {
            // result might be truncated due to downcasting to int
            return b.getBytes(1, (int) b.length());
        } finally {
            try {
                b.free();
            } catch (AbstractMethodErrorSQLFeatureNotSupportedException |  e) {
            }
        }
    }
    // arrays
    if (value instanceof Array) {
        Array a = (Array) value;
        try {
            Object[] arr = (Object[]) a.getArray();
            if (arr != null) {
                JsonArray jsonArray = new JsonArray();
                for (Object o : arr) {
                    jsonArray.add(convertSqlValue(o));
                }
                return jsonArray;
            }
        } finally {
            a.free();
        }
    }
    // fallback to String
    return value.toString();
}
Example 72
Project: vertx-mongo-client-master  File: JsonObjectCodecTest.java View source code
@Test
public void writeDocument_supportBsonDateTime() {
    JsonObjectCodec codec = new JsonObjectCodec(options);
    OffsetDateTime now = OffsetDateTime.now();
    JsonObject dateValue = new JsonObject();
    dateValue.put(JsonObjectCodec.DATE_FIELD, now.format(ISO_OFFSET_DATE_TIME));
    JsonObject value = new JsonObject();
    value.put("test", dateValue);
    BsonDocument bsonResult = new BsonDocument();
    BsonDocumentWriter writer = new BsonDocumentWriter(bsonResult);
    codec.writeDocument(writer, "", value, EncoderContext.builder().build());
    BsonValue resultValue = bsonResult.get("test");
    assertEquals(BsonType.DATE_TIME, resultValue.getBsonType());
    assertEquals(now.toInstant().toEpochMilli(), resultValue.asDateTime().getValue());
}
Example 73
Project: werval-master  File: PathBindersTest.java View source code
@BeforeClass
public static void setupParameterBinders() {
    List<ParameterBinder<? extends Object>> list = Arrays.asList(new ParameterBindersInstance.String(), new ParameterBindersInstance.Boolean(), new ParameterBindersInstance.Short(), new ParameterBindersInstance.Integer(), new ParameterBindersInstance.Long(), new ParameterBindersInstance.Double(), new ParameterBindersInstance.Float(), new ParameterBindersInstance.BigInteger(), new ParameterBindersInstance.BigDecimal(), new ParameterBindersInstance.UUID(), new ParameterBindersInstance.URL(), new ParameterBindersInstance.Class(), new ParameterBindersInstance.Duration(), new ParameterBindersInstance.Period(), new ParameterBindersInstance.Year(), new ParameterBindersInstance.Month(), new ParameterBindersInstance.DayOfWeek(), new ParameterBindersInstance.YearMonth(), new ParameterBindersInstance.MonthDay(), new ParameterBindersInstance.LocalDate(), new ParameterBindersInstance.LocalTime(), new ParameterBindersInstance.LocalDateTime(), new ParameterBindersInstance.OffsetTime(), new ParameterBindersInstance.OffsetDateTime(), new ParameterBindersInstance.ZonedDateTime(), new ParameterBindersInstance.Hashid(), new CustomParam.ParameterBinder());
    list.forEach( b -> b.init(WERVAL.application()));
    binders = new ParameterBindersInstance(list);
}
Example 74
Project: gngr-master  File: CookieParsing.java View source code
static Optional<java.util.Date> parseExpiresRFC6265(final String expiresStr) {
    final Optional<java.util.Date> expiresDate = Optional.empty();
    final String[] tokens = DATE_DELIM.split(expiresStr);
    if (tokens.length == 0) {
        return expiresDate;
    }
    boolean found_time = false, found_dom = false, found_month = false, found_year = false;
    // LocalDateTime date = LocalDateTime.MIN;
    // date = date.withNano(0);
    // LocalDate date = LocalDate.MIN;
    int dayOfMonth = 0;
    int month = 0;
    int year = 0;
    int hour = 0;
    int minute = 0;
    int second = 0;
    for (final String token2 : tokens) {
        final String token = token2.trim();
        if (token.length() == 0) {
            continue;
        }
        /* 2.1. If the found-time flag is not set and the token matches the time
       * production, set the found-time flag and set the hour- value,
       * minute-value, and second-value to the numbers denoted by the digits in
       * the date-token, respectively.  Skip the remaining sub-steps and continue
       * to the next date-token.
       */
        if (!found_time) {
            // final Matcher matcher = (strict ? STRICT_TIME : LENIENT_TIME).matcher(token);
            final Matcher matcher = LENIENT_TIME.matcher(token);
            if (matcher.matches()) {
                found_time = true;
                hour = Integer.parseInt(matcher.group(1));
                minute = Integer.parseInt(matcher.group(2));
                second = Integer.parseInt(matcher.group(3));
                continue;
            }
        }
        /* 2.2. If the found-day-of-month flag is not set and the date-token matches
       * the day-of-month production, set the found-day-of- month flag and set
       * the day-of-month-value to the number denoted by the date-token.  Skip
       * the remaining sub-steps and continue to the next date-token.
       */
        if (!found_dom) {
            final Matcher matcher = DAY_OF_MONTH.matcher(token);
            if (matcher.matches()) {
                found_dom = true;
                dayOfMonth = Integer.parseInt(matcher.group(1));
                continue;
            }
        }
        /* 2.3. If the found-month flag is not set and the date-token matches the
       * month production, set the found-month flag and set the month-value to
       * the month denoted by the date-token.  Skip the remaining sub-steps and
       * continue to the next date-token.
       */
        if (!found_month) {
            final Matcher matcher = MONTH.matcher(token);
            if (matcher.matches()) {
                found_month = true;
                month = monthToNum.get(matcher.group(1).toLowerCase());
                continue;
            }
        }
        /* 2.4. If the found-year flag is not set and the date-token matches the year
       * production, set the found-year flag and set the year-value to the number
       * denoted by the date-token.  Skip the remaining sub-steps and continue to
       * the next date-token.
       */
        if (!found_year) {
            final Matcher matcher = YEAR.matcher(token);
            if (matcher.matches()) {
                year = Integer.parseInt(matcher.group(1));
                /* From S5.1.1:
           * 3.  If the year-value is greater than or equal to 70 and less
           * than or equal to 99, increment the year-value by 1900.
           * 4.  If the year-value is greater than or equal to 0 and less
           * than or equal to 69, increment the year-value by 2000.
           */
                if ((70 <= year) && (year <= 99)) {
                    year += 1900;
                } else if ((0 <= year) && (year <= 69)) {
                    year += 2000;
                }
                if (year < 1601) {
                    // 5. ... the year-value is less than 1601
                    return expiresDate;
                }
                found_year = true;
                continue;
            }
        }
    }
    if (!(found_time && found_dom && found_month && found_year)) {
        // 5. ... at least one of the found-day-of-month, found-month, found-year, or found-time flags is not set,
        return expiresDate;
    } else {
        try {
            final OffsetDateTime dateTime = OffsetDateTime.of(year, month, dayOfMonth, hour, minute, second, 0, ZoneOffset.UTC);
            final long millis = dateTime.toInstant().toEpochMilli();
            return Optional.of(new Date(millis));
        } catch (final DateTimeException e) {
            logger.log(Level.WARNING, "parseExpires(): Bad date-time.", e);
            return Optional.empty();
        }
    }
}
Example 75
Project: parkandrideAPI-master  File: PredictionITest.java View source code
@Test
public void prediction_JSON_structure() {
    Utilization u = makeDummyPredictions();
    JsonPath json = when().get(UrlSchema.FACILITY_PREDICTION, facilityId).jsonPath();
    long facilityId = json.getLong("[0].facilityId");
    String capacityType = json.getString("[0].capacityType");
    String usage = json.getString("[0].usage");
    OffsetDateTime timestamp = OffsetDateTime.parse(json.getString("[0].timestamp"), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    int spacesAvailable = json.getInt("[0].spacesAvailable");
    assertThat(facilityId).as("facilityId").isEqualTo(u.facilityId);
    assertThat(capacityType).as("capacityType").isEqualTo(u.capacityType.name());
    assertThat(usage).as("usage").isEqualTo(u.usage.name());
    assertThat(timestamp.getOffset()).as("time should be in local timezone").isEqualTo(ZoneOffset.systemDefault().getRules().getOffset(timestamp.toInstant()));
    assertThat(spacesAvailable).as("spacesAvailable").isEqualTo(u.spacesAvailable);
}
Example 76
Project: enunciate-master  File: EnunciateJackson1Context.java View source code
protected Map<String, JsonType> loadKnownTypes() {
    HashMap<String, JsonType> knownTypes = new HashMap<String, JsonType>();
    knownTypes.put(Boolean.class.getName(), KnownJsonType.BOOLEAN);
    knownTypes.put(Byte.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Character.class.getName(), KnownJsonType.STRING);
    knownTypes.put(Double.class.getName(), KnownJsonType.NUMBER);
    knownTypes.put(Float.class.getName(), KnownJsonType.NUMBER);
    knownTypes.put(Integer.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Long.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Short.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Boolean.TYPE.getName(), KnownJsonType.BOOLEAN);
    knownTypes.put(Byte.TYPE.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Double.TYPE.getName(), KnownJsonType.NUMBER);
    knownTypes.put(Float.TYPE.getName(), KnownJsonType.NUMBER);
    knownTypes.put(Integer.TYPE.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Long.TYPE.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Short.TYPE.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(Character.TYPE.getName(), KnownJsonType.STRING);
    knownTypes.put(QName.class.getName(), KnownJsonType.STRING);
    knownTypes.put(String.class.getName(), KnownJsonType.STRING);
    knownTypes.put(Enum.class.getName(), KnownJsonType.STRING);
    knownTypes.put(java.math.BigInteger.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(java.math.BigDecimal.class.getName(), KnownJsonType.NUMBER);
    knownTypes.put(java.util.Calendar.class.getName(), this.dateType);
    knownTypes.put(java.util.Date.class.getName(), this.dateType);
    knownTypes.put(Timestamp.class.getName(), this.dateType);
    knownTypes.put(java.net.URI.class.getName(), KnownJsonType.STRING);
    knownTypes.put(java.net.URL.class.getName(), KnownJsonType.STRING);
    knownTypes.put(java.lang.Object.class.getName(), KnownJsonType.OBJECT);
    knownTypes.put(byte[].class.getName(), KnownJsonType.STRING);
    knownTypes.put(java.nio.ByteBuffer.class.getName(), KnownJsonType.STRING);
    knownTypes.put(DataHandler.class.getName(), KnownJsonType.STRING);
    knownTypes.put(java.util.UUID.class.getName(), KnownJsonType.STRING);
    knownTypes.put(XMLGregorianCalendar.class.getName(), this.dateType);
    knownTypes.put(GregorianCalendar.class.getName(), this.dateType);
    knownTypes.put(JsonNode.class.getName(), KnownJsonType.OBJECT);
    knownTypes.put(ContainerNode.class.getName(), KnownJsonType.OBJECT);
    knownTypes.put(ArrayNode.class.getName(), KnownJsonType.ARRAY);
    knownTypes.put(ObjectNode.class.getName(), KnownJsonType.OBJECT);
    knownTypes.put(ValueNode.class.getName(), KnownJsonType.STRING);
    knownTypes.put(TextNode.class.getName(), KnownJsonType.STRING);
    knownTypes.put(BinaryNode.class.getName(), KnownJsonType.STRING);
    knownTypes.put(MissingNode.class.getName(), KnownJsonType.STRING);
    knownTypes.put(NullNode.class.getName(), KnownJsonType.STRING);
    knownTypes.put(NumericNode.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(IntNode.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(DoubleNode.class.getName(), KnownJsonType.NUMBER);
    knownTypes.put(DecimalNode.class.getName(), KnownJsonType.NUMBER);
    knownTypes.put(LongNode.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(BigIntegerNode.class.getName(), KnownJsonType.WHOLE_NUMBER);
    knownTypes.put(POJONode.class.getName(), KnownJsonType.OBJECT);
    knownTypes.put(BooleanNode.class.getName(), KnownJsonType.BOOLEAN);
    knownTypes.put(Class.class.getName(), KnownJsonType.OBJECT);
    knownTypes.put("java.time.Period", KnownJsonType.STRING);
    knownTypes.put("java.time.Duration", this.dateType);
    knownTypes.put("java.time.Instant", this.dateType);
    knownTypes.put("java.time.Year", this.dateType);
    knownTypes.put("java.time.YearMonth", KnownJsonType.STRING);
    knownTypes.put("java.time.MonthDay", KnownJsonType.STRING);
    knownTypes.put("java.time.ZoneId", KnownJsonType.STRING);
    knownTypes.put("java.time.ZoneOffset", KnownJsonType.STRING);
    knownTypes.put("java.time.LocalDate", KnownJsonType.STRING);
    knownTypes.put("java.time.LocalTime", KnownJsonType.STRING);
    knownTypes.put("java.time.LocalDateTime", KnownJsonType.STRING);
    knownTypes.put("java.time.OffsetTime", KnownJsonType.STRING);
    knownTypes.put("java.time.ZonedDateTime", this.dateType);
    knownTypes.put("java.time.OffsetDateTime", this.dateType);
    knownTypes.put("org.joda.time.DateTime", this.dateType);
    knownTypes.put("java.util.Currency", KnownJsonType.STRING);
    for (String m : this.mixins.keySet()) {
        if (knownTypes.remove(m) != null) {
            debug("Unregistering %s from known types, as it is redefined using a mixin.", m);
        }
    }
    return knownTypes;
}
Example 77
Project: jOOQ-master  File: DefaultBinding.java View source code
/**
     * Inlining abstraction
     */
@SuppressWarnings({ "unchecked", "rawtypes" })
private final void toSQL(BindingSQLContext<U> ctx, Object val) {
    SQLDialect family = ctx.family();
    RenderContext render = ctx.render();
    if (render.paramType() == INLINED) {
        if (val == null) {
            render.visit(K_NULL);
        } else if (type == Boolean.class) {
            // [#1153] Some dialects don't support boolean literals TRUE and FALSE
            if (asList(FIREBIRD, SQLITE).contains(family)) {
                render.sql(((Boolean) val) ? "1" : "0");
            } else {
                render.visit(((Boolean) val) ? K_TRUE : K_FALSE);
            }
        } else // [#1154] Binary data cannot always be inlined
        if (type == byte[].class) {
            byte[] binary = (byte[]) val;
            if (asList().contains(family)) {
                render.sql("0x").sql(convertBytesToHex(binary));
            } else if (asList(DERBY, H2, HSQLDB, MARIADB, MYSQL, SQLITE).contains(family)) {
                render.sql("X'").sql(convertBytesToHex(binary)).sql('\'');
            } else if (asList().contains(family)) {
                render.sql("hextoraw('").sql(convertBytesToHex(binary)).sql("')");
            } else if (family == POSTGRES) {
                render.sql("E'").sql(PostgresUtils.toPGString(binary)).sql("'::bytea");
            } else // This default behaviour is used in debug logging for dialects
            // that do not support inlining binary data
            {
                render.sql("X'").sql(convertBytesToHex(binary)).sql('\'');
            }
        } else // Interval extends Number, so let Interval come first!
        if (Interval.class.isAssignableFrom(type)) {
            render.sql('\'').sql(escape(val, render)).sql('\'');
        } else // [#5249] Special inlining of special floating point values
        if (Double.class.isAssignableFrom(type) && ((Double) val).isNaN()) {
            if (POSTGRES == family)
                render.visit(inline("NaN")).sql("::float8");
            else
                render.sql(((Number) val).toString());
        } else // [#5249] Special inlining of special floating point values
        if (Float.class.isAssignableFrom(type) && ((Float) val).isNaN()) {
            if (POSTGRES == family)
                render.visit(inline("NaN")).sql("::float4");
            else
                render.sql(((Number) val).toString());
        } else if (Number.class.isAssignableFrom(type)) {
            render.sql(((Number) val).toString());
        } else // [#1156] DATE / TIME inlining is very vendor-specific
        if (Tools.isDate(type)) {
            Date date = getDate(type, val);
            // [#1253] SQL Server and Sybase do not implement date literals
            if (asList(SQLITE).contains(family)) {
                render.sql('\'').sql(escape(date, render)).sql('\'');
            } else // [#1253] Derby doesn't support the standard literal
            if (family == DERBY) {
                render.visit(K_DATE).sql("('").sql(escape(date, render)).sql("')");
            } else // [#3648] Circumvent a MySQL bug related to date literals
            if (family == MYSQL) {
                render.sql("{d '").sql(escape(date, render)).sql("'}");
            } else // Most dialects implement SQL standard date literals
            {
                render.visit(K_DATE).sql(" '").sql(escape(date, render)).sql('\'');
            }
        } else if (Tools.isTimestamp(type)) {
            Timestamp ts = getTimestamp(type, val);
            // [#1253] SQL Server and Sybase do not implement timestamp literals
            if (asList(SQLITE).contains(family)) {
                render.sql('\'').sql(escape(ts, render)).sql('\'');
            } else // [#1253] Derby doesn't support the standard literal
            if (family == DERBY) {
                render.visit(K_TIMESTAMP).sql("('").sql(escape(ts, render)).sql("')");
            } else // CUBRID timestamps have no fractional seconds
            if (family == CUBRID) {
                render.visit(K_DATETIME).sql(" '").sql(escape(ts, render)).sql('\'');
            } else // [#3648] Circumvent a MySQL bug related to date literals
            if (family == MYSQL) {
                render.sql("{ts '").sql(escape(ts, render)).sql("'}");
            } else // Most dialects implement SQL standard timestamp literals
            {
                render.visit(K_TIMESTAMP).sql(" '").sql(escape(ts, render)).sql('\'');
            }
        } else if (Tools.isTime(type)) {
            Time time = getTime(type, val);
            // [#1253] SQL Server and Sybase do not implement time literals
            if (asList(SQLITE).contains(family)) {
                render.sql('\'').sql(new SimpleDateFormat("HH:mm:ss").format(time)).sql('\'');
            } else // [#1253] Derby doesn't support the standard literal
            if (family == DERBY) {
                render.visit(K_TIME).sql("('").sql(escape(time, render)).sql("')");
            } else // [#3648] Circumvent a MySQL bug related to date literals
            if (family == MYSQL) {
                render.sql("{t '").sql(escape(time, render)).sql("'}");
            } else // Most dialects implement SQL standard time literals
            {
                render.visit(K_TIME).sql(" '").sql(escape(time, render)).sql('\'');
            }
        } else if (type == OffsetDateTime.class) {
            String string = format((OffsetDateTime) val);
            // Some dialects implement SQL standard time literals
            {
                render.visit(K_TIMESTAMP_WITH_TIME_ZONE).sql(" '").sql(escape(string, render)).sql('\'');
            }
        } else if (type == OffsetTime.class) {
            String string = format((OffsetTime) val);
            // Some dialects implement SQL standard time literals
            {
                render.visit(K_TIME_WITH_TIME_ZONE).sql(" '").sql(escape(string, render)).sql('\'');
            }
        } else if (type.isArray()) {
            String separator = "";
            // H2 renders arrays as rows
            if (family == H2) {
                render.sql('(');
                for (Object o : ((Object[]) val)) {
                    render.sql(separator);
                    new DefaultBinding<Object, Object>(Converters.identity((Class) type.getComponentType()), isLob).sql(new DefaultBindingSQLContext<Object>(ctx.configuration(), ctx.data(), ctx.render(), o));
                    separator = ", ";
                }
                render.sql(')');
            } else if (family == POSTGRES) {
                render.visit(cast(inline(PostgresUtils.toPGArrayString((Object[]) val)), type));
            } else // By default, render HSQLDB / POSTGRES syntax
            {
                render.visit(K_ARRAY);
                render.sql('[');
                for (Object o : ((Object[]) val)) {
                    render.sql(separator);
                    new DefaultBinding<Object, Object>(Converters.identity((Class) type.getComponentType()), isLob).sql(new DefaultBindingSQLContext<Object>(ctx.configuration(), ctx.data(), ctx.render(), o));
                    separator = ", ";
                }
                render.sql(']');
                // [#3214] Some PostgreSQL array type literals need explicit casting
                if (family == POSTGRES && EnumType.class.isAssignableFrom(type.getComponentType())) {
                    pgRenderEnumCast(render, type);
                }
            }
        } else if (EnumType.class.isAssignableFrom(type)) {
            String literal = ((EnumType) val).getLiteral();
            if (literal == null) {
                new DefaultBinding<Object, Object>(Converters.identity((Class) String.class), isLob).sql(new DefaultBindingSQLContext<Object>(ctx.configuration(), ctx.data(), ctx.render(), literal));
            } else {
                new DefaultBinding<Object, Object>(Converters.identity((Class) String.class), isLob).sql(new DefaultBindingSQLContext<Object>(ctx.configuration(), ctx.data(), ctx.render(), literal));
            }
        } else if (UDTRecord.class.isAssignableFrom(type)) {
            render.sql("[UDT]");
        } else // Known fall-through types:
        // - Blob, Clob (both not supported by jOOQ)
        // - String
        // - UUID
        {
            render.sql('\'').sql(escape(val, render), true).sql('\'');
        }
    } else // In Postgres, some additional casting must be done in some cases...
    if (family == SQLDialect.POSTGRES) {
        // Postgres needs explicit casting for enum (array) types
        if (EnumType.class.isAssignableFrom(type) || (type.isArray() && EnumType.class.isAssignableFrom(type.getComponentType()))) {
            render.sql(ctx.variable());
            pgRenderEnumCast(render, type);
        } else // ... and also for other array types
        if (type.isArray() && byte[].class != type) {
            render.sql(ctx.variable());
            render.sql("::");
            render.sql(DefaultDataType.getDataType(family, type).getCastTypeName(render.configuration()));
        } else {
            render.sql(ctx.variable());
        }
    } else {
        render.sql(ctx.variable());
    }
}
Example 78
Project: mariadb-connector-j-master  File: TimezoneDaylightSavingTimeTest.java View source code
/**
     * Check results are accurates.
     *
     * @param legacy is in legacy mode
     * @param binaryProtocol binary protocol
     * @param connection connection
     * @return current resultset
     * @throws SQLException if connection error occur.
     */
public ResultSet checkResult(boolean legacy, boolean binaryProtocol, Connection connection) throws SQLException {
    ResultSet rs;
    PreparedStatement pst;
    if (binaryProtocol) {
        pst = connection.prepareStatement("SELECT * from daylight where 1 = ?", ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
    } else {
        MariaDbConnection mariaDbConnection = (MariaDbConnection) connection;
        pst = new MariaDbPreparedStatementClient(mariaDbConnection, "SELECT * from daylight where 1 = ?", ResultSet.TYPE_SCROLL_INSENSITIVE);
    }
    pst.setInt(1, 1);
    rs = pst.executeQuery();
    rs.next();
    //test timestamp(6)
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getTimestamp(2)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(2, Timestamp.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(2, Time.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(2, Date.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(2, Calendar.class).getTime()));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(2, java.util.Date.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getTime(2)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getDate(2)));
    //test time(6)
    assertEquals("1970-01-01T01:45:00.000+0100", formatter.format(rs.getTimestamp(3)));
    assertEquals("1970-01-01T01:45:00.000+0100", formatter.format(rs.getObject(3, Timestamp.class)));
    assertEquals("1970-01-01T01:45:00.000+0100", formatter.format(rs.getObject(3, Time.class)));
    assertEquals("1970-01-01T01:45:00.000+0100", formatter.format(rs.getObject(3, Calendar.class).getTime()));
    assertEquals("1970-01-01T01:45:00.000+0100", formatter.format(rs.getObject(3, java.util.Date.class)));
    try {
        formatter.format(rs.getObject(3, Date.class));
        fail();
    } catch (SQLException e) {
    }
    assertEquals("1970-01-01T01:45:00.000+0100", formatter.format(rs.getTime(3)));
    assertEquals((long) 2700000, rs.getTime(3).getTime());
    try {
        formatter.format(rs.getDate(3));
        fail();
    } catch (SQLException e) {
    }
    //test datetime(6)
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getTimestamp(4)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(4, Timestamp.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(4, Calendar.class).getTime()));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(4, java.util.Date.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(4, Time.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getObject(4, Date.class)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getTime(4)));
    assertEquals("2015-03-29T01:45:00.012+0100", formatter.format(rs.getDate(4)));
    //test date(6)
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getTimestamp(5)));
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getObject(5, Timestamp.class)));
    try {
        formatter.format(rs.getObject(5, Time.class));
        fail();
    } catch (SQLException e) {
    }
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getObject(5, Date.class)));
    try {
        formatter.format(rs.getTime(5));
        fail();
    } catch (SQLException e) {
    }
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getDate(5)));
    assertEquals(new Date(2015 - 1900, 2, 29), rs.getDate(5));
    assertEquals(rs.getString(5), "2015-03-29");
    rs.next();
    //test timestamp(6)
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getTimestamp(2)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getObject(2, Timestamp.class)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getObject(2, Time.class)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getObject(2, Date.class)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getTime(2)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getDate(2)));
    //test time(6)
    assertEquals("1970-01-01T03:15:00.000+0100", formatter.format(rs.getTimestamp(3)));
    assertEquals("1970-01-01T03:15:00.000+0100", formatter.format(rs.getObject(3, Timestamp.class)));
    assertEquals("1970-01-01T03:15:00.000+0100", formatter.format(rs.getObject(3, Time.class)));
    try {
        formatter.format(rs.getObject(3, Date.class));
        fail();
    } catch (SQLException e) {
    }
    assertEquals("1970-01-01T03:15:00.000+0100", formatter.format(rs.getTime(3)));
    assertEquals((long) 8100000, rs.getTime(3).getTime());
    try {
        formatter.format(rs.getDate(3));
        fail();
    } catch (SQLException e) {
    }
    //test datetime(6)
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getTimestamp(4)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getObject(4, Timestamp.class)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getObject(4, Time.class)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getObject(4, Date.class)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getTime(4)));
    assertEquals("2015-03-29T03:15:00.012+0200", formatter.format(rs.getDate(4)));
    //test date(6)
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getTimestamp(5)));
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getObject(5, Timestamp.class)));
    try {
        formatter.format(rs.getObject(5, Time.class));
    } catch (SQLException e) {
    }
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getObject(5, Date.class)));
    try {
        formatter.format(rs.getTime(5));
    } catch (SQLException e) {
    }
    assertEquals("2015-03-29T00:00:00.000+0100", formatter.format(rs.getDate(5)));
    assertEquals(new Date(2015 - 1900, 2, 29), rs.getDate(5));
    assertEquals(rs.getString(5), "2015-03-29");
    rs.next();
    //test timestamp(6)
    for (int i = 2; i < 6; i++) {
        assertNull(rs.getTimestamp(i));
        assertNull(rs.getTime(i));
        assertNull(rs.getDate(i));
        assertNull(rs.getObject(i, Timestamp.class));
        assertNull(rs.getObject(i, Time.class));
        assertNull(rs.getObject(i, Date.class));
        assertNull(rs.getObject(i, Calendar.class));
        assertNull(rs.getObject(i, java.util.Date.class));
    }
    rs.first();
    //additional tests for java 8 objects
    assertEquals("2015-03-29T01:45:00.012340", rs.getTimestamp(2).toLocalDateTime().toString());
    assertEquals("2015-03-29T01:45:00.012340", rs.getObject(2, LocalDateTime.class).toString());
    if (legacy) {
        assertEquals("2015-03-29T01:45:00.012340+01:00[Europe/Paris]", rs.getObject(2, ZonedDateTime.class).toString());
        assertEquals("2015-03-29T01:45:00.012340+01:00", rs.getObject(2, OffsetDateTime.class).toString());
    } else {
        assertEquals("2015-03-28T21:45:00.012340-03:00[Canada/Atlantic]", rs.getObject(2, ZonedDateTime.class).toString());
        assertEquals("2015-03-28T21:45:00.012340-03:00", rs.getObject(2, OffsetDateTime.class).toString());
    }
    assertEquals("01:45:00.012340", rs.getObject(2, LocalTime.class).toString());
    assertEquals("2015-03-29", rs.getObject(2, LocalDate.class).toString());
    rs.next();
    //additional tests for java 8 objects
    assertEquals("2015-03-29T03:15:00.012340", rs.getTimestamp(2).toLocalDateTime().toString());
    assertEquals("2015-03-29T03:15:00.012340", rs.getObject(2, LocalDateTime.class).toString());
    if (legacy) {
        assertEquals("2015-03-29T03:15:00.012340+02:00[Europe/Paris]", rs.getObject(2, ZonedDateTime.class).toString());
        assertEquals("2015-03-29T03:15:00.012340+02:00", rs.getObject(2, OffsetDateTime.class).toString());
    } else {
        assertEquals("2015-03-28T22:15:00.012340-03:00[Canada/Atlantic]", rs.getObject(2, ZonedDateTime.class).toString());
        assertEquals("2015-03-28T22:15:00.012340-03:00", rs.getObject(2, OffsetDateTime.class).toString());
    }
    assertEquals("03:15:00.012340", rs.getObject(2, LocalTime.class).toString());
    assertEquals("2015-03-29", rs.getObject(2, LocalDate.class).toString());
    rs.next();
    //test timestamp(6)
    for (int i = 2; i < 6; i++) {
        assertNull(rs.getObject(i, LocalDateTime.class));
        assertNull(rs.getObject(i, OffsetDateTime.class));
        assertNull(rs.getObject(i, ZonedDateTime.class));
        assertNull(rs.getObject(i, LocalDate.class));
        assertNull(rs.getObject(i, LocalTime.class));
        assertNull(rs.getObject(i, OffsetTime.class));
    }
    return rs;
}
Example 79
Project: mojarra-master  File: DateTimeConverter.java View source code
// --------------------------------------------------------- Private Methods
/**
     * <p>Return a <code>DateFormat</code> instance to use for formatting
     * and parsing in this {@link Converter}.</p>
     *
     * @param locale  The <code>Locale</code> used to select formatting
     *                and parsing conventions
     * @throws ConverterException if no instance can be created
     */
private FormatWrapper getDateFormat(Locale locale) {
    if (pattern == null && type == null) {
        throw new IllegalArgumentException("Either pattern or type must" + " be specified.");
    }
    DateFormat df = null;
    DateTimeFormatter dtf = null;
    TemporalQuery from = null;
    if (pattern != null && !isJavaTimeType(type)) {
        df = new SimpleDateFormat(pattern, locale);
    } else if (type.equals("both")) {
        df = DateFormat.getDateTimeInstance(getStyle(dateStyle), getStyle(timeStyle), locale);
    } else if (type.equals("date")) {
        df = DateFormat.getDateInstance(getStyle(dateStyle), locale);
    } else if (type.equals("time")) {
        df = DateFormat.getTimeInstance(getStyle(timeStyle), locale);
    } else if (type.equals("localDate")) {
        if (null != pattern) {
            dtf = DateTimeFormatter.ofPattern(pattern, locale);
        } else {
            dtf = DateTimeFormatter.ofLocalizedDate(getFormatStyle(dateStyle)).withLocale(locale);
        }
        from = LocalDate::from;
    } else if (type.equals("localDateTime")) {
        if (null != pattern) {
            dtf = DateTimeFormatter.ofPattern(pattern, locale);
        } else {
            dtf = DateTimeFormatter.ofLocalizedDateTime(getFormatStyle(dateStyle), getFormatStyle(timeStyle)).withLocale(locale);
        }
        from = LocalDateTime::from;
    } else if (type.equals("localTime")) {
        if (null != pattern) {
            dtf = DateTimeFormatter.ofPattern(pattern, locale);
        } else {
            dtf = DateTimeFormatter.ofLocalizedTime(getFormatStyle(timeStyle)).withLocale(locale);
        }
        from = LocalTime::from;
    } else if (type.equals("offsetTime")) {
        if (null != pattern) {
            dtf = DateTimeFormatter.ofPattern(pattern, locale);
        } else {
            dtf = DateTimeFormatter.ISO_OFFSET_TIME.withLocale(locale);
        }
        from = OffsetTime::from;
    } else if (type.equals("offsetDateTime")) {
        if (null != pattern) {
            dtf = DateTimeFormatter.ofPattern(pattern, locale);
        } else {
            dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withLocale(locale);
        }
        from = OffsetDateTime::from;
    } else if (type.equals("zonedDateTime")) {
        if (null != pattern) {
            dtf = DateTimeFormatter.ofPattern(pattern, locale);
        } else {
            dtf = DateTimeFormatter.ISO_ZONED_DATE_TIME.withLocale(locale);
        }
        from = ZonedDateTime::from;
    } else {
        // PENDING(craigmcc) - i18n
        throw new IllegalArgumentException("Invalid type: " + type);
    }
    if (null != df) {
        df.setLenient(false);
        return new FormatWrapper(df);
    } else if (null != dtf) {
        return new FormatWrapper(dtf, from);
    }
    // PENDING(craigmcc) - i18n
    throw new IllegalArgumentException("Invalid type: " + type);
}
Example 80
Project: tinkerpop-master  File: AbstractTypedCompatibilityTest.java View source code
@Test
public void shouldReadWriteOffsetDateTime() throws Exception {
    final String resourceName = "offsetdatetime";
    assumeCompatibility(resourceName);
    final OffsetDateTime resource = findModelEntryObject(resourceName);
    final OffsetDateTime fromStatic = read(getCompatibility().readFromResource(resourceName), OffsetDateTime.class);
    final OffsetDateTime recycled = read(write(fromStatic, OffsetDateTime.class), OffsetDateTime.class);
    assertNotSame(fromStatic, recycled);
    assertEquals(fromStatic, recycled);
    assertEquals(resource, fromStatic);
    assertEquals(resource, recycled);
}
Example 81
Project: hbnpojogen-master  File: Core.java View source code
/**
     * @param classes
     */
private static void addImports(TreeMap<String, Clazz> classes) {
    for (Clazz clazz : classes.values()) {
        clazz.getImports().add("javax.persistence.Transient");
        List<String> keySearch = new LinkedList<String>();
        String tmp = clazz.getClassPackage() + "." + clazz.getClassName();
        keySearch.add(tmp);
        keySearch.add("*." + clazz.getClassName());
        keySearch.add(clazz.getClassPackage() + ".*");
        keySearch.add("*.*");
        String classannotation = "";
        for (String key : keySearch) {
            String ann = State.getInstance().customClassAnnotations.get(key);
            if (ann != null) {
                classannotation = String.format("%s\n%s", classannotation, ann);
            }
        }
        State.getInstance().customClassAnnotations.put(tmp, classannotation);
        for (JoinTable joinTable : clazz.getJoinMappings()) {
            clazz.getImports().add(joinTable.getDstProperty().getClazz().getFullClassName());
        }
        if (!clazz.isSubclass()) {
            if (!clazz.isEmbeddable()) {
                if (State.getInstance().isEnableSpringData()) {
                    clazz.getImports().add(SyncUtils.getConfigPackage("", PackageTypeEnum.UTIL) + ".IPojoGenEntity");
                } else {
                    clazz.getImports().add("com.github.wwadge.hbnpojogen.persistence.IPojoGenEntity");
                }
            }
            clazz.getImports().add("java.io.Serializable");
        }
        if (!clazz.isEmbeddable() && !clazz.hasEmbeddableClass()) {
            if (!clazz.isSubclass()) {
                clazz.getImports().add("java.util.Map");
                clazz.getImports().add("java.util.Collections");
                clazz.getImports().add("java.util.WeakHashMap");
            }
            clazz.getImports().add("org.hibernate.proxy.HibernateProxy");
        // clazz.getImports().add(clazz.getDataLayerImplFullClassName());
        }
        boolean didScrubbedEnum = false;
        for (PropertyObj property : clazz.getProperties().values()) {
            if (property.isDefaultValue()) {
                clazz.setDynamicUpdatesInserts(true);
            }
            if (property.isGeneratedValue()) {
                switch(property.getGeneratorType()) {
                    case AUTO:
                        if (!property.isComposite()) {
                            clazz.getImports().add("javax.persistence.GenerationType");
                            clazz.getImports().add("javax.persistence.GeneratedValue");
                        }
                        // no annotation necessary
                        break;
                    case GUID:
                        clazz.setGeneratedValueGUID(true);
                        clazz.getImports().add("javax.persistence.GeneratedValue");
                        break;
                    case CUSTOM:
                        clazz.setGeneratedValueCustom(true);
                        clazz.getImports().add("javax.persistence.GeneratedValue");
                        break;
                    case PKS:
                        clazz.setGeneratedValuePKS(true);
                        clazz.getImports().add("javax.persistence.GeneratedValue");
                        break;
                    case IDAWARE:
                        clazz.setGeneratedValueIDAware(true);
                        clazz.getImports().add("javax.persistence.GeneratedValue");
                        break;
                    case UUID:
                        clazz.setGeneratedValueUUID(true);
                        clazz.getImports().add("javax.persistence.GeneratedValue");
                        clazz.getImports().add("org.hibernate.annotations.Parameter");
                        break;
                    case UUIDWithoutDashes:
                        clazz.setGeneratedValueUUIDWithoutDashes(true);
                        clazz.getImports().add("javax.persistence.GeneratedValue");
                        break;
                    default:
                        break;
                }
            }
            if (property.isOneToMany() && !property.isOneToNBackLinkDisabled()) {
                clazz.getImports().add("javax.persistence.OneToMany");
                clazz.getImports().add("javax.persistence.FetchType");
                if (property.isOneToManyCascadeEnabledByConfig()) {
                    clazz.getImports().add("javax.persistence.CascadeType");
                }
                clazz.getImports().add("java.util.HashSet");
                clazz.getImports().add("java.util.Set");
                if (!property.getOneToManyLink().getClazz().isEmbeddable()) {
                    clazz.getImports().add(property.getOneToManyLink().getClazz().getFullClassName());
                } else {
                    clazz.getImports().add(property.getOneToManyLink().getClazz().getEmbeddedFrom().getFullClassName());
                }
            }
            if (property.isManyToMany() && !property.isOneToNBackLinkDisabled()) {
                clazz.getImports().add("java.util.HashSet");
                clazz.getImports().add("java.util.Set");
                clazz.getImports().add("javax.persistence.FetchType");
                clazz.getImports().add("javax.persistence.ManyToMany");
                if (property.isManyToManyCascadeEnabledByConfig()) {
                    clazz.getImports().add("javax.persistence.CascadeType");
                }
            }
            if (property.isManyToOne() && !property.isManyToMany()) {
                clazz.getImports().add("javax.persistence.JoinColumn");
            }
            if (property.isOneToOne()) {
                clazz.getImports().add("javax.persistence.OneToOne");
                clazz.getImports().add("javax.persistence.FetchType");
                if (!property.isOneTooneInverseSide()) {
                    clazz.getImports().add("javax.persistence.JoinColumn");
                }
                if (property.isOneToOneCascadeEnabledByConfig()) {
                    clazz.getImports().add("javax.persistence.CascadeType");
                }
            }
            if (property.isManyToOne() && property.isManyToOneCascadeEnabledByConfig()) {
                clazz.getImports().add("javax.persistence.CascadeType");
            }
            if (property.isEnumType()) {
                clazz.getImports().add(Core.doEnumImport(clazz.getTableObj().getDbCat(), property.getFieldObj().getEnumName()));
                if (clazz.getTableObj().isContainsScrubbedEnum()) {
                    if (!didScrubbedEnum) {
                        didScrubbedEnum = true;
                        enumTypedefImport(classes, clazz, tmp);
                    }
                } else {
                    clazz.getImports().add("javax.persistence.Enumerated");
                    clazz.getImports().add("javax.persistence.EnumType");
                }
            }
            if (property.isArrayType()) {
                clazz.getImports().add("java.util.Arrays");
            }
            if (property.isTransientField()) {
                clazz.getImports().add("javax.persistence.Transient");
            }
            if ((property.getJavaType() != null) && property.getJavaType().equalsIgnoreCase(Constants.DATE)) {
                clazz.getImports().add("java.util.Date");
            }
            if ((property.getJavaType() != null) && property.getJavaType().equalsIgnoreCase(Constants.LOCALDATE)) {
                if (State.getInstance().isEnableJDK8Support()) {
                    clazz.getImports().add("java.time.LocalDate");
                } else {
                    clazz.getImports().add("org.joda.time.LocalDate");
                }
                clazz.getImports().add("org.hibernate.annotations.Type");
            }
            if ((property.getJavaType() != null) && (property.getJavaType().equalsIgnoreCase(Constants.DATETIME) || property.getJavaType().equalsIgnoreCase(Constants.OFFSETDATETIME))) {
                if (State.getInstance().isEnableJDK8Support()) {
                    clazz.getImports().add("java.time.OffsetDateTime");
                } else {
                    clazz.getImports().add("org.joda.time.DateTime");
                }
                clazz.getImports().add("org.hibernate.annotations.Type");
            }
            if (!property.getColumnAnnotation().equals("")) {
                clazz.getImports().add("javax.persistence.Column");
            }
            if (!property.isNullable()) {
                clazz.getImports().add("javax.persistence.Basic");
            }
            if (State.getInstance().isEnableHibernateValidator()) {
                if (!property.getValidatorAnnotations().isEmpty()) {
                    if (!property.isManyToOne() && !property.isManyToMany() && !property.isPFK() && !property.isOneToOne()) {
                        if (!property.isNullable()) {
                            clazz.getImports().add("com.github.wwadge.hbnpojogen.persistence.validator.Mandatory");
                        }
                    }
                    if (property.isValidatorAnnotated()) {
                        clazz.getImports().add("org.hibernate.validator.Valid");
                    }
                    if (property.hasLength()) {
                        clazz.getImports().add("org.hibernate.validator.Length");
                    }
                }
            }
        }
        //			else {
        //				clazz.setClassAnnotation("");
        //			}
        String classCustomCode = State.getInstance().customClassCode.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (classCustomCode != null) {
            clazz.setClassCustomCode(classCustomCode);
        } else {
            clazz.setClassCustomCode("");
        }
        String classCustomCodeFields = State.getInstance().customClassCodeFields.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (classCustomCode != null) {
            //				System.out.println(clazz.getClassPackage() + "."
            //						+ clazz.getClassName());
            clazz.setClassCustomCodeFields(classCustomCodeFields);
        } else {
            clazz.setClassCustomCodeFields("");
        }
        for (String key : keySearch) {
            TreeSet<String> customClassImports = State.getInstance().customClassImports.get(key);
            if (customClassImports != null) {
                clazz.getImports().addAll(customClassImports);
            }
        }
        TreeSet<String> customInterfaces = State.getInstance().customClassInterfaces.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (customInterfaces != null) {
            clazz.getCustomInterfaces().addAll(customInterfaces);
        }
        customInterfaces = State.getInstance().customClassInterfaces.get(clazz.getClassPackage() + ".*");
        if (customInterfaces != null) {
            clazz.getCustomInterfaces().addAll(customInterfaces);
        }
        customInterfaces = State.getInstance().customClassInterfaces.get("*." + clazz.getClassName());
        if (customInterfaces != null) {
            clazz.getCustomInterfaces().addAll(customInterfaces);
        }
        customInterfaces = State.getInstance().customClassInterfaces.get("*.*");
        if (customInterfaces != null) {
            clazz.getCustomInterfaces().addAll(customInterfaces);
        }
        TreeSet<String> customExtends = State.getInstance().customClassExtends.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (customExtends != null) {
            clazz.getCustomExtends().addAll(customExtends);
        }
        customExtends = State.getInstance().customClassExtends.get(clazz.getClassPackage() + ".*");
        if (customExtends != null) {
            clazz.getCustomExtends().addAll(customExtends);
        }
        customExtends = State.getInstance().customClassExtends.get("*." + clazz.getClassName());
        if (customExtends != null) {
            clazz.getCustomExtends().addAll(customExtends);
        }
        customExtends = State.getInstance().customClassExtends.get("*.*");
        if (customExtends != null) {
            clazz.getCustomExtends().addAll(customExtends);
        }
        TreeMap<String, CustomAnnotations> annotation = State.getInstance().customAnnotations.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (annotation == null) {
            annotation = State.getInstance().customAnnotations.get("*." + clazz.getClassName());
            if (annotation == null) {
                annotation = State.getInstance().customAnnotations.get(clazz.getClassPackage() + ".*");
                if (annotation == null) {
                    annotation = State.getInstance().customAnnotations.get("*.*");
                }
            }
        }
        if (annotation != null) {
            // we have some custom annotation
            for (Entry<String, PropertyObj> property : clazz.getProperties().entrySet()) {
                CustomAnnotations settings = annotation.get(property.getValue().getJavaName());
                if (settings != null) {
                    property.getValue().getPropertyLevelAnnotations().addAll(settings.getPropertyLevelAnnotations());
                    property.getValue().getMethodLevelAnnotationsOnGetters().addAll(settings.getMethodLevelAnnotationsOnGetters());
                    property.getValue().getMethodLevelAnnotationsOnSetters().addAll(settings.getMethodLevelAnnotationsOnSetters());
                    property.getValue().getMethodLevelSettersPrecondition().addAll(settings.getMethodLevelSetterPrecondition());
                    property.getValue().getMethodLevelGettersPrecondition().addAll(settings.getMethodLevelGetterPrecondition());
                    property.getValue().getMethodLevelSettersPostcondition().addAll(settings.getMethodLevelSetterPostcondition());
                    property.getValue().getMethodLevelGettersPostcondition().addAll(settings.getMethodLevelGetterPostcondition());
                }
            }
        }
        String classAnnotation = State.getInstance().customClassAnnotations.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (classAnnotation != null) {
            clazz.getClassAnnotation().add(classAnnotation);
        }
        String typeDefAnnotation = State.getInstance().classTypeDefsAnnotations.get(clazz.getClassPackage() + "." + clazz.getClassName());
        if (typeDefAnnotation != null) {
            clazz.getClassTypedefsAnnotation().add(typeDefAnnotation);
        }
    }
}
Example 82
Project: dropwizard-java8-master  File: OffsetDateTimeParam.java View source code
@Override
protected OffsetDateTime parse(final String input) throws Exception {
    return OffsetDateTime.parse(input);
}
Example 83
Project: hibernate-validator-master  File: FutureValidatorForOffsetDateTime.java View source code
@Override
protected OffsetDateTime getReferenceValue(Clock reference) {
    return OffsetDateTime.now(reference);
}
Example 84
Project: kaif-master  File: TimeFixture.java View source code
/**
   * UTC time of 2015
   */
default Instant dayAt(int month, int day) {
    return OffsetDateTime.of(2015, month, day, 0, 0, 0, 0, ZoneOffset.UTC).toInstant();
}
Example 85
Project: javers-master  File: OffsetDateTimeTypeAdapter.java View source code
@Override
public String serialize(OffsetDateTime sourceValue) {
    return sourceValue.format(ISO_FORMAT);
}
Example 86
Project: datanucleus-core-master  File: OffsetDateTimeDateConverter.java View source code
public OffsetDateTime toMemberType(Date date) {
    if (date == null) {
        return null;
    }
    return OffsetDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
Example 87
Project: JXTN-master  File: Timespec.java View source code
public OffsetDateTime toOffsetDateTime() {
    return OffsetDateTime.of(this.toLocalDateTime(), ZoneOffset.UTC);
}
Example 88
Project: problem-spring-web-master  File: ExampleRestController.java View source code
@RequestMapping(path = "/handler-conversion", method = GET)
public ResponseEntity<Void> conversion(@RequestParam("dateTime") final OffsetDateTime dateTime) {
    return ResponseEntity.ok().build();
}
Example 89
Project: chatty-master  File: DateTime.java View source code
/**
     * Parses the time returned from the Twitch API.
     * 
     * http://stackoverflow.com/a/2202300/2375667
     * 
     * Switched to java.time now because DatatypeConverter isn't visible by
     * default in Java 9 anymore.
     *
     * @param time The time string
     * @return The timestamp
     * @throws IllegalArgumentException if the time could not be parsed
     */
public static long parseDatetime(String time) {
    OffsetDateTime odt = OffsetDateTime.parse(time);
    return odt.toInstant().toEpochMilli();
}
Example 90
Project: OG-Commons-master  File: TenorTest.java View source code
//-------------------------------------------------------------------------
public void test_addTo() {
    assertEquals(TENOR_3D.addTo(LocalDate.of(2014, 6, 30)), LocalDate.of(2014, 7, 3));
    assertEquals(TENOR_1W.addTo(OffsetDateTime.of(2014, 6, 30, 0, 0, 0, 0, ZoneOffset.UTC)), OffsetDateTime.of(2014, 7, 7, 0, 0, 0, 0, ZoneOffset.UTC));
}
Example 91
Project: Strata-master  File: TenorTest.java View source code
//-------------------------------------------------------------------------
public void test_addTo() {
    assertEquals(TENOR_3D.addTo(LocalDate.of(2014, 6, 30)), LocalDate.of(2014, 7, 3));
    assertEquals(TENOR_1W.addTo(OffsetDateTime.of(2014, 6, 30, 0, 0, 0, 0, ZoneOffset.UTC)), OffsetDateTime.of(2014, 7, 7, 0, 0, 0, 0, ZoneOffset.UTC));
}