Example usage for com.google.gson.stream JsonReader JsonReader

List of usage examples for com.google.gson.stream JsonReader JsonReader

Introduction

In this page you can find the example usage for com.google.gson.stream JsonReader JsonReader.

Prototype

public JsonReader(Reader in) 

Source Link

Document

Creates a new instance that reads a JSON-encoded stream from in .

Usage

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

/**
 * Gets the amount of people subscribed to the specified channel
 * /*  w  w w  . java2  s .co m*/
 * @param channelNoHash - channel to get subscriber count for
 * @param oAuth - oAuth of the channel
 * @return number of subscribers for the channel
 */
public static int subscriberCount(String channelNoHash, String oAuth) {
    try (InputStream stream = new URL(
            BASE_URL + "channels/" + channelNoHash + "/subscriptions/?oauth_token=" + oAuth).openStream()) {
        return new JsonParser().parse(new JsonReader(new InputStreamReader(stream))).getAsJsonObject()
                .getAsJsonPrimitive("_total").getAsInt();
    } catch (JsonIOException | JsonSyntaxException | IOException | NullPointerException e) {
        logger.log(Level.SEVERE, "An error occurred getting the subscriber count for " + channelNoHash, e);
        WLogger.logError(e);
    }
    return 0;
}

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

/**
 * @param channelNoHash/*from   w  w  w .  ja  va  2 s. co  m*/
 *            - channel to run the commercial in without the leading #
 * @return true if the channel is live, false otherwise
 */
public static boolean isLive(String channelNoHash) {
    try (InputStream stream = new URL(BASE_URL + "streams/" + channelNoHash).openStream()) {
        new JsonParser().parse(new JsonReader(new InputStreamReader(stream))).getAsJsonObject()
                .getAsJsonObject("stream").getAsJsonNull();
        return false;
    } catch (IllegalStateException | ClassCastException e) {
        return true;
    } catch (JsonSyntaxException | IOException e) {
        logger.log(Level.SEVERE, "An error occurred checking if the streamer is live!", e);
        WLogger.logError(e);
    }
    return false;
}

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

private static ArrayList<String> getGlobalEmotes() {
    ArrayList<String> globalEmotes = new ArrayList<>();
    try (InputStream stream = new URL(EMOTE_URL + "global.json").openStream()) {
        Set<Map.Entry<String, JsonElement>> channels = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(stream))).getAsJsonObject()
                .getAsJsonObject("emotes").entrySet();

        for (Map.Entry entry : channels) {
            globalEmotes.add(entry.getKey().toString());
        }/*from w  ww.j  av  a  2s  . c  o m*/
    } catch (JsonSyntaxException | IOException e) {
        logger.log(Level.WARNING, "An error occurred updating the emote database!", e);
        WLogger.logError(e);
    }
    return globalEmotes;
}

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

public static ArrayList<String> getSubEmotes() {
    ArrayList<String> subEmotes = new ArrayList<>();
    InputStream stream = null;/*from w w w  .  j  av  a  2 s  .c o  m*/
    InputStream stream1 = null;
    try {
        stream = new URL(EMOTE_URL + "sets.json").openStream();
        Set<Map.Entry<String, JsonElement>> channels = new JsonParser()
                .parse(new JsonReader(new InputStreamReader(stream))).getAsJsonObject().getAsJsonObject("sets")
                .entrySet();
        stream1 = new URL(EMOTE_URL + "subscriber.json").openStream();
        JsonObject subEmotesObject = new JsonParser().parse(new JsonReader(new InputStreamReader(stream1)))
                .getAsJsonObject().getAsJsonObject("channels");
        channels.stream().filter(entry -> !entry.getValue().toString().replaceAll("\"", "").startsWith("--"))
                .forEach(entry -> {
                    JsonElement channel = subEmotesObject
                            .getAsJsonObject(entry.getValue().toString().replaceAll("\"", ""));
                    if (channel != null) {
                        for (JsonElement element : channel.getAsJsonObject().getAsJsonArray("emotes")
                                .getAsJsonArray()) {
                            subEmotes.add(element.getAsJsonObject().getAsJsonPrimitive("code").getAsString());
                        }
                    }
                });
    } catch (JsonSyntaxException | IOException e) {
        logger.log(Level.WARNING, "An error occurred updating the emote database!", e);
        WLogger.logError(e);
    } finally {
        try {
            if (stream != null) {
                stream.close();
            }
            if (stream1 != null) {
                stream1.close();
            }
        } catch (IOException e) {
            WLogger.logError(e);
        }
    }
    return subEmotes;
}

From source file:io.github.weebobot.weebobot.external.TwitchUtilities.java

License:Open Source License

