Example usage for java.time Instant ofEpochMilli

List of usage examples for java.time Instant ofEpochMilli

Introduction

In this page you can find the example usage for java.time Instant ofEpochMilli.

Prototype

public static Instant ofEpochMilli(long epochMilli) 

Source Link

Document

Obtains an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z.

Usage

From source file:ru.anr.base.BaseParent.java

/**
 * Transforms an old date object to a zoned date using the default (UTC)
 * time zone/*from  w  ww  .j  a  va 2 s .co  m*/
 * 
 * @param oldDate
 *            Some old date
 * @return A zoned object
 */
public static ZonedDateTime date(Date oldDate) {

    return ZonedDateTime.ofInstant(Instant.ofEpochMilli(oldDate.getTime()), DEFAULT_TIMEZONE);
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

@Override
@SuppressWarnings("unchecked")
public MailQueueIterator browse() throws MailQueueException {
    QueueBrowser browser = null;/*from   w  w w  .  j  a va  2  s.com*/
    try {
        browser = session.createBrowser(queue);

        Enumeration<Message> messages = browser.getEnumeration();
        QueueBrowser myBrowser = browser;

        return new MailQueueIterator() {

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Read-only");
            }

            @Override
            public MailQueueItemView next() {
                while (hasNext()) {
                    try {
                        Message m = messages.nextElement();
                        return new MailQueueItemView(createMail(m), nextDeliveryDate(m));
                    } catch (MessagingException | JMSException e) {
                        LOGGER.error("Unable to browse queue", e);
                    }
                }

                throw new NoSuchElementException();
            }

            private ZonedDateTime nextDeliveryDate(Message m) throws JMSException {
                long nextDeliveryTimestamp = m.getLongProperty(JAMES_NEXT_DELIVERY);
                return Instant.ofEpochMilli(nextDeliveryTimestamp).atZone(ZoneId.systemDefault());
            }

            @Override
            public boolean hasNext() {
                return messages.hasMoreElements();
            }

            @Override
            public void close() {
                closeBrowser(myBrowser);
            }
        };

    } catch (Exception e) {
        closeBrowser(browser);

        LOGGER.error("Unable to browse queue {}", queueName, e);
        throw new MailQueueException("Unable to browse queue " + queueName, e);
    }
}

From source file:net.dv8tion.jda.core.entities.EntityBuilder.java

public void createPresence(Object memberOrFriend, JSONObject presenceJson) {
    if (memberOrFriend == null)
        throw new NullPointerException("Provided memberOrFriend was null!");

    JSONObject gameJson = presenceJson.isNull("game") ? null : presenceJson.getJSONObject("game");
    OnlineStatus onlineStatus = OnlineStatus.fromKey(presenceJson.getString("status"));
    Game game = null;// w ww  .  j  a  v a  2  s .c  o m

    if (gameJson != null && !gameJson.isNull("name")) {
        String gameName = gameJson.get("name").toString();
        String url = gameJson.isNull("url") ? null : gameJson.get("url").toString();

        Game.GameType gameType;
        try {
            gameType = gameJson.isNull("type") ? Game.GameType.DEFAULT
                    : Game.GameType.fromKey(Integer.parseInt(gameJson.get("type").toString()));
        } catch (NumberFormatException e) {
            gameType = Game.GameType.DEFAULT;
        }

        game = new GameImpl(gameName, url, gameType);
    }
    if (memberOrFriend instanceof Member) {
        MemberImpl member = (MemberImpl) memberOrFriend;
        member.setOnlineStatus(onlineStatus);
        member.setGame(game);
    } else if (memberOrFriend instanceof Friend) {
        FriendImpl friend = (FriendImpl) memberOrFriend;
        friend.setOnlineStatus(onlineStatus);
        friend.setGame(game);

        OffsetDateTime lastModified = OffsetDateTime.ofInstant(
                Instant.ofEpochMilli(presenceJson.getLong("last_modified")),
                TimeZone.getTimeZone("GMT").toZoneId());

        friend.setOnlineStatusModifiedTime(lastModified);
    } else
        throw new IllegalArgumentException(
                "An object was provided to EntityBuilder#createPresence that wasn't a Member or Friend. JSON: "
                        + presenceJson);
}

From source file:org.optaplanner.examples.conferencescheduling.persistence.ConferenceSchedulingCfpDevoxxImporter.java

