Example usage for org.joda.time DateTime toDateTime

List of usage examples for org.joda.time DateTime toDateTime

Introduction

In this page you can find the example usage for org.joda.time DateTime toDateTime.

Prototype

public DateTime toDateTime(Chronology chronology) 

Source Link

Document

Get this object as a DateTime, returning this if possible.

Usage

From source file:org.apache.abdera2.common.date.DateTimes.java

License:Apache License

/**
 * Converts the given DateTime to the given TimeZone
 *//*from  ww  w.j av a  2 s.c  om*/
public static DateTime toTimeZone(DateTime dt, String id) {
    return dt.toDateTime(DateTimeZone.forID(id));
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.translator.ASTBuilder.java

License:Apache License

public static ASTNode literal(RexLiteral literal, boolean useTypeQualInLiteral) {
    Object val = null;
    int type = 0;
    SqlTypeName sqlType = literal.getType().getSqlTypeName();

    switch (sqlType) {
    case BINARY:// w w w  . ja  v a  2  s  .  c o m
    case DATE:
    case TIME:
    case TIMESTAMP:
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_MONTH:
    case INTERVAL_SECOND:
    case INTERVAL_YEAR:
    case INTERVAL_YEAR_MONTH:
        if (literal.getValue() == null) {
            return ASTBuilder.construct(HiveParser.TOK_NULL, "TOK_NULL").node();
        }
        break;
    case TINYINT:
    case SMALLINT:
    case INTEGER:
    case BIGINT:
    case DOUBLE:
    case DECIMAL:
    case FLOAT:
    case REAL:
    case VARCHAR:
    case CHAR:
    case BOOLEAN:
        if (literal.getValue3() == null) {
            return ASTBuilder.construct(HiveParser.TOK_NULL, "TOK_NULL").node();
        }
    }

    switch (sqlType) {
    case TINYINT:
        if (useTypeQualInLiteral) {
            val = literal.getValue3() + "Y";
        } else {
            val = literal.getValue3();
        }
        type = HiveParser.IntegralLiteral;
        break;
    case SMALLINT:
        if (useTypeQualInLiteral) {
            val = literal.getValue3() + "S";
        } else {
            val = literal.getValue3();
        }
        type = HiveParser.IntegralLiteral;
        break;
    case INTEGER:
        val = literal.getValue3();
        type = HiveParser.IntegralLiteral;
        break;
    case BIGINT:
        if (useTypeQualInLiteral) {
            val = literal.getValue3() + "L";
        } else {
            val = literal.getValue3();
        }
        type = HiveParser.IntegralLiteral;
        break;
    case DOUBLE:
        val = literal.getValue3() + "D";
        type = HiveParser.NumberLiteral;
        break;
    case DECIMAL:
        val = literal.getValue3() + "BD";
        type = HiveParser.NumberLiteral;
        break;
    case FLOAT:
    case REAL:
        val = literal.getValue3();
        type = HiveParser.Number;
        break;
    case VARCHAR:
    case CHAR:
        val = literal.getValue3();
        String escapedVal = BaseSemanticAnalyzer.escapeSQLString(String.valueOf(val));
        type = HiveParser.StringLiteral;
        val = "'" + escapedVal + "'";
        break;
    case BOOLEAN:
        val = literal.getValue3();
        type = ((Boolean) val).booleanValue() ? HiveParser.KW_TRUE : HiveParser.KW_FALSE;
        break;
    case DATE: {
        //Calcite Calendar is always GMT, Hive atm uses JVM local
        final Calendar c = (Calendar) literal.getValue();
        final DateTime dt = new DateTime(c.getTimeInMillis(), DateTimeZone.forTimeZone(c.getTimeZone()));
        type = HiveParser.TOK_DATELITERAL;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        val = df.format(dt.toDateTime(DateTimeZone.getDefault()).toDate());
        val = "'" + val + "'";
    }
        break;
    case TIME:
    case TIMESTAMP: {
        //Calcite Calendar is always GMT, Hive atm uses JVM local
        final Calendar c = (Calendar) literal.getValue();
        final DateTime dt = new DateTime(c.getTimeInMillis(), DateTimeZone.forTimeZone(c.getTimeZone()));
        type = HiveParser.TOK_TIMESTAMPLITERAL;
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        val = df.format(dt.toDateTime(DateTimeZone.getDefault()).toDate());
        val = "'" + val + "'";
    }
        break;
    case INTERVAL_YEAR:
    case INTERVAL_MONTH:
    case INTERVAL_YEAR_MONTH: {
        type = HiveParser.TOK_INTERVAL_YEAR_MONTH_LITERAL;
        BigDecimal monthsBd = (BigDecimal) literal.getValue();
        HiveIntervalYearMonth intervalYearMonth = new HiveIntervalYearMonth(monthsBd.intValue());
        val = "'" + intervalYearMonth.toString() + "'";
    }
        break;
    case INTERVAL_DAY:
    case INTERVAL_DAY_HOUR:
    case INTERVAL_DAY_MINUTE:
    case INTERVAL_DAY_SECOND:
    case INTERVAL_HOUR:
    case INTERVAL_HOUR_MINUTE:
    case INTERVAL_HOUR_SECOND:
    case INTERVAL_MINUTE:
    case INTERVAL_MINUTE_SECOND:
    case INTERVAL_SECOND: {
        type = HiveParser.TOK_INTERVAL_DAY_TIME_LITERAL;
        BigDecimal millisBd = (BigDecimal) literal.getValue();

        // Calcite literal is in millis, convert to seconds
        BigDecimal secsBd = millisBd.divide(BigDecimal.valueOf(1000));
        HiveIntervalDayTime intervalDayTime = new HiveIntervalDayTime(secsBd);
        val = "'" + intervalDayTime.toString() + "'";
    }
        break;
    case NULL:
        type = HiveParser.TOK_NULL;
        break;

    //binary type should not be seen.
    case BINARY:
    default:
        throw new RuntimeException("Unsupported Type: " + sqlType);
    }

    return (ASTNode) ParseDriver.adaptor.create(type, String.valueOf(val));
}

From source file:org.apache.rya.indexing.geotemporal.model.EventQueryNode.java

License:Apache License

@Override
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final BindingSet bindings)
        throws QueryEvaluationException {
    final List<BindingSet> list = new ArrayList<>();
    try {/*from   ww  w.ja v a2  s .com*/
        final Collection<Event> searchEvents;
        final String subj;
        //if the provided binding set has the subject already, set it to the constant subject.
        if (!subjectConstant.isPresent() && bindings.hasBinding(subjectVar.get())) {
            subjectConstant = Optional.of(bindings.getValue(subjectVar.get()).stringValue());
        } else if (bindings.size() != 0) {
            list.add(bindings);
        }

        // If the subject needs to be filled in, check if the subject variable is in the binding set.
        if (subjectConstant.isPresent()) {
            // if it is, fetch that value and then fetch the entity for the subject.
            subj = subjectConstant.get();
            searchEvents = eventStore.search(Optional.of(new RyaURI(subj)), Optional.of(geoFilters),
                    Optional.of(temporalFilters));
        } else {
            searchEvents = eventStore.search(Optional.empty(), Optional.of(geoFilters),
                    Optional.of(temporalFilters));
        }

        for (final Event event : searchEvents) {
            final MapBindingSet resultSet = new MapBindingSet();
            if (event.getGeometry().isPresent()) {
                final Geometry geo = event.getGeometry().get();
                final Value geoValue = ValueFactoryImpl.getInstance().createLiteral(geo.toText());
                final Var geoObj = geoPattern.getObjectVar();
                resultSet.addBinding(geoObj.getName(), geoValue);
            }

            final Value temporalValue;
            if (event.isInstant() && event.getInstant().isPresent()) {
                final Optional<TemporalInstant> opt = event.getInstant();
                DateTime dt = opt.get().getAsDateTime();
                dt = dt.toDateTime(DateTimeZone.UTC);
                final String str = dt.toString(TemporalInstantRfc3339.FORMATTER);
                temporalValue = ValueFactoryImpl.getInstance().createLiteral(str);
            } else if (event.getInterval().isPresent()) {
                temporalValue = ValueFactoryImpl.getInstance()
                        .createLiteral(event.getInterval().get().getAsPair());
            } else {
                temporalValue = null;
            }

            if (temporalValue != null) {
                final Var temporalObj = temporalPattern.getObjectVar();
                resultSet.addBinding(temporalObj.getName(), temporalValue);
            }
            list.add(resultSet);
        }
    } catch (final ObjectStorageException e) {
        throw new QueryEvaluationException("Failed to evaluate the binding set", e);
    }
    return new CollectionIteration<>(list);
}

