Example usage for java.time OffsetDateTime now

List of usage examples for java.time OffsetDateTime now

Introduction

In this page you can find the example usage for java.time OffsetDateTime now.

Prototype

public static OffsetDateTime now(Clock clock) 

Source Link

Document

Obtains the current date-time from the specified clock.

Usage

From source file:com.amazonaws.services.kinesis.io.JsonDataExtractor.java

/**
 * {@inheritDoc}//from  w  ww .  j  av  a2  s.  c om
 */
@Override
public List<AggregateData> getData(InputEvent event) throws SerializationException {
    try {
        List<AggregateData> aggregateData = new ArrayList<>();
        OffsetDateTime dateValue = null;
        JsonNode jsonContent = null;
        String dateString, summary = null;
        long localOffset = 0;

        List<String> items = (List<String>) serialiser.toClass(event);

        // log a warning if we didn't get anything back from the serialiser
        // - this could be OK, but probably isn't
        // it would be OK, for example, if you have filterRegex
        //            if (items == null || items.size() == 0)
        //                LOG.warn(String.format(
        //                        "Failed to deserialise any content for Record (Partition Key %s, Sequence %s",
        //                        event.getPartitionKey(), event.getSequenceNumber()));

        // process all the items returned by the serialiser
        for (String item : items) {
            // Convert the string to a Jackson JsonNode for navigation
            jsonContent = StreamAggregatorUtils.asJsonNode(item);
            sumUpdates = new HashMap<>();

            LabelSet labels = new LabelSet();
            for (String key : this.labelAttributes) {
                labels.put(key, StreamAggregatorUtils.readValueAsString(jsonContent, key));
            }

            // get the unique ID for the event
            String uniqueId = null;
            if (this.uniqueIdAttribute != null) {
                switch (this.uniqueIdAttribute) {
                case StreamAggregator.REF_PARTITION_KEY:
                    uniqueId = event.getPartitionKey();
                    break;
                case StreamAggregator.REF_SEQUENCE:
                    uniqueId = event.getSequenceNumber();
                    break;
                default:
                    uniqueId = StreamAggregatorUtils.readValueAsString(jsonContent, uniqueIdAttribute);
                    break;
                }
            }

            // get the date value from the line
            if (dateValueAttribute != null) {
                dateString = StreamAggregatorUtils.readValueAsString(jsonContent, dateValueAttribute);

                // bail on no date returned
                if (dateString == null || dateString.equals(""))
                    throw new SerializationException(
                            String.format("Unable to read date value attribute %s from JSON Content %s",
                                    dateValueAttribute, item));

                // turn date as long or string into Date
                if (this.dateFormat != null) {
                    dateValue = OffsetDateTime.parse(dateString, dateFormatter);
                } else {
                    // no formatter, so treat as epoch seconds
                    try {
                        dateValue = OffsetDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(dateString)),
                                ZoneId.of("UTC"));
                    } catch (Exception e) {
                        LOG.error(String.format(
                                "Unable to create Date Value element from item '%s' due to invalid format as Epoch Seconds",
                                dateValueAttribute));
                        throw new SerializationException(e);
                    }
                }
            } else {
                // no date value attribute configured, so use now
                dateValue = OffsetDateTime.now(ZoneId.of("UTC"));
            }

            // get the summed values
            if (this.aggregatorType.equals(AggregatorType.SUM)) {
                // get the positional sum items
                for (String s : summaryConfig.getItemSet()) {
                    try {
                        summary = StreamAggregatorUtils.readValueAsString(jsonContent, s);

                        // if a summary is not found in the data element,
                        // then we simply continue without it
                        if (summary != null)
                            sumUpdates.put(s, Double.parseDouble(summary));
                    } catch (NumberFormatException nfe) {
                        LOG.error(String
                                .format("Unable to deserialise Summary '%s' due to NumberFormatException", s));
                        throw new SerializationException(nfe);
                    }
                }
            }

            // get local offset
            if (offsetAttribute != null) {
                try {
                    String offsetString = StreamAggregatorUtils.readValueAsString(jsonContent, offsetAttribute);
                    if (offsetString != null)
                        localOffset = Long.parseLong(offsetString);
                } catch (NumberFormatException nfe) {
                    LOG.error(String.format(
                            "Unable to deserialise local offset '%s' due to NumberFormatException",
                            dateValueAttribute));
                    throw new SerializationException(nfe);
                }
            }

            aggregateData.add(new AggregateData(uniqueId, labels, dateValue, sumUpdates, localOffset));
        }

        return aggregateData;
    } catch (Exception e) {
        throw new SerializationException(e);
    }
}

