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() 

Source Link

Document

Obtains the current date-time from the system clock in the default time-zone.

Usage

From source file:org.silverpeas.components.gallery.notification.user.AlbumMediaNotificationManagerTest.java

@Test
void putCreationWithDelayOnSeveralAlbumsWithLatency() throws Exception {
    gallerySettings.put("subscription.notification.delay", "10");
    final OffsetDateTime now = OffsetDateTime.now();
    testedManager.putCreationOf(albumMediaA, senderX);
    testedManager.putCreationOf(albumMediaB, senderX);
    await().pollInterval(5, TimeUnit.SECONDS).until(() -> true);
    testedManager.putCreationOf(albumMediaC, senderX);
    testedManager.putCreationOf(albumMediaD, senderX);
    assertThat(getContextCache().size(), is(3));
    final String expectedKey1 = "1@gallery38@26";
    assertThat(getContextCache(), hasKey(expectedKey1));
    NotificationAlbumJob notificationAlbumJob = getContextCache().get(expectedKey1);
    assertNotificationAlbumJob(notificationAlbumJob, 2, albumDetail1, senderX);
    final String expectedKey2 = "1@gallery38@27";
    assertThat(getContextCache(), hasKey(expectedKey2));
    notificationAlbumJob = getContextCache().get(expectedKey2);
    assertNotificationAlbumJob(notificationAlbumJob, 1, albumDetail2, senderX);
    final String expectedKey3 = "1@gallery39@28";
    assertThat(getContextCache(), hasKey(expectedKey3));
    notificationAlbumJob = getContextCache().get(expectedKey3);
    assertNotificationAlbumJob(notificationAlbumJob, 1, albumDetail3, senderX);
    verify(scheduler, times(4)).unscheduleJob(anyString());
    final ArgumentCaptor<JobTrigger> captor = forClass(JobTrigger.class);
    verify(scheduler, times(4)).scheduleJob(any(NotificationAlbumJob.class), captor.capture());
    final List<JobTrigger> jobTriggers = captor.getAllValues();
    assertThat(jobTriggers, hasSize(4));
    assertJobScheduled(jobTriggers.get(0), now, 0);
    assertJobScheduled(jobTriggers.get(1), now, 0);
    assertJobScheduled(jobTriggers.get(2), now, 5000);
    assertJobScheduled(jobTriggers.get(3), now, 5000);
}

From source file:net.dv8tion.jda.core.requests.WebSocketClient.java

@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame,
        WebSocketFrame clientCloseFrame, boolean closedByServer) {
    sentAuthInfo = false;// www.  j a  v a2s  . c o m
    connected = false;
    api.setStatus(JDA.Status.DISCONNECTED);

    CloseCode closeCode = null;
    int rawCloseCode = 1000;

    if (keepAliveThread != null) {
        keepAliveThread.interrupt();
        keepAliveThread = null;
    }
    if (serverCloseFrame != null) {
        rawCloseCode = serverCloseFrame.getCloseCode();
        closeCode = CloseCode.from(rawCloseCode);
        if (closeCode == CloseCode.RATE_LIMITED)
            LOG.fatal(
                    "WebSocket connection closed due to ratelimit! Sent more than 120 websocket messages in under 60 seconds!");
        else if (closeCode != null)
            LOG.debug("WebSocket connection closed with code " + closeCode);
        else
            LOG.warn("WebSocket connection closed with unknown meaning for close-code " + rawCloseCode);
    }

    // null is considered -reconnectable- as we do not know the close-code meaning
    boolean closeCodeIsReconnect = closeCode == null || closeCode.isReconnect();
    if (!shouldReconnect || !closeCodeIsReconnect) //we should not reconnect
    {
        if (ratelimitThread != null)
            ratelimitThread.interrupt();

        if (!closeCodeIsReconnect) {
            //it is possible that a token can be invalidated due to too many reconnect attempts
            //or that a bot reached a new shard minimum and cannot connect with the current settings
            //if that is the case we have to drop our connection and inform the user with a fatal error message
            LOG.fatal("WebSocket connection was closed and cannot be recovered due to identification issues");
            LOG.fatal(closeCode);
        }

        api.setStatus(JDA.Status.SHUTDOWN);
        api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), rawCloseCode));
    } else {
        if (rawCloseCode == 1000)
            invalidate(); // 1000 means our session is dropped so we cannot resume
        api.getEventManager().handle(new DisconnectEvent(api, serverCloseFrame, clientCloseFrame,
                closedByServer, OffsetDateTime.now()));
        reconnect();
    }
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public <T extends Record> T createRecord(RecordConfig config, OrmFactory<T> factory) {
    OffsetDateTime now = OffsetDateTime.now();
    return addPropertiesToRecord(factory.createNew(vf.createIRI(RECORD_NAMESPACE + UUID.randomUUID())), config,
            now, now);/*from  www.ja  v a2  s .c  o  m*/
}

