-1

Here is code of my getStream method:

public static Twitch_Stream getStream(String channelname) {
        try {
            String json = API.readJsonFromUrl("https://api.twitch.tv/kraken/streams?channel=" + channelname);

            Twitch_Stream stream = new Twitch_Stream();
            if (json.equalsIgnoreCase("[]")) {
                stream.setOnline(false);
                return stream;
            }

            JsonArray jb = gson.fromJson(json, JsonArray.class);
            if (jb.size() != 0) {
                JsonObject jo = (JsonObject) jb.get(0);
                stream.setOnline(true);
                stream.load(jo);
            }

            return stream;
        } catch (Exception error) {
            error.printStackTrace();
        }

        return null;

    }

and here is code of Twitch_Stream class http://pastebin.com/3RX1L1cv

When I make something like this

Twitch_Stream streamer = Twitch_API.getStream("Jankos");
Bukkit.broadcastMessage("getName " + streamer.getName());
Bukkit.broadcastMessage(streamer.isOnline() + "");

streamer.getName() return null and streamer.isOnline() returns false, even when stream is on.

Where did I make a mistake?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
dekros
  • 59
  • 1
  • 8
  • 2
    Post your code in question. If it is too long to post here it means you didn't reduce your example only to parts needed by this question. – Pshemo Jul 12 '15 at 16:48
  • cannot open this link and check;/? – dekros Jul 12 '15 at 17:41
  • Purpose of Stack Overflow is not only to help you, but to help others with similar problems. If your links will break then your question will be useless for others. – Pshemo Jul 12 '15 at 17:55

1 Answers1

3

I don't know what problem is in your code but simple workaround would be reading content from "https://api.twitch.tv/kraken/streams/" + channel which is JSON in format:

{
    "_links" : {
       //links to stream and channel
    },
    "stream" : {
       //details about current stream
    }
}

Now if value of stream key is null stream is off-line. If it is not null, it is on-line.

So your code can look like

public static void main(String[] argv) throws IOException {

    System.out.println(checkIfOnline("Jankos"));
    System.out.println(checkIfOnline("nightblue3"));

}

public static boolean checkIfOnline(String channel) throws IOException {
    String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel;

    String jsonText = readFromUrl(channerUrl);// reads text from URL
    JSONObject json = new JSONObject(jsonText);

    return !json.isNull("stream");
}

private static String readFromUrl(String url) throws IOException {
    URL page = new URL(url);
    try (Stream<String> stream = new BufferedReader(new InputStreamReader(
            page.openStream(), StandardCharsets.UTF_8)).lines()) {
        return stream.collect(Collectors.joining(System.lineSeparator()));
    }
}

I used JSONObject from org.json library. I am also using Java 8 and its streams.

If you want to use gson you can use instead something like

public static boolean checkIfOnline(String channel) throws IOException {
    String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel;

    String jsonText = readFromUrl(channerUrl);// reads text from URL

    JsonParser parser = new JsonParser();
    JsonObject json = parser.parse(jsonText).getAsJsonObject();

    return !json.get("stream").isJsonNull();
}

If you don't have Java 8 you can rewrite code reading text from URL to something like

private static String readFromUrl(String url) throws IOException {
    URL page = new URL(url);
    StringBuilder sb = new StringBuilder();
    Scanner scanner = null;
    try{
        scanner = new Scanner(page.openStream(), StandardCharsets.UTF_8.name());
        while (scanner.hasNextLine()){
            sb.append(scanner.nextLine());
        }
    }finally{
        if (scanner!=null)
            scanner.close();
    }
    return sb.toString();
}

