Example usage for org.joda.time.format ISODateTimeFormat dateTime

List of usage examples for org.joda.time.format ISODateTimeFormat dateTime

Introduction

In this page you can find the example usage for org.joda.time.format ISODateTimeFormat dateTime.

Prototype

public static DateTimeFormatter dateTime() 

Source Link

Document

Returns a formatter that combines a full date and time, separated by a 'T' (yyyy-MM-dd'T'HH:mm:ss.SSSZZ).

Usage

From source file:org.apache.druid.query.extraction.TimeFormatExtractionFn.java

License:Apache License

public TimeFormatExtractionFn(@JsonProperty("format") String format, @JsonProperty("timeZone") DateTimeZone tz,
        @JsonProperty("locale") String localeString, @JsonProperty("granularity") Granularity granularity,
        @JsonProperty("asMillis") boolean asMillis) {
    this.format = format;
    this.tz = tz;
    this.locale = localeString == null ? null : Locale.forLanguageTag(localeString);
    this.granularity = granularity == null ? Granularities.NONE : granularity;

    if (asMillis && format == null) {
        Preconditions.checkArgument(tz == null, "timeZone requires a format");
        Preconditions.checkArgument(localeString == null, "locale requires a format");
        this.formatter = null;
    } else {//from w  w w .j av  a  2s . c  o m
        this.formatter = (format == null ? ISODateTimeFormat.dateTime() : DateTimeFormat.forPattern(format))
                .withZone(tz == null ? DateTimeZone.UTC : tz).withLocale(locale);
    }

    this.asMillis = asMillis;
}

From source file:org.apache.druid.sql.http.SqlResource.java

License:Apache License

@POST
@Produces(MediaType.APPLICATION_JSON)/*ww w.ja  va 2s  .c  om*/
@Consumes(MediaType.APPLICATION_JSON)
public Response doPost(final SqlQuery sqlQuery, @Context final HttpServletRequest req) throws IOException {
    final SqlLifecycle lifecycle = sqlLifecycleFactory.factorize();
    final String sqlQueryId = lifecycle.initialize(sqlQuery.getQuery(), sqlQuery.getContext());
    final String remoteAddr = req.getRemoteAddr();
    final String currThreadName = Thread.currentThread().getName();

    try {
        Thread.currentThread().setName(StringUtils.format("sql[%s]", sqlQueryId));

        final PlannerContext plannerContext = lifecycle.planAndAuthorize(req);
        final DateTimeZone timeZone = plannerContext.getTimeZone();

        // Remember which columns are time-typed, so we can emit ISO8601 instead of millis values.
        // Also store list of all column names, for X-Druid-Sql-Columns header.
        final List<RelDataTypeField> fieldList = lifecycle.rowType().getFieldList();
        final boolean[] timeColumns = new boolean[fieldList.size()];
        final boolean[] dateColumns = new boolean[fieldList.size()];
        final String[] columnNames = new String[fieldList.size()];

        for (int i = 0; i < fieldList.size(); i++) {
            final SqlTypeName sqlTypeName = fieldList.get(i).getType().getSqlTypeName();
            timeColumns[i] = sqlTypeName == SqlTypeName.TIMESTAMP;
            dateColumns[i] = sqlTypeName == SqlTypeName.DATE;
            columnNames[i] = fieldList.get(i).getName();
        }

        final Yielder<Object[]> yielder0 = Yielders.each(lifecycle.execute());

        try {
            return Response.ok((StreamingOutput) outputStream -> {
                Exception e = null;
                CountingOutputStream os = new CountingOutputStream(outputStream);
                Yielder<Object[]> yielder = yielder0;

                try (final ResultFormat.Writer writer = sqlQuery.getResultFormat().createFormatter(os,
                        jsonMapper)) {
                    writer.writeResponseStart();

                    if (sqlQuery.includeHeader()) {
                        writer.writeHeader(Arrays.asList(columnNames));
                    }

                    while (!yielder.isDone()) {
                        final Object[] row = yielder.get();
                        writer.writeRowStart();
                        for (int i = 0; i < fieldList.size(); i++) {
                            final Object value;

                            if (timeColumns[i]) {
                                value = ISODateTimeFormat.dateTime()
                                        .print(Calcites.calciteTimestampToJoda((long) row[i], timeZone));
                            } else if (dateColumns[i]) {
                                value = ISODateTimeFormat.dateTime()
                                        .print(Calcites.calciteDateToJoda((int) row[i], timeZone));
                            } else {
                                value = row[i];
                            }

                            writer.writeRowField(fieldList.get(i).getName(), value);
                        }
                        writer.writeRowEnd();
                        yielder = yielder.next(null);
                    }

                    writer.writeResponseEnd();
                } catch (Exception ex) {
                    e = ex;
                    log.error(ex, "Unable to send sql response [%s]", sqlQueryId);
                    throw new RuntimeException(ex);
                } finally {
                    yielder.close();
                    lifecycle.emitLogsAndMetrics(e, remoteAddr, os.getCount());
                }
            }).header("X-Druid-SQL-Query-Id", sqlQueryId).build();
        } catch (Throwable e) {
            // make sure to close yielder if anything happened before starting to serialize the response.
            yielder0.close();
            throw new RuntimeException(e);
        }
    } catch (ForbiddenException e) {
        throw e; // let ForbiddenExceptionMapper handle this
    } catch (Exception e) {
        log.warn(e, "Failed to handle query: %s", sqlQuery);
        lifecycle.emitLogsAndMetrics(e, remoteAddr, -1);

        final Exception exceptionToReport;

        if (e instanceof RelOptPlanner.CannotPlanException) {
            exceptionToReport = new ISE("Cannot build plan for query: %s", sqlQuery.getQuery());
        } else {
            exceptionToReport = e;
        }

        return Response.serverError().type(MediaType.APPLICATION_JSON_TYPE)
                .entity(jsonMapper.writeValueAsBytes(QueryInterruptedException.wrapIfNeeded(exceptionToReport)))
                .build();
    } finally {
        Thread.currentThread().setName(currThreadName);
    }
}