From source file:org.assertj.jodatime.api.DateTimeAssert.java

License:Apache License

/**
 * Verifies that actual and given {@code DateTime} have same year, month, day, hour, minute and second fields,
 * (millisecond fields are ignored in comparison).
 * <p>/*from ww  w. j a v a  2  s. c o m*/
 * Note that given {@link DateTime} is converted in the actual's {@link DateTimeZone} before comparison.
 * <p>
 * Assertion can fail with dateTimes in same chronological millisecond time window, e.g :
 * <p>
 * 2000-01-01T00:00:<b>01.000</b> and 2000-01-01T00:00:<b>00.999</b>.
 * <p>
 * Assertion fails as second fields differ even if time difference is only 1ms.
 * <p>
 * Code example :
 * <pre><code class='java'> // successfull assertions
 * DateTime dateTime1 = new DateTime(2000, 1, 1, 0, 0, 1, 0);
 * DateTime dateTime2 = new DateTime(2000, 1, 1, 0, 0, 1, 456);
 * assertThat(dateTime1).isEqualToIgnoringMillis(dateTime2);
 * 
 * // failing assertions (even if time difference is only 1ms)
 * DateTime dateTimeA = new DateTime(2000, 1, 1, 0, 0, 1, 0);
 * DateTime dateTimeB = new DateTime(2000, 1, 1, 0, 0, 0, 999);
 * assertThat(dateTimeA).isEqualToIgnoringMillis(dateTimeB);</code></pre>
 * 
 * @param other the given {@link DateTime}.
 * @return this assertion object.
 * @throws AssertionError if the actual {@code DateTime} is {@code null}.
 * @throws IllegalArgumentException if other {@code DateTime} is {@code null}.
 * @throws AssertionError if the actual {@code DateTime} is are not equal with milliseconds ignored.
 */