From source file:com.amazonaws.services.kinesis.io.ObjectExtractor.java

/**
 * {@inheritDoc}//from   ww  w.  ja v  a 2 s  .c om
 */
@Override
public List<AggregateData> getData(InputEvent event) throws SerializationException {
    if (!validated) {
        try {
            validate();
        } catch (Exception e) {
            throw new SerializationException(e);
        }
    }

    try {
        List<AggregateData> data = new ArrayList<>();

        Object o = serialiser.toClass(event);

        // get the value of the reflected labels
        LabelSet labels = new LabelSet();
        for (String key : this.aggregateLabelMethods) {
            labels.put(key, aggregateLabelMethodMap.get(key).invoke(o).toString());
        }

        // get the unique ID value from the object
        String uniqueId = null;
        if (this.uniqueIdMethodName != null) {
            switch (this.uniqueIdMethodName) {
            case StreamAggregator.REF_PARTITION_KEY:
                uniqueId = event.getPartitionKey();
                break;
            case StreamAggregator.REF_SEQUENCE:
                uniqueId = event.getSequenceNumber();
                break;
            default:
                Object id = uniqueIdMethod.invoke(o);
                if (id != null) {
                    uniqueId = id.toString();
                }
                break;
            }
        }

        // get the date value from the object
        if (this.dateMethod != null) {
            eventDate = dateMethod.invoke(o);

            if (eventDate == null) {
                dateValue = OffsetDateTime.now(ZoneId.of("UTC"));
            } else {
                if (eventDate instanceof Date) {
                    dateValue = OffsetDateTime.ofInstant(((Date) eventDate).toInstant(), ZoneId.of("UTC"));
                } else if (eventDate instanceof Long) {
                    dateValue = OffsetDateTime.ofInstant(Instant.ofEpochMilli((Long) eventDate),
                            ZoneId.of("UTC"));
                } else {
                    throw new Exception(String.format("Cannot use data type %s for date value on event",
                            eventDate.getClass().getSimpleName()));
                }
            }
        }

        // extract all summed values from the serialised object
        if (this.aggregatorType.equals(AggregatorType.SUM)) {
            // lift out the aggregated method value
            for (String s : this.sumValueMap.keySet()) {
                summaryValue = this.sumValueMap.get(s).invoke(o);

                if (summaryValue != null) {
                    if (summaryValue instanceof Double) {
                        sumUpdates.put(s, (Double) summaryValue);
                    } else if (summaryValue instanceof Long) {
                        sumUpdates.put(s, ((Long) summaryValue).doubleValue());
                    } else if (summaryValue instanceof Integer) {
                        sumUpdates.put(s, ((Integer) summaryValue).doubleValue());
                    } else {
                        String msg = String.format("Unable to access  Summary %s due to NumberFormatException",
                                s);
                        LOG.error(msg);
                        throw new SerializationException(msg);
                    }
                }
            }
        }

        data.add(new AggregateData(uniqueId, labels, dateValue, sumUpdates));

        return data;
    } catch (Exception e) {
        throw new SerializationException(e);
    }
}

From source file:ddf.catalog.registry.federationadmin.service.impl.FederationAdminServiceImpl.java