From source file:org.silverpeas.components.gallery.notification.user.AlbumMediaNotificationManagerTest.java

@Test
void putCreationAndThenDeletionOfSameMediaWithDelay() throws Exception {
    final OffsetDateTime now = OffsetDateTime.now();
    gallerySettings.put("subscription.notification.delay", "10");
    testedManager.putCreationOf(albumMediaA, senderX);
    testedManager.putDeletionOf(albumMediaA, senderX);
    assertThat(getContextCache().size(), is(0));
    verify(scheduler, times(2)).unscheduleJob(anyString());
    final ArgumentCaptor<JobTrigger> captor = forClass(JobTrigger.class);
    verify(scheduler, times(1)).scheduleJob(any(NotificationAlbumJob.class), captor.capture());
    final JobTrigger jobTrigger = captor.getValue();
    assertJobScheduled(jobTrigger, now, 0);
}

From source file:org.silverpeas.components.gallery.notification.user.AlbumMediaNotificationManagerTest.java

@Test
void putCreationThenDeletionAndThenCreationOfSameMediaWithDelay() throws Exception {
    final OffsetDateTime now = OffsetDateTime.now();
    gallerySettings.put("subscription.notification.delay", "10");
    testedManager.putCreationOf(albumMediaA, senderX);
    testedManager.putDeletionOf(albumMediaA, senderX);
    testedManager.putCreationOf(albumMediaA, senderX);
    assertThat(getContextCache().size(), is(1));
    final String expectedKey = "1@gallery38@26";
    assertThat(getContextCache(), hasKey(expectedKey));
    final NotificationAlbumJob notificationAlbumJob = getContextCache().get(expectedKey);
    assertNotificationAlbumJob(notificationAlbumJob, 1, albumDetail1, senderX);
    verify(scheduler, times(3)).unscheduleJob(anyString());
    final ArgumentCaptor<JobTrigger> captor = forClass(JobTrigger.class);
    verify(scheduler, times(2)).scheduleJob(any(NotificationAlbumJob.class), captor.capture());
    final List<JobTrigger> jobTriggers = captor.getAllValues();
    assertThat(jobTriggers, hasSize(2));
    assertJobScheduled(jobTriggers.get(0), now, 0);
    assertJobScheduled(jobTriggers.get(1), now, 0);
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public Distribution createDistribution(DistributionConfig config) {
    OffsetDateTime now = OffsetDateTime.now();

    Distribution distribution = distributionFactory
            .createNew(vf.createIRI(DISTRIBUTION_NAMESPACE + UUID.randomUUID()));
    distribution.setProperty(vf.createLiteral(config.getTitle()), vf.createIRI(DCTERMS.TITLE.stringValue()));
    distribution.setProperty(vf.createLiteral(now), vf.createIRI(DCTERMS.ISSUED.stringValue()));
    distribution.setProperty(vf.createLiteral(now), vf.createIRI(DCTERMS.MODIFIED.stringValue()));
    if (config.getDescription() != null) {
        distribution.setProperty(vf.createLiteral(config.getDescription()),
                vf.createIRI(DCTERMS.DESCRIPTION.stringValue()));
    }//from  w  ww . j  a va 2  s.c om
    if (config.getFormat() != null) {
        distribution.setProperty(vf.createLiteral(config.getFormat()),
                vf.createIRI(DCTERMS.FORMAT.stringValue()));
    }
    if (config.getAccessURL() != null) {
        distribution.setAccessURL(config.getAccessURL());
    }
    if (config.getDownloadURL() != null) {
        distribution.setDownloadURL(config.getDownloadURL());
    }

    return distribution;
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public <T extends Version> T createVersion(@Nonnull String title, String description, OrmFactory<T> factory) {
    OffsetDateTime now = OffsetDateTime.now();

    T version = factory.createNew(vf.createIRI(VERSION_NAMESPACE + UUID.randomUUID()));
    version.setProperty(vf.createLiteral(title), vf.createIRI(DCTERMS.TITLE.stringValue()));
    if (description != null) {
        version.setProperty(vf.createLiteral(description), vf.createIRI(DCTERMS.DESCRIPTION.stringValue()));
    }/*from ww  w  .j  a  v  a  2 s  . com*/
    version.setProperty(vf.createLiteral(now), vf.createIRI(DCTERMS.ISSUED.stringValue()));
    version.setProperty(vf.createLiteral(now), vf.createIRI(DCTERMS.MODIFIED.stringValue()));

    return version;
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public <T extends Branch> T createBranch(@Nonnull String title, String description, OrmFactory<T> factory) {
    OffsetDateTime now = OffsetDateTime.now();

    T branch = factory.createNew(vf.createIRI(BRANCH_NAMESPACE + UUID.randomUUID()));
    branch.setProperty(vf.createLiteral(title), vf.createIRI(DCTERMS.TITLE.stringValue()));
    branch.setProperty(vf.createLiteral(now), vf.createIRI(DCTERMS.ISSUED.stringValue()));
    branch.setProperty(vf.createLiteral(now), vf.createIRI(DCTERMS.MODIFIED.stringValue()));
    if (description != null) {
        branch.setProperty(vf.createLiteral(description), vf.createIRI(DCTERMS.DESCRIPTION.stringValue()));
    }/*  ww  w .j  a v  a 2 s  .co  m*/

    return branch;
}

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

public Message createMessage(JSONObject jsonObject, MessageChannel chan, boolean exceptionOnMissingUser) {
    final long id = jsonObject.getLong("id");
    String content = !jsonObject.isNull("content") ? jsonObject.getString("content") : "";

    JSONObject author = jsonObject.getJSONObject("author");
    final long authorId = author.getLong("id");
    boolean fromWebhook = jsonObject.has("webhook_id");

    MessageImpl message = new MessageImpl(id, chan, fromWebhook).setContent(content)
            .setTime(!jsonObject.isNull("timestamp") ? OffsetDateTime.parse(jsonObject.getString("timestamp"))
                    : OffsetDateTime.now())
            .setMentionsEveryone(/*  w w  w. j a v a  2 s  . c  om*/
                    !jsonObject.isNull("mention_everyone") && jsonObject.getBoolean("mention_everyone"))
            .setTTS(!jsonObject.isNull("tts") && jsonObject.getBoolean("tts"))
            .setPinned(!jsonObject.isNull("pinned") && jsonObject.getBoolean("pinned"));
    if (chan instanceof PrivateChannel) {
        if (authorId == api.getSelfUser().getIdLong())
            message.setAuthor(api.getSelfUser());
        else
            message.setAuthor(((PrivateChannel) chan).getUser());
    } else if (chan instanceof Group) {
        UserImpl user = (UserImpl) api.getUserMap().get(authorId);
        if (user == null)
            user = (UserImpl) api.getFakeUserMap().get(authorId);
        if (user == null && fromWebhook)
            user = (UserImpl) createFakeUser(author, false);
        if (user == null) {
            if (exceptionOnMissingUser)
                throw new IllegalArgumentException(MISSING_USER); //Specifically for MESSAGE_CREATE
            else
                user = (UserImpl) createFakeUser(author, false); //Any message creation that isn't MESSAGE_CREATE
        }
        message.setAuthor(user);

        //If the message was sent by a cached fake user, lets update it.
        if (user.isFake() && !fromWebhook) {
            user.setName(author.getString("username")).setDiscriminator(author.get("discriminator").toString())
                    .setAvatarId(author.isNull("avatar") ? null : author.getString("avatar"))
                    .setBot(author.has("bot") && author.getBoolean("bot"));
        }
    } else {
        GuildImpl guild = (GuildImpl) ((TextChannel) chan).getGuild();
        Member member = guild.getMembersMap().get(authorId);
        User user = member != null ? member.getUser() : null;
        if (user != null)
            message.setAuthor(user);
        else if (fromWebhook || !exceptionOnMissingUser)
            message.setAuthor(createFakeUser(author, false));
        else
            throw new IllegalArgumentException(MISSING_USER);
    }

    List<Message.Attachment> attachments = new LinkedList<>();
    if (!jsonObject.isNull("attachments")) {
        JSONArray jsonAttachments = jsonObject.getJSONArray("attachments");
        for (int i = 0; i < jsonAttachments.length(); i++) {
            JSONObject jsonAttachment = jsonAttachments.getJSONObject(i);
            attachments.add(new Message.Attachment(jsonAttachment.getString("id"),
                    jsonAttachment.getString("url"), jsonAttachment.getString("proxy_url"),
                    jsonAttachment.getString("filename"), jsonAttachment.getInt("size"),
                    jsonAttachment.has("height") ? jsonAttachment.getInt("height") : 0,
                    jsonAttachment.has("width") ? jsonAttachment.getInt("width") : 0, api));
        }
    }
    message.setAttachments(attachments);

    List<MessageEmbed> embeds = new LinkedList<>();
    JSONArray jsonEmbeds = jsonObject.getJSONArray("embeds");
    for (int i = 0; i < jsonEmbeds.length(); i++) {
        embeds.add(createMessageEmbed(jsonEmbeds.getJSONObject(i)));
    }
    message.setEmbeds(embeds);

    if (!jsonObject.isNull("edited_timestamp"))
        message.setEditedTime(OffsetDateTime.parse(jsonObject.getString("edited_timestamp")));

    if (jsonObject.has("reactions")) {
        JSONArray reactions = jsonObject.getJSONArray("reactions");
        List<MessageReaction> list = new LinkedList<>();
        for (int i = 0; i < reactions.length(); i++) {
            JSONObject obj = reactions.getJSONObject(i);
            JSONObject emoji = obj.getJSONObject("emoji");

            final Long emojiId = emoji.isNull("id") ? null : emoji.getLong("id");
            String emojiName = emoji.getString("name");

            boolean self = obj.has("self") && obj.getBoolean("self");
            int count = obj.getInt("count");
            Emote emote = null;
            if (emojiId != null) {
                emote = api.getEmoteById(emojiId);
                if (emote == null)
                    emote = new EmoteImpl(emojiId, api).setName(emojiName);
            }
            MessageReaction.ReactionEmote reactionEmote;
            if (emote == null)
                reactionEmote = new MessageReaction.ReactionEmote(emojiName, null, api);
            else
                reactionEmote = new MessageReaction.ReactionEmote(emote);
            list.add(new MessageReaction(chan, reactionEmote, message.getIdLong(), self, count));
        }
        message.setReactions(list);
    }

    if (message.isFromType(ChannelType.TEXT)) {
        TextChannel textChannel = message.getTextChannel();
        TreeMap<Integer, User> mentionedUsers = new TreeMap<>();
        if (!jsonObject.isNull("mentions")) {
            JSONArray mentions = jsonObject.getJSONArray("mentions");
            for (int i = 0; i < mentions.length(); i++) {
                JSONObject mention = mentions.getJSONObject(i);
                User u = api.getUserById(mention.getLong("id"));
                if (u != null) {
                    //We do this to properly order the mentions. The array given by discord is out of order sometimes.

                    String mentionId = mention.getString("id");
                    int index = content.indexOf("<@" + mentionId + ">");
                    if (index < 0)
                        index = content.indexOf("<@!" + mentionId + ">");
                    mentionedUsers.put(index, u);
                }
            }
        }
        message.setMentionedUsers(new LinkedList<User>(mentionedUsers.values()));

        TreeMap<Integer, Role> mentionedRoles = new TreeMap<>();
        if (!jsonObject.isNull("mention_roles")) {
            JSONArray roleMentions = jsonObject.getJSONArray("mention_roles");
            for (int i = 0; i < roleMentions.length(); i++) {
                String roleId = roleMentions.getString(i);
                Role r = textChannel.getGuild().getRoleById(roleId);
                if (r != null) {
                    int index = content.indexOf("<@&" + roleId + ">");
                    mentionedRoles.put(index, r);
                }
            }
        }
        message.setMentionedRoles(new LinkedList<Role>(mentionedRoles.values()));

        List<TextChannel> mentionedChannels = new LinkedList<>();
        TLongObjectMap<TextChannel> chanMap = ((GuildImpl) textChannel.getGuild()).getTextChannelsMap();
        Matcher matcher = channelMentionPattern.matcher(content);
        while (matcher.find()) {
            TextChannel channel = chanMap.get(Long.parseLong(matcher.group(1)));
            if (channel != null && !mentionedChannels.contains(channel)) {
                mentionedChannels.add(channel);
            }
        }
        message.setMentionedChannels(mentionedChannels);
    }
    return message;
}

From source file:org.matonto.catalog.impl.SimpleCatalogManager.java

@Override
public Commit createCommit(@Nonnull InProgressCommit inProgressCommit, Set<Commit> parents,
        @Nonnull String message) {
    IRI associatedWith = vf.createIRI(Activity.wasAssociatedWith_IRI);
    IRI informedBy = vf.createIRI(Activity.wasInformedBy_IRI);
    OffsetDateTime now = OffsetDateTime.now();
    Value user = inProgressCommit.getProperty(associatedWith).get();
    String metadata = now.toString() + user.stringValue();
    IRI generatedIRI = vf.createIRI(Activity.generated_IRI);

    if (parents != null) {
        metadata += parents.stream()//from   w w  w  .j  av  a 2  s  . c om
                .sorted(Comparator.comparing(commit2 -> commit2.getResource().stringValue()))
                .map(commit -> commit.getResource().stringValue()).collect(Collectors.joining(""));
    }

    Commit commit = commitFactory.createNew(vf.createIRI(COMMIT_NAMESPACE + DigestUtils.shaHex(metadata)));
    commit.setProperty(inProgressCommit.getProperty(generatedIRI).get(), generatedIRI);
    commit.setProperty(vf.createLiteral(now), vf.createIRI(PROV_AT_TIME));
    commit.setProperty(vf.createLiteral(message), vf.createIRI(DCTERMS.TITLE.stringValue()));
    commit.setProperty(user, associatedWith);

    Model revisionModel = mf.createModel(inProgressCommit.getModel());
    revisionModel.remove(inProgressCommit.getResource(), null, null);
    Revision revision = revisionFactory.getExisting((Resource) inProgressCommit.getProperty(generatedIRI).get(),
            revisionModel);

    if (parents != null) {
        revision.setProperties(parents.stream().map(parent -> parent.getProperty(generatedIRI).get())
                .collect(Collectors.toSet()), vf.createIRI(Entity.wasDerivedFrom_IRI));
        commit.setProperties(parents.stream().map(Commit::getResource).collect(Collectors.toSet()), informedBy);
    }

    commit.getModel().addAll(revisionModel);
    return commit;
}