public DateTimeAssert isEqualToIgnoringMillis(DateTime other) {
    Objects.instance().assertNotNull(info, actual);
    assertDateTimeParameterIsNotNull(other);
    if (!areEqualIgnoringMillis(actual, other.toDateTime(actual.getZone()))) {
        throw Failures.instance().failure(info, shouldBeEqualIgnoringMillis(actual, other));
    }
    return this;
}

From source file:org.assertj.jodatime.api.DateTimeAssert.java

License:Apache License

/**
 * Verifies that actual and given {@link DateTime} have same year, month, day, hour and minute fields (second and
 * millisecond fields are ignored in comparison).
 * <p>//from   ww w  . jav a2  s. c  o m
 * Note that given {@link DateTime} is converted in the actual's {@link DateTimeZone} before comparison.
 * <p>
 * Assertion can fail with DateTimes in same chronological second time window, e.g :
 * <p>
 * 2000-01-01T00:<b>01:00</b>.000 and 2000-01-01T00:<b>00:59</b>.000.
 * <p>
 * Assertion fails as minute fields differ even if time difference is only 1s.
 * <p>
 * Code example :
 * <pre><code class='java'> // successfull assertions
 * DateTime dateTime1 = new DateTime(2000, 1, 1, 23, 50, 0, 0);
 * DateTime dateTime2 = new DateTime(2000, 1, 1, 23, 50, 10, 456);
 * assertThat(dateTime1).isEqualToIgnoringSeconds(dateTime2);
 * 
 * // failing assertions (even if time difference is only 1ms)
 * DateTime dateTimeA = new DateTime(2000, 1, 1, 23, 50, 00, 000);
 * DateTime dateTimeB = new DateTime(2000, 1, 1, 23, 49, 59, 999);
 * assertThat(dateTimeA).isEqualToIgnoringSeconds(dateTimeB);</code></pre>
 * 
 * @param other the given {@link DateTime}.
 * @return this assertion object.
 * @throws AssertionError if the actual {@code DateTime} is {@code null}.
 * @throws IllegalArgumentException if other {@code DateTime} is {@code null}.
 * @throws AssertionError if the actual {@code DateTime} is are not equal with second and millisecond fields ignored.
 */