private void createIdentityNode() throws SourceUnavailableException, IngestException {

    String registryPackageId = UUID.randomUUID().toString().replaceAll("-", "");
    RegistryPackageType registryPackage = RIM_FACTORY.createRegistryPackageType();
    registryPackage.setId(registryPackageId);
    registryPackage.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    ExtrinsicObjectType extrinsicObject = RIM_FACTORY.createExtrinsicObjectType();
    extrinsicObject.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    String extrinsicObjectId = UUID.randomUUID().toString().replaceAll("-", "");
    extrinsicObject.setId(extrinsicObjectId);

    String siteName = SystemInfo.getSiteName();
    if (StringUtils.isNotBlank(siteName)) {
        extrinsicObject.setName(getInternationalStringTypeFromString(siteName));
    }/*from w w w.ja  v  a 2s . com*/

    String home = SystemBaseUrl.getBaseUrl();
    if (StringUtils.isNotBlank(home)) {
        extrinsicObject.setHome(home);
    }

    String version = SystemInfo.getVersion();
    if (StringUtils.isNotBlank(version)) {
        VersionInfoType versionInfo = RIM_FACTORY.createVersionInfoType();
        versionInfo.setVersionName(version);

        extrinsicObject.setVersionInfo(versionInfo);
    }

    OffsetDateTime now = OffsetDateTime.now(ZoneId.of(ZoneOffset.UTC.toString()));
    String rightNow = now.toString();
    ValueListType valueList = RIM_FACTORY.createValueListType();
    valueList.getValue().add(rightNow);

    SlotType1 lastUpdated = RIM_FACTORY.createSlotType1();
    lastUpdated.setValueList(RIM_FACTORY.createValueList(valueList));
    lastUpdated.setSlotType(DatatypeConstants.DATETIME.toString());
    lastUpdated.setName(RegistryConstants.XML_LAST_UPDATED_NAME);
    extrinsicObject.getSlot().add(lastUpdated);

    SlotType1 liveDate = RIM_FACTORY.createSlotType1();
    liveDate.setValueList(RIM_FACTORY.createValueList(valueList));
    liveDate.setSlotType(DatatypeConstants.DATETIME.toString());
    liveDate.setName(RegistryConstants.XML_LIVE_DATE_NAME);
    extrinsicObject.getSlot().add(liveDate);

    if (registryPackage.getRegistryObjectList() == null) {
        registryPackage.setRegistryObjectList(RIM_FACTORY.createRegistryObjectListType());
    }

    registryPackage.getRegistryObjectList().getIdentifiable()
            .add(RIM_FACTORY.createIdentifiable(extrinsicObject));

    Metacard identityMetacard = jaxbToMetacard(registryPackage);
    if (identityMetacard != null) {
        Attribute registryNodeAttribute = new AttributeImpl(RegistryObjectMetacardType.REGISTRY_IDENTITY_NODE,
                true);
        identityMetacard.setAttribute(registryNodeAttribute);

        addLocalEntry(identityMetacard);
    }
}

From source file:org.codice.ddf.registry.federationadmin.service.impl.IdentityNodeInitialization.java