private static ArrayList<String> getBTTVEmotes() {
    ArrayList<String> bttvEmotes = new ArrayList<>();
    try (InputStream stream = new URL(BTTV_URL + "emotes").openStream()) {
        JsonArray jsonEmotes = new JsonParser().parse(new JsonReader(new InputStreamReader(stream)))
                .getAsJsonObject().getAsJsonArray("emotes").getAsJsonArray();

        for (JsonElement element : jsonEmotes) {
            bttvEmotes.add(element.getAsJsonObject().getAsJsonPrimitive("regex").getAsString());
        }//from   ww  w  .java 2s  .  c o m
    } catch (JsonSyntaxException | IOException e) {
        logger.log(Level.WARNING, "An error occurred updating the emote database!", e);
        WLogger.logError(e);
    }
    return bttvEmotes;
}

From source file:io.grpc.examples.hedging.HedgingHelloWorldClient.java

License:Apache License

/** Construct client connecting to HelloWorld server at {@code host:port}. */
public HedgingHelloWorldClient(String host, int port, boolean hedging) {
    Map<String, ?> hedgingServiceConfig = new Gson().fromJson(
            new JsonReader(new InputStreamReader(
                    HedgingHelloWorldClient.class.getResourceAsStream("hedging_service_config.json"), UTF_8)),
            Map.class);

    ManagedChannelBuilder<?> channelBuilder = ManagedChannelBuilder.forAddress(host, port)
            // Channels are secure by default (via SSL/TLS). For the example we disable TLS to avoid
            // needing certificates.
            .usePlaintext();//www . j a  va 2 s .c o m
    if (hedging) {
        channelBuilder.defaultServiceConfig(hedgingServiceConfig).enableRetry();
    }
    channel = channelBuilder.build();
    blockingStub = GreeterGrpc.newBlockingStub(channel);
    this.hedging = hedging;
}

From source file:io.grpc.internal.JsonParser.java

License:Apache License

/**
 * Parses a json string, returning either a {@code Map<String, ?>}, {@code List<?>},
 * {@code String}, {@code Double}, {@code Boolean}, or {@code null}.
 *//* w w  w  .j a  v a  2  s.c  o m*/
public static Object parse(String raw) throws IOException {
    JsonReader jr = new JsonReader(new StringReader(raw));
    try {
        return parseRecursive(jr);
    } finally {
        try {
            jr.close();
        } catch (IOException e) {
            logger.log(Level.WARNING, "Failed to close", e);
        }
    }
}

From source file:io.motown.chargingstationconfiguration.viewmodel.restapi.providers.GsonJsonProvider.java

License:Apache License

@Override
public Object readFrom(Class<Object> objectClass, Type type, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> stringStringMultivaluedMap, InputStream inputStream) throws IOException {
    JsonReader reader = new JsonReader(new InputStreamReader(inputStream, Charset.forName(UTF_8)));
    Object obj = gson.fromJson(reader, type);
    reader.close();/* w  w  w  . j  ava 2  s . c o  m*/
    return obj;
}

From source file:io.robusta.rra.representation.implementation.GsonRepresentation.java

License:Apache License

/**
 * contructor//from w w  w . ja  v  a  2s.  c  om
 * 
 * @param inputStream
 */
public GsonRepresentation(InputStream inputStream) {
    this.document = new JsonParser().parse(new JsonReader(new InputStreamReader(inputStream)));
}

From source file:io.soliton.protobuf.json.JsonRpcClientHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpResponse response)
        throws Exception {
    if (!(response instanceof HttpContent)) {
        clientLogger.logServerError(null, null, new Exception("Returned response has no content"));
        logger.severe("Returned response has no content");
        return;// ww  w  .j  a  va  2  s  .c om
    }

    HttpContent content = (HttpContent) response;

    if (!response.headers().get(HttpHeaders.Names.CONTENT_TYPE).equals(JsonRpcProtocol.CONTENT_TYPE)) {
        logger.warning("Incorrect Content-Type: " + response.headers().get(HttpHeaders.Names.CONTENT_TYPE));
    }

    JsonElement root;
    try {
        ByteBufInputStream stream = new ByteBufInputStream(content.content());
        JsonReader reader = new JsonReader(new InputStreamReader(stream, Charsets.UTF_8));
        root = new JsonParser().parse(reader);
    } catch (JsonSyntaxException jsonException) {
        clientLogger.logServerError(null, null, jsonException);
        logger.warning("JSON response cannot be decoded");
        return;
    }
    if (!root.isJsonObject()) {
        logger.warning("JSON response is not a JSON object: " + root.toString());
        return;
    }

    JsonRpcResponse jsonRpcResponse = JsonRpcResponse.fromJson(root.getAsJsonObject());

    JsonElement requestId = jsonRpcResponse.id();
    if (requestId == null || !requestId.isJsonPrimitive()) {
        clientLogger.logServerError(null, null,
                new Exception("Received response identifier is not JSON primitive"));
        logger.warning("Received response identifier is not JSON primitive: " + requestId.toString());
        return;
    }

    JsonResponseFuture<? extends Message> future = inFlightRequests.remove(requestId.getAsLong());
    if (future == null) {
        clientLogger.logServerError(null, null, new Exception("Response received for unknown identifier"));
        logger.severe("Response received for unknown identifier: " + requestId.getAsLong());
        return;
    }

    clientLogger.logSuccess(future.method());
    future.setResponse(jsonRpcResponse);
}