From source file:org.apache.marmotta.kiwi.loader.csv.SQLDateTimeProcessor.java

License:Apache License

/**
 * This method is invoked by the framework when the processor needs to process data or check constraints.
 *
 * @since 1.0/*from  w w w  .  java 2 s .com*/
 */
@Override
public Object execute(Object value, CsvContext context) {
    if (value == null) {
        return null;
    }

    if (!(value instanceof DateTime)) {
        throw new SuperCsvCellProcessorException(DateTime.class, value, context, this);
    }

    return ISODateTimeFormat.dateTime().withZoneUTC().print((DateTime) value);
}

From source file:org.apache.nifi.att.m2x.M2XStreamValue.java

License:Apache License

public void setTimestamp(String timestamp) {
    setTimestamp(ISODateTimeFormat.dateTime().parseDateTime(timestamp));
}

From source file:org.apache.nifi.processors.att.m2x.GetM2XStream.java

License:Apache License

private String getLastStartTime(final ProcessContext context, StateManager stateManager) {
    String startTime = null;// w  w  w . j a  v a  2 s. c o  m

    try {
        final StateMap stateMap = stateManager.getState(Scope.CLUSTER);

        startTime = stateMap.get("startTime");
        if (StringUtils.isEmpty(startTime)) {
            final long startTimeAgo = context.getProperty(START_TIME_AGO).asTimePeriod(TimeUnit.MILLISECONDS)
                    .longValue();
            if (startTimeAgo > 0) {
                final long startTimeMillis = System.currentTimeMillis() - startTimeAgo;
                startTime = ISODateTimeFormat.dateTime().print(startTimeMillis);
            }
        }
    } catch (final IOException e) {
        getLogger().warn("Failed to retrieve the last start time from the state manager", e);
    }

    return startTime;
}

From source file:org.apache.nifi.processors.att.m2x.PutM2XStream.java