private void createIdentityNode() throws FederationAdminException {
    String registryPackageId = System.getProperty(RegistryConstants.REGISTRY_ID_PROPERTY);
    if (StringUtils.isEmpty(registryPackageId)) {
        registryPackageId = RegistryConstants.GUID_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");
        setSystemRegistryId(registryPackageId);
    }/* w ww.  java 2  s.  c  o  m*/
    LOGGER.info("Creating registry identity node: {} {}", SystemInfo.getSiteName(), registryPackageId);
    RegistryPackageType registryPackage = RIM_FACTORY.createRegistryPackageType();
    registryPackage.setId(registryPackageId);
    registryPackage.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    ExtrinsicObjectType extrinsicObject = RIM_FACTORY.createExtrinsicObjectType();
    extrinsicObject.setObjectType(RegistryConstants.REGISTRY_NODE_OBJECT_TYPE);

    String extrinsicObjectId = RegistryConstants.GUID_PREFIX + UUID.randomUUID().toString().replaceAll("-", "");
    extrinsicObject.setId(extrinsicObjectId);

    String siteName = SystemInfo.getSiteName();
    if (StringUtils.isNotBlank(siteName)) {
        extrinsicObject.setName(internationalStringTypeHelper.create(siteName));
    } else {
        extrinsicObject.setName(internationalStringTypeHelper.create(UNKNOWN_SITE_NAME));
    }

    String home = SystemBaseUrl.EXTERNAL.getBaseUrl();
    extrinsicObject.setHome(home);

    String version = SystemInfo.getVersion();
    if (StringUtils.isNotBlank(version)) {
        VersionInfoType versionInfo = RIM_FACTORY.createVersionInfoType();
        versionInfo.setVersionName(version);

        extrinsicObject.setVersionInfo(versionInfo);
    }

    OffsetDateTime now = OffsetDateTime.now(ZoneId.of(ZoneOffset.UTC.toString()));
    String rightNow = now.toString();

    SlotType1 lastUpdated = slotTypeHelper.create(RegistryConstants.XML_LAST_UPDATED_NAME, rightNow, DATE_TIME);
    extrinsicObject.getSlot().add(lastUpdated);

    SlotType1 liveDate = slotTypeHelper.create(RegistryConstants.XML_LIVE_DATE_NAME, rightNow, DATE_TIME);
    extrinsicObject.getSlot().add(liveDate);

    if (registryPackage.getRegistryObjectList() == null) {
        registryPackage.setRegistryObjectList(RIM_FACTORY.createRegistryObjectListType());
    }

    registryPackage.getRegistryObjectList().getIdentifiable()
            .add(RIM_FACTORY.createIdentifiable(extrinsicObject));

    Metacard identityMetacard = getRegistryMetacardFromRegistryPackage(registryPackage);
    if (identityMetacard != null) {
        identityMetacard
                .setAttribute(new AttributeImpl(RegistryObjectMetacardType.REGISTRY_IDENTITY_NODE, true));
        identityMetacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.REGISTRY_LOCAL_NODE, true));
        federationAdminService.addRegistryEntry(identityMetacard);
    }
}

From source file:ox.softeng.gel.filereceive.FileReceive.java

public void generateStartupMessage() throws IOException {

    try {/* w  w w.ja  v  a2  s . co m*/
        StringWriter writer;
        MessageDTO message = new MessageDTO();
        message.setSource("file-receiver");
        message.setDetails("Burst Service starting\n" + version());
        message.setSeverity(SeverityEnum.INFORMATIONAL);
        message.setDateTimeCreated(OffsetDateTime.now(ZoneId.of("UTC")));
        message.setTitle("File Receiver Startup");
        message.addTopic("service");
        message.addTopic("startup");
        message.addTopic("file-receiver");
        message.addMetadata("gmc", "gel");
        message.addMetadata("file_receiver_service_version", version());

        writer = new StringWriter();
        getMarshaller().marshal(message, writer);

        AMQP.BasicProperties.Builder builder = new AMQP.BasicProperties().builder();
        builder.deliveryMode(2);
        builder.contentType("text/xml");
        builder.timestamp(Date.from(OffsetDateTime.now(ZoneId.systemDefault()).toInstant()));

        Channel channel = factory.newConnection().createChannel();
        channel.exchangeDeclare(exchangeName, "topic", true);
        channel.basicPublish(exchangeName, burstQueue, builder.build(), writer.toString().getBytes());
        channel.close();

    } catch (JAXBException | TimeoutException ignored) {
    }
}

From source file:com.muk.services.security.DefaultUaaLoginService.java

private String httpCookieToString(HttpCookie cookie) {
    final OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(cookie.getMaxAge());
    final String cookieExpires = DateTimeFormatter.RFC_1123_DATE_TIME.format(now);
    final StringBuilder cookieBuilder = new StringBuilder();
    cookieBuilder.append(cookie.getName()).append("=").append(cookie.getValue()).append(";path=")
            .append(cookie.getPath()).append(";max-age=").append(cookie.getMaxAge()).append(";expires=")
            .append(cookieExpires);//ww w . jav a2 s  .co  m

    if (cookie.isHttpOnly()) {
        cookieBuilder.append(";HttpOnly");
    }

    return cookieBuilder.toString();
}