public DateTimeAssert isEqualToIgnoringSeconds(DateTime other) {
    Objects.instance().assertNotNull(info, actual);
    assertDateTimeParameterIsNotNull(other);
    if (!areEqualIgnoringSeconds(actual, other.toDateTime(actual.getZone()))) {
        throw Failures.instance().failure(info, shouldBeEqualIgnoringSeconds(actual, other));
    }
    return this;
}

From source file:org.assertj.jodatime.api.DateTimeAssert.java

License:Apache License

/**
 * Verifies that actual and given {@code DateTime} have same year, month, day and hour fields (minute, second and
 * millisecond fields are ignored in comparison).
 * <p>//from w w w  .ja  v  a 2 s. co m
 * Note that given {@link DateTime} is converted in the actual's {@link DateTimeZone} before comparison.
 * <p>
 * Assertion can fail with dateTimes in same chronological second time window, e.g :
 * <p>
 * 2000-01-01T<b>01:00</b>:00.000 and 2000-01-01T<b>00:59:59</b>.000.
 * <p>
 * Time difference is only 1s but hour fields differ.
 * <p>
 * Code example :
 * <pre><code class='java'> // successfull assertions
 * DateTime dateTime1 = new DateTime(2000, 1, 1, 23, 50, 0, 0);
 * DateTime dateTime2 = new DateTime(2000, 1, 1, 23, 00, 2, 7);
 * assertThat(dateTime1).isEqualToIgnoringMinutes(dateTime2);
 * 
 * // failing assertions (even if time difference is only 1ms)
 * DateTime dateTimeA = new DateTime(2000, 1, 1, 01, 00, 00, 000);
 * DateTime dateTimeB = new DateTime(2000, 1, 1, 00, 59, 59, 999);
 * assertThat(dateTimeA).isEqualToIgnoringMinutes(dateTimeB);</code></pre>
 * 
 * @param other the given {@link DateTime}.
 * @return this assertion object.
 * @throws AssertionError if the actual {@code DateTime} is {@code null}.
 * @throws IllegalArgumentException if other {@code DateTime} is {@code null}.
 * @throws AssertionError if the actual {@code DateTime} is are not equal ignoring minute, second and millisecond
 *           fields.
 */
public DateTimeAssert isEqualToIgnoringMinutes(DateTime other) {
    Objects.instance().assertNotNull(info, actual);
    assertDateTimeParameterIsNotNull(other);
    if (!areEqualIgnoringMinutes(actual, other.toDateTime(actual.getZone()))) {
        throw Failures.instance().failure(info, shouldBeEqualIgnoringMinutes(actual, other));
    }
    return this;
}

From source file:org.assertj.jodatime.api.DateTimeAssert.java

License:Apache License