License:Apache License

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;// www .ja v  a2  s .  co m
    }

    final ProcessorLog logger = getLogger();
    final OkHttpClient httpClient = getHttpClient();
    final StateManager stateManager = context.getStateManager();
    final String apiKey = context.getProperty(M2X_API_KEY).getValue();
    final String apiUrl = context.getProperty(M2X_API_URL).getValue();
    final String deviceId = context.getProperty(M2X_DEVICE_ID).getValue();
    final String streamName = context.getProperty(M2X_STREAM_NAME).getValue();
    final String streamType = context.getProperty(M2X_STREAM_TYPE).getValue();
    final String streamUrl = new StringBuilder().append(apiUrl.replaceAll("/*$", "")).append("/devices/")
            .append(deviceId).append("/streams/").append(streamName).append("/value").toString();

    try {
        final AtomicReference<String> postBodyRef = new AtomicReference<>();
        session.read(flowFile, new InputStreamCallback() {
            @Override
            public void process(InputStream is) {
                try {
                    String timestamp = flowFile.getAttribute("m2x.stream.value.timestamp");
                    if (StringUtils.isEmpty(timestamp)) {
                        timestamp = ISODateTimeFormat.dateTime().print(flowFile.getEntryDate());
                    }
                    final String value = IOUtils.toString(is, StandardCharsets.UTF_8);

                    final M2XStreamValue m2xValue = new M2XStreamValue();
                    m2xValue.setValue(value);
                    m2xValue.setTimestamp(timestamp);

                    final ObjectMapper mapper = new ObjectMapper();
                    mapper.registerModule(new JodaModule());
                    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

                    final String postBody = mapper.writeValueAsString(m2xValue);
                    logger.warn("POST body is {}", new Object[] { postBody });
                    postBodyRef.set(postBody);
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });

        final String postBody = postBodyRef.get();
        if (StringUtils.isEmpty(postBody)) {
            logger.error("FlowFile {} contents didn't produce a valid M2X stream value",
                    new Object[] { flowFile });
            session.transfer(flowFile, REL_FAILURE);
            return;
        }

        final Request request = new Request.Builder().url(streamUrl).addHeader("X-M2X-KEY", apiKey)
                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody)).build();
        final Response response = httpClient.newCall(request).execute();

        if (!response.isSuccessful()) {
            logger.error(response.message());
            context.yield();
            session.penalize(flowFile);
            return;
        }
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        context.yield();
        session.penalize(flowFile);
        return;
    }

    session.transfer(flowFile, REL_SUCCESS);
}

From source file:org.apache.rya.api.domain.RyaTypeUtils.java

License:Apache License

/**
 * Creates a date {@link RyaType} object.
 * @param value the {@link Date} object.
 * @return the {@link RyaType} with the data type set to
 * {@link XMLSchema#DATETIME} and the data set to the specified
 * {@code value}./*from ww w  .  ja  v a2 s. c  o m*/
 */
public static RyaType dateRyaType(final Date value) {
    final DateTime dateTime = new DateTime(value.getTime());
    final StringBuffer sb = new StringBuffer();
    ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC).printTo(sb, dateTime.getMillis());
    final String formattedDate = sb.toString();
    return new RyaType(XMLSchema.DATE, formattedDate);
}

From source file:org.apache.rya.api.domain.RyaTypeUtils.java

License:Apache License

/**
 * Creates a date/time {@link RyaType} object.
 * @param value the {@link DateTime} object.
 * @return the {@link RyaType} with the data type set to
 * {@link XMLSchema#DATETIME} and the data set to the specified
 * {@code value}.//from   w  w w  . j  ava2s .c o m
 */
public static RyaType dateRyaType(final DateTime value) {
    final StringBuffer sb = new StringBuffer();
    ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC).printTo(sb, value.getMillis());
    final String formattedDate = sb.toString();
    return new RyaType(XMLSchema.DATETIME, formattedDate);
}

From source file:org.apache.streams.juneau.JodaDateSwap.java

License:Apache License

/**
 * Constructor.
 */
public JodaDateSwap() {
    dateFormatter = ISODateTimeFormat.dateTime();
}

From source file:org.apache.streams.rss.serializer.SyndEntrySerializer.java

License:Apache License

private void serializeDate(ObjectNode root, Date date, String key) {
    DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
    if (date == null)
        return;// w  ww  .ja  v a  2  s  . c  om
    root.put(key, formatter.print(date.getTime()));
}