or from what I see you can use your API.readJsonFromUrl instead of readFromUrl.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • It is feature added in Java 8. You can find more info here https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html and https://docs.oracle.com/javase/tutorial/collections/streams/index.html. In short it is pipeline of operations you want to do on some elements. – Pshemo Jul 12 '15 at 20:27
  • I don't know. Are you using Java 8? – Pshemo Jul 12 '15 at 20:38
  • @dekros If you are using Eclipse or any other IDE it should be able to add this imports for you. Anyway these classes belong to `java.util.stream` package so use `import java.util.stream.Collectors;` and `import java.util.stream.Stream;` – Pshemo Jul 12 '15 at 21:01
  • i have this error http://scr.hu/1det/03o29 i use NetBeans and i have java Version 8 update 45 (build 1.8.0_45-b15) – dekros Jul 12 '15 at 21:10
  • I can't reproduce this problem. Is your project configured to work with Java 8 compiler and libraries? Can you check values of your project in `properties -> sources -> Source/Binary format` and `properties -> libraries -> java platform`? – Pshemo Jul 12 '15 at 21:29
  • @dekros Yes. This shows that your NetBeans is using Java 7 JDK. To use streams you need to install Java 8 JDK. You will also need to update your NetBeans to version 8. – Pshemo Jul 13 '15 at 10:22
  • ok im make this and checking online stream is work but when i want check status like this public static String checkStatus(String channel) throws IOException { String channerUrl = "https://api.twitch.tv/kraken/streams/" + channel; String jsonText = readFromUrl(channerUrl); JsonParser parser = new JsonParser(); JsonObject json = parser.parse(jsonText).getAsJsonObject(); return json.get("status").getAsString(); } i have this error Exception in thread "main" java.lang.NullPointerException in line return json.get("status").getAsString(); – dekros Jul 13 '15 at 11:26
  • That is because as I said, if stream is off-line value of status is `null` and you can't invoke `getAsString` on `null`. – Pshemo Jul 13 '15 at 11:35
  • yes but stream is online link to this stream: https://api.twitch.tv/kraken/streams/disstream and i want get maybe status – dekros Jul 13 '15 at 11:36
  • There is no `status` key in this JSON, but `stream` key. To make your work with JSON easier you need to format it properly. You can do it on-line using http://jsonformatter.curiousconcept.com/. Also `stream` will contain JSON object, not String, so `getAsString` will not work. If you want to have string representation of that JSON object use `toString`, but if you want to do some additional processing you can simply use `json.getAsJsonObject("stream")`. – Pshemo Jul 13 '15 at 11:53
  • ok but when i change method to JsonObject and i make this: return json.getAsJsonObject("mature"); method return me null but method should return false ;/ – dekros Jul 13 '15 at 12:38
  • `json` doesn't have `mature` element. Such element is part of object labelled as `channel` which is part of element labelled as `stream` (as long as this object is not null, when stream is off-line). So you need to select `stream` object, check if it is not null, then from it `channel`, and finally read value of `mature`. – Pshemo Jul 13 '15 at 12:48
  • can you give example for this? is my first time with json;// – dekros Jul 13 '15 at 12:50
  • It is same as parsing XML or HTML, or any parent-children structure (where children can have their own children). You need to select outer element to get inner element. If you have `parentJsonObject` and you want to get its child JsonObject call `JsonObject child = parentJsonObject.getAsJsonObject("labelOfChildObject")`. In your case parent is `json` object and child will be `stream`. When you get that child and you will make sure that it is not null pick child object of `stream` with label `channel`. – Pshemo Jul 13 '15 at 13:00
  • somethink like this? JsonObject json = parser.parse(jsonText).getAsJsonObject(); JsonObject child = json.getAsJsonObject("stream"); if(child.isJsonNull()){ return null; } but how to now return something? return child.get("display_name").toString();? im only coding in c++ and java but i beginner in programing – dekros Jul 13 '15 at 13:17
  • `display_name` doesn't hold object value. In JSON object is thing inside `{}`, array is represented by contend surrounded by `[` `]`. If value is simple string like `"label": "value"` then you can use `getAsJsonObject` but you need `get(label)`. BTW you should probably read some tutorial about parsing JSON using `gson` library since I can't explain you everything. – Pshemo Jul 13 '15 at 13:44
  • ok sory for spaming etc but is my first time with this. but i must make this;/ can you give me code to get displayName? when i try child.get/child.getAs etc i have errors or return me null;/ – dekros Jul 13 '15 at 14:03
  • Your `child` seems to hold object from `stream` label. But `display_name` is part of object from `channel` label, which is part of `stream` object. So you need to get `channel` object and get `display_name` String placed directly in it. So try with `child.getAsJsonObject("channel").get("display_name").getAsString()`. – Pshemo Jul 13 '15 at 14:18
  • You are welcome :) (and based on twitch channels you observe - nie ma sprawy :) – Pshemo Jul 13 '15 at 21:37