Example usage for java.time OffsetDateTime parse

List of usage examples for java.time OffsetDateTime parse

Introduction

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

Prototype

public static OffsetDateTime parse(CharSequence text) 

Source Link

Document

Obtains an instance of OffsetDateTime from a text string such as 2007-12-03T10:15:30+01:00 .

Usage

From source file:org.apache.tinkerpop.gremlin.structure.io.Model.java

private Model() {
    final Configuration conf = new BaseConfiguration();
    conf.setProperty(TinkerGraph.GREMLIN_TINKERGRAPH_DEFAULT_VERTEX_PROPERTY_CARDINALITY,
            VertexProperty.Cardinality.list.name());
    final TinkerGraph graph = TinkerGraph.open(conf);
    TinkerFactory.generateTheCrew(graph);
    final GraphTraversalSource g = graph.traversal();

    final Compatibility[] noTypeGraphSONPlusGryo3_2_3 = Compatibilities.with(GryoCompatibility.class)
            .beforeRelease("3.2.4").join(Compatibilities.UNTYPED_GRAPHSON).matchToArray();
    final Compatibility[] noTypeGraphSONPlusGryo3_3_0 = Compatibilities.with(GryoCompatibility.class)
            .beforeRelease("3.3.0").join(Compatibilities.UNTYPED_GRAPHSON).matchToArray();
    final Compatibility[] noGraphSONBeforeV3 = Compatibilities.with(GraphSONCompatibility.class)
            .configuredAs(".*v2d0-partial|v1d0|v2d0-no-types").join(Compatibilities.GRYO_ONLY).matchToArray();

    // IMPORTANT - the "title" or name of the Entry needs to be unique

    // Serialization of Class in Gryo 1.0 had a bug that prevented proper operation in versions prior to 3.2.4.
    addCoreEntry(File.class, "Class", "", noTypeGraphSONPlusGryo3_2_3);
    addCoreEntry(new Date(1481750076295L), "Date");
    addCoreEntry(100.00d, "Double");
    addCoreEntry(100.00f, "Float", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addCoreEntry(100, "Integer");
    addCoreEntry(Arrays.asList(1, "person", true), "List",
            "List is used to distinguish between different collection types as JSON is not explicit enough for all of Gremlin's requirements.",
            noGraphSONBeforeV3);/*from  w  ww .j  av  a 2s. c o  m*/
    addCoreEntry(100L, "Long", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    final Map<Object, Object> map = new HashMap<>();
    map.put("test", 123);
    map.put(new Date(1481750076295L), "red");
    map.put(Arrays.asList(1, 2, 3), new Date(1481750076295L));
    addCoreEntry(map, "Map",
            "Map is redefined so that to provide the ability to allow for non-String keys, which is not possible in JSON.",
            noGraphSONBeforeV3);
    addCoreEntry(new HashSet<>(Arrays.asList(1, "person", true)), "Set",
            "Allows a JSON collection to behave as a Set.", noGraphSONBeforeV3);
    // Timestamp was added to Gryo 1.0 as of 3.2.4. It was not supported in 3.2.3.
    addCoreEntry(new java.sql.Timestamp(1481750076295L), "Timestamp", "", noTypeGraphSONPlusGryo3_2_3);
    addCoreEntry(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"), "UUID");

    addGraphStructureEntry(graph.edges().next(), "Edge", "");
    addGraphStructureEntry(g.V().out().out().path().next(), "Path", "");
    addGraphStructureEntry(graph.edges().next().properties().next(), "Property", "");
    // TODO: missing a stargraph deserializer in graphson v1/v2
    addEntry("Graph Structure", StarGraph.of(graph.vertices().next()), "StarGraph", "",
            Compatibilities.GRYO_ONLY.match());
    addGraphStructureEntry(graph, "TinkerGraph",
            "`TinkerGraph` has a custom serializer that is registered as part of the `TinkerIoRegistry`.");
    // TODO: tree has bugs for graphson
    addEntry("Graph Structure", g.V(1).out().out().tree().next(), "Tree", "",
            Compatibilities.GRYO_ONLY.match());
    addGraphStructureEntry(graph.vertices().next(), "Vertex", "");
    addGraphStructureEntry(graph.vertices().next().properties().next(), "VertexProperty", "");

    addGraphProcessEntry(SackFunctions.Barrier.normSack, "Barrier", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(new Bytecode.Binding("x", 1), "Binding",
            "A \"Binding\" refers to a `Bytecode.Binding`.", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(g.V().hasLabel("person").out().in().tree().asAdmin().getBytecode(), "Bytecode",
            "The following `Bytecode` example represents the traversal of `g.V().hasLabel('person').out().in().tree()`. Obviously the serialized `Bytecode` woudl be quite different for the endless variations of commands that could be used together in the Gremlin language.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(VertexProperty.Cardinality.list, "Cardinality", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Column.keys, "Column", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Direction.OUT, "Direction", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Operator.sum, "Operator", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Order.incr, "Order", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(TraversalOptionParent.Pick.any, "Pick", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(Pop.all, "Pop", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(org.apache.tinkerpop.gremlin.util.function.Lambda.function("{ it.get() }"), "Lambda",
            "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    final TraversalMetrics tm = createStaticTraversalMetrics();
    final MutableMetrics metrics = new MutableMetrics(tm.getMetrics("7.0.0()"));
    metrics.addNested(new MutableMetrics(tm.getMetrics("3.0.0()")));
    addGraphProcessEntry(metrics, "Metrics", "", noTypeGraphSONPlusGryo3_3_0);
    addGraphProcessEntry(P.gt(0), "P", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(P.within(1), "P within", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(P.without(1, 2), "P without", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    // A bug in the the Gryo serialization of ConjunctiveP prevented its proper serialization in versions prior to 3.3.0 and 3.2.4.
    addGraphProcessEntry(P.gt(0).and(P.lt(10)), "P and", "", noTypeGraphSONPlusGryo3_2_3);
    // A bug in the the Gryo serialization of ConjunctiveP prevented its proper serialization in versions prior to 3.3.0 and 3.2.4.
    addGraphProcessEntry(P.gt(0).or(P.within(-1, -10, -100)), "P or", "", noTypeGraphSONPlusGryo3_2_3);
    addGraphProcessEntry(Scope.local, "Scope", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(T.label, "T", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addGraphProcessEntry(createStaticTraversalMetrics(), "TraversalMetrics", "", noTypeGraphSONPlusGryo3_3_0);
    addGraphProcessEntry(g.V().hasLabel("person").asAdmin().nextTraverser(), "Traverser", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());

    final Map<String, Object> requestBindings = new HashMap<>();
    requestBindings.put("x", 1);

    final Map<String, Object> requestAliases = new HashMap<>();
    requestAliases.put("g", "social");

    // RequestMessage is not testable prior to Gryo 3.0 as serialization was handled by an intermediate component
    // (MessageSerializer) that doesn't fit the test model.
    RequestMessage requestMessage;
    requestMessage = RequestMessage.build("authentication")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("saslMechanism", "PLAIN", "sasl", "AHN0ZXBocGhlbgBwYXNzd29yZA==").create();
    addRequestMessageEntry(requestMessage, "Authentication Response",
            "The following `RequestMessage` is an example of the response that should be made to a SASL-based authentication challenge.");
    requestMessage = RequestMessage.build("eval").processor("session")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "g.V(x)", "bindings", requestBindings, "language", "gremlin-groovy", "session",
                    UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .create();
    addRequestMessageEntry(requestMessage, "Session Eval",
            "The following `RequestMessage` is an example of a simple session request for a script evaluation with parameters.");
    requestMessage = RequestMessage.build("eval").processor("session")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "social.V(x)", "bindings", requestBindings, "language", "gremlin-groovy", "aliases",
                    requestAliases, "session", UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .create();
    addRequestMessageEntry(requestMessage, "Session Eval Aliased",
            "The following `RequestMessage` is an example of a session request for a script evaluation with an alias that binds the `TraversalSource` of \"g\" to \"social\".");
    requestMessage = RequestMessage.build("close").processor("session")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("session", UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786")).create();
    addRequestMessageEntry(requestMessage, "Session Close",
            "The following `RequestMessage` is an example of a request to close a session.");
    requestMessage = RequestMessage.build("eval")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "g.V(x)", "bindings", requestBindings, "language", "gremlin-groovy").create();
    addRequestMessageEntry(requestMessage, "Sessionless Eval",
            "The following `RequestMessage` is an example of a simple sessionless request for a script evaluation with parameters.");
    requestMessage = RequestMessage.build("eval")
            .overrideRequestId(UUID.fromString("cb682578-9d92-4499-9ebc-5c6aa73c5397"))
            .add("gremlin", "social.V(x)", "bindings", requestBindings, "language", "gremlin-groovy", "aliases",
                    requestAliases)
            .create();
    addRequestMessageEntry(requestMessage, "Sessionless Eval Aliased",
            "The following `RequestMessage` is an example of a sessionless request for a script evaluation with an alias that binds the `TraversalSource` of \"g\" to \"social\".");

    // ResponseMessage is not testable prior to Gryo 3.0 as serialization was handled by an intermediate component
    // (MessageSerializer) that doesn't fit the test model
    ResponseMessage responseMessage = ResponseMessage
            .build(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .code(org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode.AUTHENTICATE).create();
    addResponseMessageEntry(responseMessage, "Authentication Challenge",
            "When authentication is enabled, an initial request to the server will result in an authentication challenge. The typical response message will appear as follows, but handling it could be different depending on the SASL implementation (e.g. multiple challenges maybe requested in some cases, but not in the default provided by Gremlin Server).");
    responseMessage = ResponseMessage.build(UUID.fromString("41d2e28a-20a4-4ab0-b379-d810dede3786"))
            .code(org.apache.tinkerpop.gremlin.driver.message.ResponseStatusCode.SUCCESS)
            .result(Collections.singletonList(graph.vertices().next())).create();
    addResponseMessageEntry(responseMessage, "Standard Result",
            "The following `ResponseMessage` is a typical example of the typical successful response Gremlin Server will return when returning results from a script.");

    addExtendedEntry(new BigDecimal(new java.math.BigInteger("123456789987654321123456789987654321")),
            "BigDecimal", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(new BigInteger("123456789987654321123456789987654321"), "BigInteger", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(new Byte("1"), "Byte", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    // ByteBuffer was added to Gryo 1.0 as of 3.2.4. It was not supported in earlier versions.
    addEntry("Extended", () -> java.nio.ByteBuffer.wrap("some bytes for you".getBytes()), "ByteBuffer", "",
            noTypeGraphSONPlusGryo3_2_3);
    addExtendedEntry("x".charAt(0), "Char", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(Duration.ofDays(5), "Duration", "The following example is a `Duration` of five days.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    try {
        // InetAddress was added to Gryo 1.0 as of 3.2.4. It was not supported in earlier versions.
        addEntry("Extended", InetAddress.getByName("localhost"), "InetAddress", "",
                noTypeGraphSONPlusGryo3_2_3);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    addExtendedEntry(Instant.parse("2016-12-14T16:39:19.349Z"), "Instant", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(LocalDate.of(2016, 1, 1), "LocalDate", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(LocalDateTime.of(2016, 1, 1, 12, 30), "LocalDateTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(LocalTime.of(12, 30, 45), "LocalTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(MonthDay.of(1, 1), "MonthDay", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(OffsetDateTime.parse("2007-12-03T10:15:30+01:00"), "OffsetDateTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(OffsetTime.parse("10:15:30+01:00"), "OffsetTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(Period.of(1, 6, 15), "Period",
            "The following example is a `Period` of one year, six months and fifteen days.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(new Short("100"), "Short", "", Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(Year.of(2016), "Year", "The following example is of the `Year` \"2016\".",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(YearMonth.of(2016, 6), "YearMonth",
            "The following example is a `YearMonth` of \"June 2016\"",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(ZonedDateTime.of(2016, 12, 23, 12, 12, 24, 36, ZoneId.of("GMT+2")), "ZonedDateTime", "",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
    addExtendedEntry(ZoneOffset.ofHoursMinutesSeconds(3, 6, 9), "ZoneOffset",
            "The following example is a `ZoneOffset` of three hours, six minutes, and nine seconds.",
            Compatibilities.UNTYPED_GRAPHSON.matchToArray());
}

From source file:net.dv8tion.jda.handle.EntityBuilder.java

public Message createMessage(JSONObject jsonObject) {
    String id = jsonObject.getString("id");
    String content = jsonObject.getString("content");
    MessageImpl message = new MessageImpl(id, api)
            .setAuthor(api.getUserMap().get(jsonObject.getJSONObject("author").getString("id")))
            .setContent(content).setTime(OffsetDateTime.parse(jsonObject.getString("timestamp")))
            .setMentionsEveryone(jsonObject.getBoolean("mention_everyone")).setTTS(jsonObject.getBoolean("tts"))
            .setPinned(jsonObject.getBoolean("pinned"));

    List<Message.Attachment> attachments = new LinkedList<>();
    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));
    }/*from  w  ww . j a  v  a 2  s .c o m*/
    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);

    Matcher matcher = emotePatter.matcher(content);
    List<Emote> emoteList = new LinkedList<>();
    while (matcher.find())
        emoteList.add(
                api.getEmoteById(matcher.group(2)) == null ? new EmoteImpl(matcher.group(1), matcher.group(2))
                        : api.getEmoteById(matcher.group(2)));
    message.setEmotes(emoteList);

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

    String channelId = jsonObject.getString("channel_id");
    TextChannel textChannel = api.getChannelMap().get(channelId);
    if (textChannel != null) {
        message.setChannelId(textChannel.getId());
        message.setIsPrivate(false);
        TreeMap<Integer, User> mentionedUsers = new TreeMap<>();
        JSONArray mentions = jsonObject.getJSONArray("mentions");
        for (int i = 0; i < mentions.length(); i++) {
            JSONObject mention = mentions.getJSONObject(i);
            User u = api.getUserMap().get(mention.getString("id"));
            if (u != null) {
                //We do this to properly order the mentions. The array given by discord is out of order sometimes.
                int index = content.indexOf("<@" + mention.getString("id") + ">");
                mentionedUsers.put(index, u);
            }
        }
        message.setMentionedUsers(new LinkedList<User>(mentionedUsers.values()));

        TreeMap<Integer, Role> mentionedRoles = new TreeMap<>();
        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<>();
        Map<String, TextChannel> chanMap = ((GuildImpl) textChannel.getGuild()).getTextChannelsMap();
        matcher = channelMentionPattern.matcher(content);
        while (matcher.find()) {
            TextChannel channel = chanMap.get(matcher.group(1));
            if (channel != null && !mentionedChannels.contains(channel)) {
                mentionedChannels.add(channel);
            }
        }
        message.setMentionedChannels(mentionedChannels);
    } else {
        message.setIsPrivate(true);
        PrivateChannel privateChannel = api.getPmChannelMap().get(channelId);
        if (privateChannel != null) {
            message.setChannelId(privateChannel.getId());
        } else {
            throw new IllegalArgumentException("Could not find Private/Text Channel of id " + channelId);
        }
    }

    return message;
}

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

public Member createMember(GuildImpl guild, JSONObject memberJson) {
    User user = createUser(memberJson.getJSONObject("user"));
    MemberImpl member = (MemberImpl) guild.getMember(user);
    if (member == null) {
        member = new MemberImpl(guild, user);
        guild.getMembersMap().put(user.getIdLong(), member);
    }/*from  w ww . j  a  va2 s  .c  o m*/

    ((GuildVoiceStateImpl) member.getVoiceState()).setGuildMuted(memberJson.getBoolean("mute"))
            .setGuildDeafened(memberJson.getBoolean("deaf"));

    member.setJoinDate(OffsetDateTime.parse(memberJson.getString("joined_at"))).setNickname(
            memberJson.has("nick") && !memberJson.isNull("nick") ? memberJson.getString("nick") : null);

    JSONArray rolesJson = memberJson.getJSONArray("roles");
    for (int k = 0; k < rolesJson.length(); k++) {
        final long roleId = rolesJson.getLong(k);
        Role r = guild.getRolesMap().get(roleId);
        if (r == null) {
            WebSocketClient.LOG.debug("Received a Member with an unknown Role. MemberId: "
                    + member.getUser().getId() + " GuildId: " + guild.getId() + " roleId: " + roleId);
        } else {
            member.getRoleSet().add(r);
        }
    }

    return member;
}

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

public Instant parseDate(Serializable value) {

    if (value instanceof Date) {
        return ((Date) value).toInstant();
    }/*from ww w .j  av a 2s  .com*/

    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: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(// www .ja  va2 s  . c o  m
                    !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.silverpeas.core.calendar.icalendar.ICal4JExchangeImportTest.java

private static OffsetDateTime datetime(String date) {
    return OffsetDateTime.parse(date);
}

From source file:org.silverpeas.core.calendar.CalendarEventOccurrence.java

private static Temporal getDate(String temporal) {
    if (temporal.contains("T")) {
        return OffsetDateTime.parse(temporal);
    } else {//from  w  w  w  .j av a2s  .co  m
        return LocalDate.parse(temporal);
    }
}

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

public MessageEmbed createMessageEmbed(JSONObject messageEmbed) {
    if (messageEmbed.isNull("type"))
        throw new JSONException(
                "Encountered embed object with missing/null type field for Json: " + messageEmbed);
    EmbedType type = EmbedType.fromKey(messageEmbed.getString("type"));
    /* if (type == EmbedType.UNKNOWN)
    throw new JSONException("Discord provided us an unknown embed type.  Json: " + messageEmbed);*/
    MessageEmbedImpl embed = new MessageEmbedImpl().setType(type)
            .setUrl(messageEmbed.isNull("url") ? null : messageEmbed.getString("url"))
            .setTitle(messageEmbed.isNull("title") ? null : messageEmbed.getString("title"))
            .setDescription(messageEmbed.isNull("description") ? null : messageEmbed.getString("description"))
            .setColor(messageEmbed.isNull("color") || messageEmbed.getInt("color") == 0 ? null
                    : new Color(messageEmbed.getInt("color")))
            .setTimestamp(messageEmbed.isNull("timestamp") ? null
                    : OffsetDateTime.parse(messageEmbed.getString("timestamp")));

    if (messageEmbed.has("thumbnail")) {
        JSONObject thumbnailJson = messageEmbed.getJSONObject("thumbnail");
        embed.setThumbnail(new Thumbnail(thumbnailJson.getString("url"), thumbnailJson.getString("proxy_url"),
                thumbnailJson.getInt("width"), thumbnailJson.getInt("height")));
    } else//  w w  w  . j a  v  a  2  s . c  o  m
        embed.setThumbnail(null);

    if (messageEmbed.has("provider")) {
        JSONObject providerJson = messageEmbed.getJSONObject("provider");
        embed.setSiteProvider(new Provider(providerJson.isNull("name") ? null : providerJson.getString("name"),
                providerJson.isNull("url") ? null : providerJson.getString("url")));
    } else
        embed.setSiteProvider(null);

    if (messageEmbed.has("author")) {
        JSONObject authorJson = messageEmbed.getJSONObject("author");
        embed.setAuthor(new AuthorInfo(authorJson.isNull("name") ? null : authorJson.getString("name"),
                authorJson.isNull("url") ? null : authorJson.getString("url"),
                authorJson.isNull("icon_url") ? null : authorJson.getString("icon_url"),
                authorJson.isNull("proxy_icon_url") ? null : authorJson.getString("proxy_icon_url")));
    } else
        embed.setAuthor(null);

    if (messageEmbed.has("image")) {
        JSONObject imageJson = messageEmbed.getJSONObject("image");
        embed.setImage(new ImageInfo(imageJson.isNull("url") ? null : imageJson.getString("url"),
                imageJson.isNull("proxy_url") ? null : imageJson.getString("proxy_url"),
                imageJson.isNull("width") ? -1 : imageJson.getInt("width"),
                imageJson.isNull("height") ? -1 : imageJson.getInt("height")));
    } else
        embed.setImage(null);

    if (messageEmbed.has("footer")) {
        JSONObject footerJson = messageEmbed.getJSONObject("footer");
        embed.setFooter(new Footer(footerJson.isNull("text") ? null : footerJson.getString("text"),
                footerJson.isNull("icon_url") ? null : footerJson.getString("icon_url"),
                footerJson.isNull("proxy_icon_url") ? null : footerJson.getString("proxy_icon_url")));
    } else
        embed.setFooter(null);

    if (messageEmbed.has("fields")) {
        JSONArray fieldsJson = messageEmbed.getJSONArray("fields");
        List<Field> fields = new LinkedList<>();
        for (int index = 0; index < fieldsJson.length(); index++) {
            JSONObject fieldJson = fieldsJson.getJSONObject(index);
            fields.add(new Field(fieldJson.isNull("name") ? null : fieldJson.getString("name"),
                    fieldJson.isNull("value") ? null : fieldJson.getString("value"),
                    !fieldJson.isNull("inline") && fieldJson.getBoolean("inline"), false)); // unchecked field instantiation
        }
        embed.setFields(fields);
    } else
        embed.setFields(Collections.emptyList());

    if (messageEmbed.has("video")) {
        JSONObject videoJson = messageEmbed.getJSONObject("video");
        embed.setVideoInfo(new MessageEmbed.VideoInfo(videoJson.getString("url"),
                videoJson.isNull("width") ? -1 : videoJson.getInt("width"),
                videoJson.isNull("height") ? -1 : videoJson.getInt("height")));
    }
    return embed;
}

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

public Invite createInvite(JSONObject object) {
    final String code = object.getString("code");

    final User inviter = object.has("inviter") ? this.createFakeUser(object.getJSONObject("inviter"), false)
            : null;//from  w ww. j  a  va 2s  .  c  om

    final JSONObject channelObject = object.getJSONObject("channel");

    final ChannelType channelType = ChannelType.fromId(channelObject.getInt("type"));
    final long channelId = channelObject.getLong("id");
    final String channelName = channelObject.getString("name");

    final Invite.Channel channel = new InviteImpl.ChannelImpl(channelId, channelName, channelType);

    final JSONObject guildObject = object.getJSONObject("guild");

    final String guildIconId = guildObject.isNull("icon") ? null : guildObject.getString("icon");
    final long guildId = guildObject.getLong("id");
    final String guildName = guildObject.getString("name");
    final String guildSplashId = guildObject.isNull("splash") ? null : guildObject.getString("splash");

    final Invite.Guild guild = new InviteImpl.GuildImpl(guildId, guildIconId, guildName, guildSplashId);

    final int maxAge;
    final int maxUses;
    final boolean temporary;
    final OffsetDateTime timeCreated;
    final int uses;
    final boolean expanded;

    if (object.has("max_uses")) {
        expanded = true;
        maxAge = object.getInt("max_age");
        maxUses = object.getInt("max_uses");
        uses = object.getInt("uses");
        temporary = object.getBoolean("temporary");
        timeCreated = OffsetDateTime.parse(object.getString("created_at"));
    } else {
        expanded = false;
        maxAge = -1;
        maxUses = -1;
        uses = -1;
        temporary = false;
        timeCreated = null;
    }

    return new InviteImpl(api, code, expanded, inviter, maxAge, maxUses, temporary, timeCreated, uses, channel,
            guild);
}