private void importTimeslotList() {
    List<Timeslot> timeslotList = new ArrayList<>();
    Map<Timeslot, List<Room>> timeslotToAvailableRoomsMap = new HashMap<>();
    Map<Pair<LocalDateTime, LocalDateTime>, Timeslot> startAndEndTimeToTimeslotMap = new HashMap<>();

    Long timeSlotId = 0L;//from  w  w w .  j a  v a 2s  .c o m
    String schedulesUrl = conferenceBaseUrl + "/schedules/";
    LOGGER.debug("Sending a request to: " + schedulesUrl);
    JsonArray daysArray = readJson(schedulesUrl, JsonReader::readObject).getJsonArray("links");
    for (int i = 0; i < daysArray.size(); i++) {
        JsonObject dayObject = daysArray.getJsonObject(i);
        String dayUrl = dayObject.getString("href");

        LOGGER.debug("Sending a request to: " + dayUrl);
        JsonArray daySlotsArray = readJson(dayUrl, JsonReader::readObject).getJsonArray("slots");

        for (int j = 0; j < daySlotsArray.size(); j++) {
            JsonObject timeslotObject = daySlotsArray.getJsonObject(j);

            LocalDateTime startDateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeslotObject.getJsonNumber("fromTimeMillis").longValue()),
                    ZoneId.of(ZONE_ID));
            LocalDateTime endDateTime = LocalDateTime.ofInstant(
                    Instant.ofEpochMilli(timeslotObject.getJsonNumber("toTimeMillis").longValue()),
                    ZoneId.of(ZONE_ID));

            Room room = roomIdToRoomMap.get(timeslotObject.getString("roomId"));
            if (room == null) {
                throw new IllegalStateException("The timeslot (" + timeslotObject.getString("slotId")
                        + ") has a roomId (" + timeslotObject.getString("roomId")
                        + ") that does not exist in the rooms list");
            }

            // Assuming slotId is of format: tia_room6_monday_12_.... take only "tia"
            String talkTypeName = timeslotObject.getString("slotId").split("_")[0];
            TalkType timeslotTalkType = talkTypeNameToTalkTypeMap.get(talkTypeName);
            if (Arrays.asList(IGNORED_TALK_TYPES).contains(talkTypeName)) {
                continue;
            }

            Timeslot timeslot;
            if (startAndEndTimeToTimeslotMap.keySet().contains(Pair.of(startDateTime, endDateTime))) {
                timeslot = startAndEndTimeToTimeslotMap.get(Pair.of(startDateTime, endDateTime));
                timeslotToAvailableRoomsMap.get(timeslot).add(room);
                if (timeslotTalkType != null) {
                    timeslot.getTalkTypeSet().add(timeslotTalkType);
                }
            } else {
                timeslot = new Timeslot(timeSlotId++);
                timeslot.withStartDateTime(startDateTime).withEndDateTime(endDateTime)
                        .withTalkTypeSet(timeslotTalkType == null ? new HashSet<>()
                                : new HashSet<>(Arrays.asList(timeslotTalkType)));
                timeslot.setTagSet(new HashSet<>());

                timeslotList.add(timeslot);
                timeslotToAvailableRoomsMap.put(timeslot, new ArrayList<>(Arrays.asList(room)));
                startAndEndTimeToTimeslotMap.put(Pair.of(startDateTime, endDateTime), timeslot);
            }

            if (!timeslotObject.isNull("talk")) {
                scheduleTalk(timeslotObject, room, timeslot);
            }

            for (TalkType talkType : timeslot.getTalkTypeSet()) {
                talkType.getCompatibleTimeslotSet().add(timeslot);
            }
            timeslotTalkTypeToTotalMap.merge(talkTypeName, 1, Integer::sum);
        }
    }

    for (Room room : solution.getRoomList()) {
        room.setUnavailableTimeslotSet(timeslotList.stream()
                .filter(timeslot -> !timeslotToAvailableRoomsMap.get(timeslot).contains(room))
                .collect(Collectors.toSet()));
    }

    solution.setTimeslotList(timeslotList);
}

From source file:org.codice.ddf.catalog.ui.util.EndpointUtil.java

public Instant parseDate(Serializable value) {

    if (value instanceof Date) {
        return ((Date) value).toInstant();
    }/*w w w . j a v a 2s  .  c om*/

    if (value instanceof Long) {
        return Instant.ofEpochMilli((Long) value);
    }

    if (!(value instanceof String)) {
        return null;
    }

    String string = String.valueOf(value);

    if (StringUtils.isBlank(string)) {
        return null;
    }

    if (StringUtils.isNumeric(string)) {
        try {
            return Instant.ofEpochMilli(Long.parseLong(string));
        } catch (NumberFormatException ex) {
            LOGGER.debug("Failed to create Epoch time from a numeric: {}", string, ex);
            return null;
        }
    }

    if (iso8601Z.matcher(string).matches()) {
        return Instant.parse(string);
    }

    if (iso8601Offset.matcher(string).matches()) {
        return OffsetDateTime.parse(string).toInstant();
    }

    SimpleDateFormat dateFormat;
    if (jsonDefault.matcher(string).matches()) {
        dateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
    } else {
        dateFormat = new SimpleDateFormat();
    }
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        return dateFormat.parse(string).toInstant();
    } catch (ParseException e) {
        LOGGER.debug("Failed to parse as a dateFormat time from a date string: {}", string, e);
        return null;
    }
}