/**
 * Verifies that actual and given {@code DateTime} have same year, month and day fields (hour, minute, second and
 * millisecond fields are ignored in comparison).
 * <p>/*  ww w  .  j a v  a 2  s  .c o m*/
 * Note that given {@link DateTime} is converted in the actual's {@link DateTimeZone} before comparison.
 * <p>
 * Assertion can fail with dateTimes in same chronological minute time window, e.g :
 * <p>
 * 2000-01-<b>01T23:59</b>:00.000 and 2000-01-02T<b>00:00</b>:00.000.
 * <p>
 * Time difference is only 1min but day fields differ.
 * <p>
 * Code example :
 * <pre><code class='java'> // successfull assertions
 * DateTime dateTime1 = new DateTime(2000, 1, 1, 23, 59, 59, 999);
 * DateTime dateTime2 = new DateTime(2000, 1, 1, 00, 00, 00, 000);
 * assertThat(dateTime1).isEqualToIgnoringHours(dateTime2);
 * 
 * // failing assertions (even if time difference is only 1ms)
 * DateTime dateTimeA = new DateTime(2000, 1, 2, 00, 00, 00, 000);
 * DateTime dateTimeB = new DateTime(2000, 1, 1, 23, 59, 59, 999);
 * assertThat(dateTimeA).isEqualToIgnoringHours(dateTimeB);</code></pre>
 * 
 * @param other the given {@link DateTime}.
 * @return this assertion object.
 * @throws AssertionError if the actual {@code DateTime} is {@code null}.
 * @throws IllegalArgumentException if other {@code DateTime} is {@code null}.
 * @throws AssertionError if the actual {@code DateTime} is are not equal with second and millisecond fields ignored.
 */
public DateTimeAssert isEqualToIgnoringHours(DateTime other) {
    Objects.instance().assertNotNull(info, actual);
    assertDateTimeParameterIsNotNull(other);
    if (!haveSameYearMonthAndDayOfMonth(actual, other.toDateTime(actual.getZone()))) {
        throw Failures.instance().failure(info, shouldBeEqualIgnoringHours(actual, other));
    }
    return this;
}

From source file:org.atlasapi.persistence.content.mongo.MongoDBQueryBuilder.java

License:Apache License

private List<ConstrainedAttribute> buildQueries(ContentQuery query) {
    return query.accept(new QueryVisitor<ConstrainedAttribute>() {

        @Override//from w ww .  jav  a  2 s  .  c  o  m
        @SuppressWarnings("unchecked")
        public ConstrainedAttribute visit(IntegerAttributeQuery query) {
            final List<Integer> values = (List<Integer>) query.getValue();

            BasicDBObject rhs = query.accept(new IntegerOperatorVisitor<BasicDBObject>() {

                @Override
                public BasicDBObject visit(Equals equals) {
                    return new BasicDBObject(IN, list(values));
                }

                @Override
                public BasicDBObject visit(LessThan lessThan) {
                    return new BasicDBObject(LESS_THAN, Collections.max(values));
                }

                @Override
                public BasicDBObject visit(GreaterThan greaterThan) {
                    return new BasicDBObject(GREATER_THAN, Collections.min(values));
                }
            });

            return new ConstrainedAttribute(query.getAttribute(), rhs);
        }

        @Override
        public ConstrainedAttribute visit(final StringAttributeQuery query) {
            final BasicDBList values = new BasicDBList();
            values.addAll(query.getValue());

            return query.accept(new StringOperatorVisitor<ConstrainedAttribute>() {

                @Override
                public ConstrainedAttribute visit(Equals equals) {
                    return new ConstrainedAttribute(query.getAttribute(), new BasicDBObject(IN, values));
                }

                @Override
                public ConstrainedAttribute visit(Beginning beginning) {
                    Pattern pattern = Pattern.compile("^" + (String) query.getValue().get(0),
                            Pattern.CASE_INSENSITIVE);
                    return new ConstrainedAttribute(query.getAttribute(), pattern);
                }
            });

        }

        @Override
        public ConstrainedAttribute visit(final BooleanAttributeQuery query) {

            if (query.isUnconditionallyTrue()) {
                return null;
            }

            final Boolean value = (Boolean) query.getValue().get(0);

            return query.accept(new BooleanOperatorVisitor<ConstrainedAttribute>() {

                @Override
                public ConstrainedAttribute visit(Equals equals) {
                    return new ConstrainedAttribute(query.getAttribute(), value);
                }
            });

        }

        @Override
        @SuppressWarnings("unchecked")
        public ConstrainedAttribute visit(final EnumAttributeQuery<?> query) {

            final List<Enum<?>> values = (List<Enum<?>>) query.getValue();

            return query.accept(new EnumOperatorVisitor<ConstrainedAttribute>() {

                @Override
                public ConstrainedAttribute visit(Equals equals) {
                    return new ConstrainedAttribute(query.getAttribute(),
                            new BasicDBObject(IN, list(toLowercaseStrings(values))));
                }

                private Collection<?> toLowercaseStrings(Collection<Enum<?>> values) {
                    List<String> strings = Lists.newArrayList();
                    for (Enum<?> value : values) {
                        strings.add(value.toString().toLowerCase());
                    }
                    return strings;
                }
            });
        }

        @SuppressWarnings("unchecked")
        @Override
        public ConstrainedAttribute visit(DateTimeAttributeQuery query) {
            final List<Date> values = toDate((List<DateTime>) query.getValue());

            BasicDBObject rhs = query.accept(new DateTimeOperatorVisitor<BasicDBObject>() {

                @Override
                public BasicDBObject visit(Before before) {
                    return new BasicDBObject(LESS_THAN, Collections.max(values));
                }

                @Override
                public BasicDBObject visit(After after) {
                    return new BasicDBObject(GREATER_THAN, Collections.min(values));
                }

                @Override
                public BasicDBObject visit(Equals equals) {
                    throw new UnsupportedOperationException();
                }
            });
            return new ConstrainedAttribute(query.getAttribute(), rhs);
        }

        private List<Date> toDate(List<DateTime> values) {
            return Lists.transform(values, new Function<DateTime, Date>() {
                @Override
                public Date apply(DateTime time) {
                    return time.toDateTime(DateTimeZones.UTC).toDate();
                }
            });
        }

        @Override
        public ConstrainedAttribute visit(MatchesNothing noOp) {
            throw new IllegalArgumentException();
        }
    });
}