From source file:ox.softeng.burst.service.BurstService.java

private void generateStartupMessage() {
    Message message = new Message("burst-service", "Burst Service starting\n" + version(),
            SeverityEnum.INFORMATIONAL, OffsetDateTime.now(ZoneId.of("UTC")), "Burst Service Startup");
    message.addTopic("service");
    message.addTopic("startup");
    message.addTopic("burst");
    message.addMetadata("gmc", "gel");
    message.addMetadata("burst_service_version", version());

    try {//w  w  w.j a  va2 s .  c om
        message.save(entityManagerFactory);
    } catch (HibernateException he) {
        logger.error("Could not save startup message to database: " + he.getMessage(), he);
    } catch (Exception e) {
        logger.error("Unhandled exception trying to process startup message", e);
    }
}

From source file:com.epam.dlab.backendapi.service.impl.SchedulerJobServiceImpl.java

/**
 * Enriches existing scheduler job with the following data:
 * - sets current date as 'beginDate' if this parameter wasn't defined;
 * - sets current system time zone offset as 'timeZoneOffset' if this parameter wasn't defined.
 *
 * @param dto current scheduler job//from w w  w.j av a 2s . c  o m
 */
private void enrichSchedulerJobIfNecessary(SchedulerJobDTO dto) {
    if (Objects.isNull(dto.getBeginDate()) || StringUtils.isBlank(dto.getBeginDate().toString())) {
        dto.setBeginDate(LocalDate.now());
    }
    if (Objects.isNull(dto.getTimeZoneOffset()) || StringUtils.isBlank(dto.getTimeZoneOffset().toString())) {
        dto.setTimeZoneOffset(OffsetDateTime.now(ZoneId.systemDefault()).getOffset());
    }
}

From source file:com.amazonaws.services.kinesis.aggregators.StreamAggregator.java

/**
 * {@inheritDoc}//  ww w .  j ava  2  s .  c om
 */