From source file:ru.anr.base.BaseParent.java

/**
 * @param date/*from  w w w . j av  a2s.com*/
 *            Date
 * @param locale
 *            Locale
 * @return formatted date
 */
public static String formatDate(long date, String locale) {

    return DateTimeFormatter
            .ofPattern("ru_RU".equals(locale) ? "dd.MM.yyyy HH:mm:ss z" : "dd/MM/yyyy HH:mm:ss z")
            .withZone(ZoneOffset.systemDefault())
            .format(LocalDateTime.ofInstant(Instant.ofEpochMilli(date), ZoneId.systemDefault()));
}

From source file:ru.anr.base.BaseParent.java

/**
 * @param pattern//ww w  . j  a  v  a 2  s.co m
 *            patter
 * @param date
 *            date
 * @return formatted date
 */
public static String formatDate(String pattern, Calendar date) {

    return DateTimeFormatter.ofPattern(pattern).format(
            LocalDateTime.ofInstant(Instant.ofEpochMilli(date.getTimeInMillis()), ZoneId.systemDefault()));
}

From source file:co.rsk.peg.BridgeSerializationUtilsTest.java

@Test
public void serializeAndDeserializeFederationWithRealRLP() {
    NetworkParameters networkParms = NetworkParameters.fromID(NetworkParameters.ID_REGTEST);
    byte[][] publicKeyBytes = new byte[][] { BtcECKey.fromPrivate(BigInteger.valueOf(100)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(200)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(300)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(400)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(500)).getPubKey(),
            BtcECKey.fromPrivate(BigInteger.valueOf(600)).getPubKey(), };

    Federation federation = new Federation(
            Arrays.asList(BtcECKey.fromPublicOnly(publicKeyBytes[0]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[1]), BtcECKey.fromPublicOnly(publicKeyBytes[2]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[3]), BtcECKey.fromPublicOnly(publicKeyBytes[4]),
                    BtcECKey.fromPublicOnly(publicKeyBytes[5])),
            Instant.ofEpochMilli(0xabcdef), 42L, networkParms);

    byte[] result = BridgeSerializationUtils.serializeFederation(federation);
    Federation deserializedFederation = BridgeSerializationUtils.deserializeFederation(result, networkParms);
    Assert.assertThat(federation, is(deserializedFederation));
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

private static String processFromDate(Date fromValue) {
    final String ret;

    if (fromValue != null) {
        Instant instant = Instant.ofEpochMilli(fromValue.getTime());
        return instant.toString();
    } else {/*from  w w  w.ja  va2 s  . co m*/
        ret = "*";
    }

    return ret;
}

From source file:org.sleuthkit.autopsy.experimental.autoingest.FileExporterSettingsPanel.java

private void populateArtifactEditor(ArtifactCondition artifactConditionToPopulateWith) {
    cbAttributeType.setSelected(true);/*from   w w  w  .j a  v  a2 s  . c om*/
    comboBoxArtifactName.setSelectedItem(artifactConditionToPopulateWith.getArtifactTypeName());
    comboBoxAttributeComparison
            .setSelectedItem(artifactConditionToPopulateWith.getRelationalOperator().getSymbol());
    comboBoxAttributeName.setSelectedItem(artifactConditionToPopulateWith.getAttributeTypeName());
    BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE valueType = artifactConditionToPopulateWith
            .getAttributeValueType();
    comboBoxValueType.setSelectedItem(valueType.getLabel());
    comboBoxValueType
            .setEnabled(null == attributeTypeMap.get(artifactConditionToPopulateWith.getAttributeTypeName()));
    if (valueType == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) {
        Instant instant = Instant
                .ofEpochMilli(artifactConditionToPopulateWith.getDateTimeValue().toDate().getTime());
        dateTimePicker.setDateTime(LocalDateTime.ofInstant(instant, ZoneId.systemDefault()));
    } else {
        tbAttributeValue.setText(artifactConditionToPopulateWith.getStringRepresentationOfValue());
    }
}