From source file:org.codehaus.httpcache4j.Conditionals.java

License:Open Source License

/**
 * You should use the server's time here. Otherwise you might get unexpected results.
 * The typical use case is: <br/>/*from w w  w .ja  v  a  2 s.co m*/
 * <pre>
 *   HTTPResponse response = ....
 *   HTTPRequest request = createRequest();
 *   request = request.conditionals(new Conditionals().ifModifiedSince(response.getLastModified());
 * </pre>
 *
 * @param time the time to check.
 * @return the conditionals with the If-Modified-Since date set.
 */
public Conditionals ifModifiedSince(DateTime time) {
    Validate.isTrue(match.isEmpty(),
            String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH));
    Validate.isTrue(unModifiedSince == null, String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE,
            HeaderConstants.IF_UNMODIFIED_SINCE));
    time = time.toDateTime(DateTimeZone.forID("UTC"));
    time = time.withMillisOfSecond(0);
    return new Conditionals(empty(), noneMatch, time, null);
}

From source file:org.codehaus.httpcache4j.Conditionals.java

License:Open Source License

/**
 * You should use the server's time here. Otherwise you might get unexpected results.
 * The typical use case is: <br/>/*from  w  w  w . jav  a 2 s.c  om*/
 * <pre>
 *   HTTPResponse response = ....
 *   HTTPRequest request = createRequest();
 *   request = request.conditionals(new Conditionals().ifUnModifiedSince(response.getLastModified());
 * </pre>
 *
 * @param time the time to check.
 * @return the conditionals with the If-Unmodified-Since date set.
 */
public Conditionals ifUnModifiedSince(DateTime time) {
    Validate.isTrue(noneMatch.isEmpty(),
            String.format(ERROR_MESSAGE, HeaderConstants.IF_UNMODIFIED_SINCE, HeaderConstants.IF_NON_MATCH));
    Validate.isTrue(modifiedSince == null, String.format(ERROR_MESSAGE, HeaderConstants.IF_UNMODIFIED_SINCE,
            HeaderConstants.IF_MODIFIED_SINCE));
    time = time.toDateTime(DateTimeZone.forID("UTC"));
    time = time.withMillisOfSecond(0);
    return new Conditionals(match, empty(), null, time);
}