public void aggregateEvents(List<InputEvent> events) throws Exception {
    start = System.currentTimeMillis();
    int aggregatedEventCount = 0;
    int aggregatedElementCount = 0;

    if (!online) {
        throw new Exception("Aggregator Not Initialised");
    }

    BigInteger thisSequence;
    List<AggregateData> extractedItems = null;
    OffsetDateTime eventDate = null;

    try {
        for (InputEvent event : events) {
            // reset extracted items
            extractedItems = null;

            if (event.getSequenceNumber() != null) {
                thisSequence = new BigInteger(event.getSequenceNumber());
                // ignore any records which are going backward with regard
                // to
                // the current hwm
                if (highSeq != null && highSeq.compareTo(thisSequence) != -1) {
                    ignoredRecordsBelowHWM++;
                    continue;
                }
            }

            // set the low sequence if this is the first record received
            // after a flush
            if (lowSeq == null)
                lowSeq = event.getSequenceNumber();

            // high sequence is always the latest value
            highSeq = new BigInteger(event.getSequenceNumber());

            // extract the data from the input event
            try {
                extractedItems = dataExtractor.getData(event);
            } catch (SerializationException se) {
                // customer may have elected to suppress serialisation
                // errors if the stream is expected have heterogenous data
                // on it
                if (this.raiseExceptionOnDataExtractionErrors) {
                    throw se;
                } else {
                    logWarn(String.format("Serialisation Exception Sequence %s Partition Key %s",
                            event.getSequenceNumber(), event.getPartitionKey()), se);
                }
            }

            // data extractor may have returned multiple data elements, or
            // be empty if there were serialisation problems which are
            // suppressed
            if (extractedItems != null) {
                aggregatedEventCount++;

                for (AggregateData data : extractedItems) {
                    // run the idempotency check
                    if (!this.idempotencyCheck.doProcess(event.getPartitionKey(), event.getSequenceNumber(),
                            data, event.getData())) {
                        logInfo(String.format("Ignoring Event %s as it failed Idempotency Check",
                                event.getPartitionKey()));
                        continue;
                    }

                    aggregatedElementCount++;

                    // if the data extractor didn't have a date value to
                    // extract, then use the current time
                    eventDate = data.getDate();
                    if (eventDate == null) {
                        eventDate = OffsetDateTime.now(ZoneId.of("UTC"));
                    }

                    // generate the local updates, one per time horizon that
                    // is requested
                    for (TimeHorizon h : timeHorizons) {
                        OffsetDateTime localEventDate = eventDate;
                        if (!h.isUTC())
                            localEventDate = eventDate.minus(Duration.ofMillis(data.getLocalOffset()));

                        // atomically update the aggregate table with event
                        // count or count + summaries
                        cache.update(aggregatorType, data.getLabels(),
                                (timeHorizons.size() > 1 ? h.getItemWithMultiValueFormat(localEventDate)
                                        : h.getValue(localEventDate)),
                                h, event.getSequenceNumber(), 1, data.getSummaries(),
                                dataExtractor.getSummaryConfig());
                    }
                }
            }
        }

        logInfo(String.format("Aggregation Complete - %s Records and %s Elements in %s ms",
                aggregatedEventCount, aggregatedElementCount, (System.currentTimeMillis() - start)));
    } catch (SerializationException se) {
        shutdown(true, InventoryModel.STATE.SERIALISATION_ERROR);
        LOG.error(se);
        throw se;
    } catch (Exception e) {
        shutdown(true, InventoryModel.STATE.UNKNOWN_ERROR);
        LOG.error(e);
        throw e;
    }
}

From source file:org.codice.ddf.registry.federationadmin.impl.FederationAdmin.java

private void updateDateFields(RegistryPackageType rpt) {

    ExtrinsicObjectType nodeInfo = null;
    for (JAXBElement identifiable : rpt.getRegistryObjectList().getIdentifiable()) {
        RegistryObjectType registryObject = (RegistryObjectType) identifiable.getValue();

        if (registryObject instanceof ExtrinsicObjectType
                && RegistryConstants.REGISTRY_NODE_OBJECT_TYPE.equals(registryObject.getObjectType())) {
            nodeInfo = (ExtrinsicObjectType) registryObject;
            break;
        }/*from  www  . jav  a2 s. co m*/
    }
    if (nodeInfo != null) {
        boolean liveDateFound = false;
        boolean lastUpdatedFound = false;

        OffsetDateTime now = OffsetDateTime.now(ZoneId.of(ZoneOffset.UTC.toString()));
        String rightNow = now.toString();

        for (SlotType1 slot : nodeInfo.getSlot()) {
            if (slot.getName().equals(RegistryConstants.XML_LIVE_DATE_NAME)) {
                liveDateFound = true;
            } else if (slot.getName().equals(RegistryConstants.XML_LAST_UPDATED_NAME)) {
                ValueListType valueList = EbrimConstants.RIM_FACTORY.createValueListType();
                valueList.getValue().add(rightNow);
                slot.setValueList(EbrimConstants.RIM_FACTORY.createValueList(valueList));
                lastUpdatedFound = true;
            }
        }

        if (!liveDateFound) {
            SlotType1 liveDate = slotHelper.create(RegistryConstants.XML_LIVE_DATE_NAME, rightNow, DATE_TIME);

            nodeInfo.getSlot().add(liveDate);
        }

        if (!lastUpdatedFound) {
            SlotType1 lastUpdated = slotHelper.create(RegistryConstants.XML_LAST_UPDATED_NAME, rightNow,
                    DATE_TIME);

            nodeInfo.getSlot().add(lastUpdated);
        }
    }
}