List of usage examples for org.joda.time Period days
public static Period days(int days)
From source file:io.druid.sql.calcite.expression.builtin.CastOperatorConversion.java
License:Apache License
private static DruidExpression castCharToDateTime(final PlannerContext plannerContext, final DruidExpression operand, final SqlTypeName toType) { // Cast strings to datetimes by parsing them from SQL format. final DruidExpression timestampExpression = DruidExpression.fromFunctionCall("timestamp_parse", ImmutableList.of(operand, DruidExpression.fromExpression(DruidExpression.nullLiteral()), DruidExpression.fromExpression( DruidExpression.stringLiteral(plannerContext.getTimeZone().getID())))); if (toType == SqlTypeName.DATE) { return TimeFloorOperatorConversion.applyTimestampFloor(timestampExpression, new PeriodGranularity(Period.days(1), null, plannerContext.getTimeZone()), plannerContext.getExprMacroTable()); } else if (toType == SqlTypeName.TIMESTAMP) { return timestampExpression; } else {/*from w ww. ja v a 2 s . c o m*/ throw new ISE("Unsupported DateTime type[%s]", toType); } }
From source file:io.druid.sql.calcite.expression.builtin.TimeFloorOperatorConversion.java
License:Apache License
public static DruidExpression applyTimestampFloor(final DruidExpression input, final PeriodGranularity granularity, final ExprMacroTable macroTable) { Preconditions.checkNotNull(input, "input"); Preconditions.checkNotNull(granularity, "granularity"); // Collapse floor chains if possible. Useful for constructs like CAST(FLOOR(__time TO QUARTER) AS DATE). if (granularity.getPeriod().equals(Period.days(1))) { final TimestampFloorExprMacro.TimestampFloorExpr floorExpr = Expressions.asTimestampFloorExpr(input, macroTable);/*from ww w .j ava2 s . c o m*/ if (floorExpr != null) { final PeriodGranularity inputGranularity = floorExpr.getGranularity(); if (Objects.equals(inputGranularity.getTimeZone(), granularity.getTimeZone()) && Objects.equals(inputGranularity.getOrigin(), granularity.getOrigin()) && periodIsDayMultiple(inputGranularity.getPeriod())) { return input; } } } return DruidExpression.fromFunctionCall("timestamp_floor", ImmutableList .of(input.getExpression(), DruidExpression.stringLiteral(granularity.getPeriod().toString()), DruidExpression.numberLiteral(granularity.getOrigin() == null ? null : granularity.getOrigin().getMillis()), DruidExpression.stringLiteral(granularity.getTimeZone().toString())) .stream().map(DruidExpression::fromExpression).collect(Collectors.toList())); }
From source file:io.druid.sql.calcite.expression.Expressions.java
License:Apache License
/** * Translate a Calcite {@code RexNode} to a Druid expressions. * * @param plannerContext SQL planner context * @param rowSignature signature of the rows to be extracted from * @param rexNode expression meant to be applied on top of the rows * * @return rexNode referring to fields in rowOrder, or null if not possible *///from w ww.j a va 2 s . co m @Nullable public static DruidExpression toDruidExpression(final PlannerContext plannerContext, final RowSignature rowSignature, final RexNode rexNode) { final SqlKind kind = rexNode.getKind(); final SqlTypeName sqlTypeName = rexNode.getType().getSqlTypeName(); if (kind == SqlKind.INPUT_REF) { // Translate field references. final RexInputRef ref = (RexInputRef) rexNode; final String columnName = rowSignature.getRowOrder().get(ref.getIndex()); if (columnName == null) { throw new ISE("WTF?! Expression referred to nonexistent index[%d]", ref.getIndex()); } return DruidExpression.fromColumn(columnName); } else if (kind == SqlKind.CAST || kind == SqlKind.REINTERPRET) { // Translate casts. final RexNode operand = ((RexCall) rexNode).getOperands().get(0); final DruidExpression operandExpression = toDruidExpression(plannerContext, rowSignature, operand); if (operandExpression == null) { return null; } final SqlTypeName fromType = operand.getType().getSqlTypeName(); final SqlTypeName toType = rexNode.getType().getSqlTypeName(); if (SqlTypeName.CHAR_TYPES.contains(fromType) && SqlTypeName.DATETIME_TYPES.contains(toType)) { // Cast strings to datetimes by parsing them from SQL format. final DruidExpression timestampExpression = DruidExpression.fromFunctionCall("timestamp_parse", ImmutableList.of(operandExpression, DruidExpression .fromExpression(DruidExpression.stringLiteral(dateTimeFormatString(toType))))); if (toType == SqlTypeName.DATE) { return TimeFloorOperatorConversion.applyTimestampFloor(timestampExpression, new PeriodGranularity(Period.days(1), null, plannerContext.getTimeZone())); } else { return timestampExpression; } } else if (SqlTypeName.DATETIME_TYPES.contains(fromType) && SqlTypeName.CHAR_TYPES.contains(toType)) { // Cast datetimes to strings by formatting them in SQL format. return DruidExpression.fromFunctionCall("timestamp_format", ImmutableList.of(operandExpression, DruidExpression .fromExpression(DruidExpression.stringLiteral(dateTimeFormatString(fromType))))); } else { // Handle other casts. final ExprType fromExprType = exprTypeForValueType(Calcites.getValueTypeForSqlTypeName(fromType)); final ExprType toExprType = exprTypeForValueType(Calcites.getValueTypeForSqlTypeName(toType)); if (fromExprType == null || toExprType == null) { // We have no runtime type for these SQL types. return null; } final DruidExpression typeCastExpression; if (fromExprType != toExprType) { // Ignore casts for simple extractions (use Function.identity) since it is ok in many cases. typeCastExpression = operandExpression.map(Function.identity(), expression -> String.format("CAST(%s, '%s')", expression, toExprType.toString())); } else { typeCastExpression = operandExpression; } if (toType == SqlTypeName.DATE) { // Floor to day when casting to DATE. return TimeFloorOperatorConversion.applyTimestampFloor(typeCastExpression, new PeriodGranularity(Period.days(1), null, plannerContext.getTimeZone())); } else { return typeCastExpression; } } } else if (rexNode instanceof RexCall) { final SqlOperator operator = ((RexCall) rexNode).getOperator(); final SqlOperatorConversion conversion = plannerContext.getOperatorTable() .lookupOperatorConversion(operator); if (conversion != null) { return conversion.toDruidExpression(plannerContext, rowSignature, rexNode); } final List<DruidExpression> operands = Expressions.toDruidExpressions(plannerContext, rowSignature, ((RexCall) rexNode).getOperands()); if (operands == null) { return null; } else if (UNARY_PREFIX_OPERATOR_MAP.containsKey(operator)) { return DruidExpression .fromExpression(String.format("(%s %s)", UNARY_PREFIX_OPERATOR_MAP.get(operator), Iterables.getOnlyElement(operands).getExpression())); } else if (UNARY_SUFFIX_OPERATOR_MAP.containsKey(operator)) { return DruidExpression .fromExpression(String.format("(%s %s)", Iterables.getOnlyElement(operands).getExpression(), UNARY_SUFFIX_OPERATOR_MAP.get(operator))); } else if (BINARY_OPERATOR_MAP.containsKey(operator)) { if (operands.size() != 2) { throw new ISE("WTF?! Got binary operator[%s] with %s args?", kind, operands.size()); } return DruidExpression.fromExpression(String.format("(%s %s %s)", operands.get(0).getExpression(), BINARY_OPERATOR_MAP.get(operator), operands.get(1).getExpression())); } else if (DIRECT_CONVERSIONS.containsKey(operator)) { final String functionName = DIRECT_CONVERSIONS.get(operator); return DruidExpression.fromExpression(DruidExpression.functionCall(functionName, operands)); } else { return null; } } else if (kind == SqlKind.LITERAL) { // Translate literal. if (SqlTypeName.NUMERIC_TYPES.contains(sqlTypeName)) { return DruidExpression .fromExpression(DruidExpression.numberLiteral((Number) RexLiteral.value(rexNode))); } else if (SqlTypeFamily.INTERVAL_DAY_TIME == sqlTypeName.getFamily()) { // Calcite represents DAY-TIME intervals in milliseconds. final long milliseconds = ((Number) RexLiteral.value(rexNode)).longValue(); return DruidExpression.fromExpression(DruidExpression.numberLiteral(milliseconds)); } else if (SqlTypeFamily.INTERVAL_YEAR_MONTH == sqlTypeName.getFamily()) { // Calcite represents YEAR-MONTH intervals in months. final long months = ((Number) RexLiteral.value(rexNode)).longValue(); return DruidExpression.fromExpression(DruidExpression.numberLiteral(months)); } else if (SqlTypeName.STRING_TYPES.contains(sqlTypeName)) { return DruidExpression .fromExpression(DruidExpression.stringLiteral(RexLiteral.stringValue(rexNode))); } else if (SqlTypeName.TIMESTAMP == sqlTypeName || SqlTypeName.DATE == sqlTypeName) { if (RexLiteral.isNullLiteral(rexNode)) { return DruidExpression.fromExpression(DruidExpression.nullLiteral()); } else { return DruidExpression.fromExpression(DruidExpression.numberLiteral(Calcites .calciteDateTimeLiteralToJoda(rexNode, plannerContext.getTimeZone()).getMillis())); } } else if (SqlTypeName.BOOLEAN == sqlTypeName) { return DruidExpression .fromExpression(DruidExpression.numberLiteral(RexLiteral.booleanValue(rexNode) ? 1 : 0)); } else { // Can't translate other literals. return null; } } else { // Can't translate. return null; } }
From source file:io.konig.dao.core.SimpleChartFactory.java
License:Apache License
private Period toPeriod(ShapeQuery query) throws DaoException { String value = query.getParameters().get("timeInterval.durationUnit"); if (value == null) { throw new DaoException("durationUnit is not defined"); }/* ww w . j a v a 2 s.c o m*/ value = value.toLowerCase(); switch (value) { case "second": return Period.seconds(1); case "hour": return Period.hours(1); case "day": return Period.days(1); case "week": return Period.weeks(1); case "month": return Period.months(1); case "quarter": return Period.months(3); case "year": return Period.years(1); } throw new DaoException("Invalid durationUnit: " + value); }
From source file:io.mesosphere.mesos.frameworks.cassandra.framework.Main.java
License:Apache License
private static int _main() throws UnknownHostException { final Optional<String> portOption = Env.option("PORT0"); if (!portOption.isPresent()) { throw new SystemExitException("Environment variable PORT0 must be defined", 5); }//www .j a va 2s .com final int port0 = Integer.parseInt(portOption.get()); final String host = Env.option("HOST").or("localhost"); final int executorCount = Integer.parseInt(Env.option("CASSANDRA_NODE_COUNT").or("3")); final int seedCount = Integer.parseInt(Env.option("CASSANDRA_SEED_COUNT").or("2")); final double resourceCpuCores = Double.parseDouble(Env.option("CASSANDRA_RESOURCE_CPU_CORES").or("2.0")); final long resourceMemoryMegabytes = Long.parseLong(Env.option("CASSANDRA_RESOURCE_MEM_MB").or("2048")); final long resourceDiskMegabytes = Long.parseLong(Env.option("CASSANDRA_RESOURCE_DISK_MB").or("2048")); final long javaHeapMb = Long.parseLong(Env.option("CASSANDRA_RESOURCE_HEAP_MB").or("0")); final long healthCheckIntervalSec = Long .parseLong(Env.option("CASSANDRA_HEALTH_CHECK_INTERVAL_SECONDS").or("60")); final long bootstrapGraceTimeSec = Long .parseLong(Env.option("CASSANDRA_BOOTSTRAP_GRACE_TIME_SECONDS").or("120")); final String cassandraVersion = "2.1.4"; final String frameworkName = frameworkName(Env.option("CASSANDRA_CLUSTER_NAME")); final String zkUrl = Env.option("CASSANDRA_ZK").or("zk://localhost:2181/cassandra-mesos"); final long zkTimeoutMs = Long.parseLong(Env.option("CASSANDRA_ZK_TIMEOUT_MS").or("10000")); final String mesosMasterZkUrl = Env.option("MESOS_ZK").or("zk://localhost:2181/mesos"); final String mesosUser = Env.option("MESOS_USER").or(""); final long failoverTimeout = Long.parseLong(Env.option("CASSANDRA_FAILOVER_TIMEOUT_SECONDS") .or(String.valueOf(Period.days(7).toStandardSeconds().getSeconds()))); final String mesosRole = Env.option("CASSANDRA_FRAMEWORK_MESOS_ROLE").or("*"); final String dataDirectory = Env.option("CASSANDRA_DATA_DIRECTORY").or(DEFAULT_DATA_DIRECTORY); // TODO: Temporary. Will be removed when MESOS-1554 is released final boolean jmxLocal = Boolean.parseBoolean(Env.option("CASSANDRA_JMX_LOCAL").or("true")); final boolean jmxNoAuthentication = Boolean .parseBoolean(Env.option("CASSANDRA_JMX_NO_AUTHENTICATION").or("false")); final String defaultRack = Env.option("CASSANDRA_DEFAULT_RACK").or("RACK0"); final String defaultDc = Env.option("CASSANDRA_DEFAULT_DC").or("DC0"); final List<ExternalDc> externalDcs = getExternalDcs(Env.filterStartsWith("CASSANDRA_EXTERNAL_DC_", true)); final Matcher matcher = validateZkUrl(zkUrl); final State state = new ZooKeeperState(matcher.group(1), zkTimeoutMs, TimeUnit.MILLISECONDS, matcher.group(2)); if (seedCount > executorCount || seedCount <= 0 || executorCount <= 0) { throw new IllegalArgumentException( "number of nodes (" + executorCount + ") and/or number of seeds (" + seedCount + ") invalid"); } final PersistedCassandraFrameworkConfiguration configuration = new PersistedCassandraFrameworkConfiguration( state, frameworkName, healthCheckIntervalSec, bootstrapGraceTimeSec, cassandraVersion, resourceCpuCores, resourceDiskMegabytes, resourceMemoryMegabytes, javaHeapMb, executorCount, seedCount, mesosRole, dataDirectory, jmxLocal, jmxNoAuthentication, defaultRack, defaultDc, externalDcs); final FrameworkInfo.Builder frameworkBuilder = FrameworkInfo.newBuilder() .setFailoverTimeout(failoverTimeout).setUser(mesosUser).setName(frameworkName).setRole(mesosRole) .setCheckpoint(true); final Optional<String> frameworkId = configuration.frameworkId(); if (frameworkId.isPresent()) { frameworkBuilder.setId(frameworkId(frameworkId.get())); } final URI httpServerBaseUri = URI.create("http://" + host + ":" + port0 + "/"); final Clock clock = new SystemClock(); final PersistedCassandraClusterHealthCheckHistory healthCheckHistory = new PersistedCassandraClusterHealthCheckHistory( state); final PersistedCassandraClusterState clusterState = new PersistedCassandraClusterState(state); final SeedManager seedManager = new SeedManager(configuration, new ObjectMapper(), new SystemClock()); final CassandraCluster cassandraCluster = new CassandraCluster(clock, httpServerBaseUri.toString(), new ExecutorCounter(state, 0L), clusterState, healthCheckHistory, new PersistedCassandraClusterJobs(state), configuration, seedManager); final HealthReportService healthReportService = new HealthReportService(clusterState, configuration, healthCheckHistory, clock); final Scheduler scheduler = new CassandraScheduler(configuration, cassandraCluster, clock); final JsonFactory factory = new JsonFactory(); final ObjectMapper objectMapper = new ObjectMapper(factory); objectMapper.registerModule(new GuavaModule()); // create JsonProvider to provide custom ObjectMapper JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider(); provider.setMapper(objectMapper); final ResourceConfig rc = new ResourceConfig().registerInstances( new FileResourceController(cassandraVersion), new ApiController(factory), new ClusterCleanupController(cassandraCluster, factory), new ClusterRepairController(cassandraCluster, factory), new ClusterRollingRestartController(cassandraCluster, factory), new ConfigController(cassandraCluster, factory), new LiveEndpointsController(cassandraCluster, factory), new NodeController(cassandraCluster, factory), new HealthCheckController(healthReportService), new QaReportController(cassandraCluster, factory), new ScaleOutController(cassandraCluster, factory), provider); final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(httpServerBaseUri, rc); final MesosSchedulerDriver driver; final Optional<Credential> credentials = getCredential(); if (credentials.isPresent()) { frameworkBuilder.setPrincipal(credentials.get().getPrincipal()); driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), mesosMasterZkUrl, credentials.get()); } else { frameworkBuilder.setPrincipal("cassandra-framework"); driver = new MesosSchedulerDriver(scheduler, frameworkBuilder.build(), mesosMasterZkUrl); } seedManager.startSyncingSeeds(60); final int status; switch (driver.run()) { case DRIVER_STOPPED: status = 0; break; case DRIVER_ABORTED: status = 1; break; case DRIVER_NOT_STARTED: status = 2; break; default: status = 3; break; } httpServer.shutdownNow(); // Ensure that the driver process terminates. driver.stop(true); return status; }
From source file:net.cpollet.jixture.fixtures.generator.field.DateSequence.java
License:Apache License
/** * Build a sequence that will return values between {@code start} and {@code end} (inclusive) with an increment of * 1 day.//from w w w. j av a 2 s.com * * @see #DateSequence(org.joda.time.DateTime, org.joda.time.DateTime, org.joda.time.ReadablePeriod) * * @param start first value in sequence, inclusive. * @param stop last element in sequence, inclusive. */ public DateSequence(DateTime start, DateTime stop) { this(start, stop, Period.days(1)); }
From source file:net.ftlines.wicket.fullcalendar.callback.AbstractShiftedEventParam.java
License:Apache License
public Period getDelta() { return Period.days(daysDelta).plusMinutes(minutesDelta); }
From source file:net.oneandone.stool.configuration.Until.java
License:Apache License
public boolean isBefore(int days) { return date != null && date.isBefore(DateTime.now().minus(Period.days(days))); }
From source file:net.solarnetwork.central.dras.mock.biz.MockDRASQueryBiz.java
License:Open Source License
@Override public List<? extends NodeDatum> getAggregatedDatum(Class<? extends NodeDatum> datumClass, DatumQueryCommand criteria) {// ww w . jav a 2 s .c o m MutableDateTime mdt = new MutableDateTime(criteria.getStartDate()); Period period; switch (criteria.getAggregate()) { case Hour: period = Period.hours(1); break; case Day: period = Period.days(1); break; case Week: period = Period.weeks(1); break; case Month: period = Period.months(1); break; default: period = Period.minutes(1); } List<NodeDatum> results = new ArrayList<NodeDatum>(); do { NodeDatum datum = null; if (ConsumptionDatum.class.isAssignableFrom(datumClass)) { ReportingConsumptionDatum d = new ReportingConsumptionDatum(); d.setNodeId(criteria.getNodeId()); d.setCreated(mdt.toDateTime()); Duration dur = period.toDurationFrom(mdt); float hours = (float) ((double) dur.getMillis() / (double) (1000 * 60 * 60)); d.setWattHours(Double.valueOf(hours * consumptionWattHours)); datum = d; } else if (PowerDatum.class.isAssignableFrom(datumClass)) { ReportingPowerDatum d = new ReportingPowerDatum(); d.setNodeId(criteria.getNodeId()); d.setCreated(mdt.toDateTime()); Duration dur = period.toDurationFrom(mdt); float hours = (float) ((double) dur.getMillis() / (double) (1000 * 60 * 60)); d.setWattHours(Double.valueOf(hours * generationWattHours)); datum = d; } if (datum != null) { results.add(datum); } mdt.add(period); } while (mdt.isBefore(criteria.getEndDate())); return results; }
From source file:org.apache.calcite.adapter.druid.DruidSqlCastConverter.java
License:Apache License
@Override public String toDruidExpression(RexNode rexNode, RelDataType topRel, DruidQuery druidQuery) { final RexNode operand = ((RexCall) rexNode).getOperands().get(0); final String operandExpression = DruidExpressions.toDruidExpression(operand, topRel, druidQuery); if (operandExpression == null) { return null; }/*from w w w . j a v a2 s. c o m*/ final SqlTypeName fromType = operand.getType().getSqlTypeName(); final SqlTypeName toType = rexNode.getType().getSqlTypeName(); final String timeZoneConf = druidQuery.getConnectionConfig().timeZone(); final TimeZone timeZone = TimeZone.getTimeZone(timeZoneConf == null ? "UTC" : timeZoneConf); final boolean nullEqualToEmpty = druidQuery.getConnectionConfig().nullEqualToEmpty(); if (SqlTypeName.CHAR_TYPES.contains(fromType) && SqlTypeName.DATETIME_TYPES.contains(toType)) { //case chars to dates return castCharToDateTime( toType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE ? timeZone : DateTimeUtils.UTC_ZONE, operandExpression, toType, nullEqualToEmpty ? "" : null); } else if (SqlTypeName.DATETIME_TYPES.contains(fromType) && SqlTypeName.CHAR_TYPES.contains(toType)) { //case dates to chars return castDateTimeToChar( fromType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE ? timeZone : DateTimeUtils.UTC_ZONE, operandExpression, fromType); } else if (SqlTypeName.DATETIME_TYPES.contains(fromType) && toType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE) { if (timeZone.equals(DateTimeUtils.UTC_ZONE)) { // bail out, internal representation is the same, // we do not need to do anything return operandExpression; } // to timestamp with local time zone return castCharToDateTime(timeZone, castDateTimeToChar(DateTimeUtils.UTC_ZONE, operandExpression, fromType), toType, nullEqualToEmpty ? "" : null); } else if (fromType == SqlTypeName.TIMESTAMP_WITH_LOCAL_TIME_ZONE && SqlTypeName.DATETIME_TYPES.contains(toType)) { if (toType != SqlTypeName.DATE && timeZone.equals(DateTimeUtils.UTC_ZONE)) { // bail out, internal representation is the same, // we do not need to do anything return operandExpression; } // timestamp with local time zone to other types return castCharToDateTime(DateTimeUtils.UTC_ZONE, castDateTimeToChar(timeZone, operandExpression, fromType), toType, nullEqualToEmpty ? "" : null); } else { // Handle other casts. final DruidType fromExprType = DruidExpressions.EXPRESSION_TYPES.get(fromType); final DruidType toExprType = DruidExpressions.EXPRESSION_TYPES.get(toType); if (fromExprType == null || toExprType == null) { // Unknown types bail out. return null; } final String typeCastExpression; if (fromExprType != toExprType) { typeCastExpression = DruidQuery.format("CAST(%s, '%s')", operandExpression, toExprType.toString()); } else { // case it is the same type it is ok to skip CAST typeCastExpression = operandExpression; } if (toType == SqlTypeName.DATE) { // Floor to day when casting to DATE. return DruidExpressions.applyTimestampFloor(typeCastExpression, Period.days(1).toString(), "", TimeZone.getTimeZone(druidQuery.getConnectionConfig().timeZone())); } else { return typeCastExpression; } } }