[Resource] IPUtils : Get player's weather, city, local time, and more

Discussion in 'Resources' started by Plo124, May 1, 2014.

Thread Status:
Not open for further replies.
  1. Offline

    Plo124

    Ever wanted to be really creepy to your players and say "Hey Plo457, hows the snow at your place? Oh, and should you be sleeping? Its 2-30 in the morning.". Now you can with these utils.

    Hi guys, I was testing with Java some JSON parsing, then I came up with an idea, get the weather of a player.
    This class file uses a cache for the IP data to avoid too many requests, because the API for that website says to keep traffic to a minumum.

    With this class, you only need to make 0-1 instances of the class, so try not to add this into a class where you frequently call new className(); Also sorry for using static methods.

    I'm planning to add a tornado watch, which will return a boolean if there is a tornado near the target city (from the IP address).

    So here is the main class, and I am developing addons to this main class, using the few methods it contains. Also with the main class, and all the examples, please remove the tags, these are what bukkit adds because it is a link.
    Main class (open)
    Code:java
    1. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.HashMap; import java.util.TimeZone; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; public class IPUtils { static HashMap<String,JSONObject> ipStorage = new HashMap<String,JSONObject>(); public static String ipToTime(String ip){ int offset = 0; if (ipStorage.containsKey(ip)){ offset = Integer.parseInt((String) ipStorage.get(ip).get("timeZone")); } else { String url = "[url]http://api.ipinfodb.com/v3/ip-city/?key=d7859a91e5346872d0378a2674821fbd60bc07ed63684c3286c083198f024138&ip="+ip+"&format=json";
    2. JSONObject object = stringToJSON(getUrlSource(url));
    3. String timezone = (String) object.get("timeZone");
    4. if (timezone != null && timezone.length() > 3){
    5. offset = Integer.parseInt(timezone.substring(0,timezone.length()-3));
    6. ipStorage.put(ip,object);
    7. } else {
    8. return "Error: Cannot parse time";
    9. }
    10. }
    11. Calendar time = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    12. time.add(Calendar.HOUR_OF_DAY,offset);
    13. DateFormat formatter = new SimpleDateFormat("EEEEEE hh:mm");
    14. formatter.setCalendar(time);
    15. String date = formatter.format(time.getTime());
    16. DateFormat formatter2 = new SimpleDateFormat("aa");
    17. formatter2.setCalendar(time);
    18. date += formatter2.format(time.getTime()).toLowerCase();
    19. return date;
    20. }
    21. public static String getCityName(String ip){
    22. JSONObject obj=null;
    23. if (ipStorage.containsKey(ip)){
    24. obj = ipStorage.get(ip);
    25. } else {
    26. String url = "[URL]http://api.ipinfodb.com/v3/ip-city/?key=d7859a91e5346872d0378a2674821fbd60bc07ed63684c3286c083198f024138&ip=[/url]"+ip+"&format=json";
    27. JSONObject object = stringToJSON(getUrlSource(url));
    28. obj = object;
    29. ipStorage.put(ip,object);
    30. }
    31. return (String) obj.get("cityName");
    32. }
    33. public static String getStateName(String ip){
    34. JSONObject obj=null;
    35. if (ipStorage.containsKey(ip)){
    36. obj = ipStorage.get(ip);
    37. } else {
    38. String url = "[url]http://api.ipinfodb.com/v3/ip-city/?key=d7859a91e5346872d0378a2674821fbd60bc07ed63684c3286c083198f024138&ip=[/url]"+ip+"&format=json";
    39. JSONObject object = stringToJSON(getUrlSource(url));
    40. obj = object;
    41. ipStorage.put(ip,object);
    42. }
    43. return (String) obj.get("regionName");
    44. }
    45. public static String getCountryName(String ip){
    46. JSONObject obj=null;
    47. if (ipStorage.containsKey(ip)){
    48. obj = ipStorage.get(ip);
    49. } else {
    50. String url = "[url]http://api.ipinfodb.com/v3/ip-city/?key=d7859a91e5346872d0378a2674821fbd60bc07ed63684c3286c083198f024138&ip=[/url]"+ip+"&format=json";
    51. JSONObject object = stringToJSON(getUrlSource(url));
    52. obj = object;
    53. ipStorage.put(ip,object);
    54. }
    55. String country = (String) obj.get("countryName");
    56. if (country.contains(",")){
    57. country = country.split(",")[0];
    58. }
    59. return country;
    60. }
    61. public static String getCountryCode(String ip){
    62. JSONObject obj=null;
    63. if (ipStorage.containsKey(ip)){
    64. obj = ipStorage.get(ip);
    65. } else {
    66. String url = "[url]http://api.ipinfodb.com/v3/ip-city/?key=d7859a91e5346872d0378a2674821fbd60bc07ed63684c3286c083198f024138&ip=[/url]"+ip+"&format=json";
    67. JSONObject object = stringToJSON(getUrlSource(url));
    68. obj = object;
    69. ipStorage.put(ip,object);
    70. }
    71. String country = (String) obj.get("countryCode");
    72. return country;
    73. }
    74. public static JSONObject stringToJSON(String json){
    75. return (JSONObject) JSONValue.parse(json);
    76. }
    77. private static String getUrlSource(String url){
    78. URL url2 = null;
    79. try {
    80. url2 = new URL(url);
    81. } catch (MalformedURLException e) {
    82. }
    83. URLConnection yc = null;
    84. try {
    85. yc = url2.openConnection();
    86. } catch (IOException e) {
    87. }
    88. BufferedReader in = null;
    89. try {
    90. yc.getInputStream(), "UTF-8"));
    91. } catch (IOException e) {
    92. }
    93. String inputLine;
    94. StringBuilder a = new StringBuilder();
    95. try {
    96. while ((inputLine = in.readLine()) != null)
    97. a.append(inputLine);
    98. } catch (IOException e) {
    99. }
    100. try {
    101. in.close();
    102. } catch (IOException e) {
    103. }
    104.  
    105. return a.toString();
    106. }
    107. }


    Addons:
    To use an Addon simply place the method into the IPUtils class.

    Weather Addon:
    Code:java
    1. public static String getWeather(String ip){
    2. String weather = "Unknown";
    3. String search = getCityName(ip)+","+getCountryCode(ip);
    4. String url = "[url]http://api.openweathermap.org/data/2.5/weather?q=[/url]"+search;
    5. JSONObject object = stringToJSON(getUrlSource(url));
    6. weather = (String)((JSONObject)((JSONArray) object.get("weather")).get(0)).get("main");
    7. return weather;
    8. }



    Because this uses a IP and not a player object (I dont see why you need to use a player object), you can add this in your server list, but I would advise keeping a cache so the ping time isnt really low each time they ping your server.

    Also, credits to openweathermap.org and ipinfodb.com as these are the APIs that I use in this resource/demonstration.
    Thanks for reading this post.
     
    ever_x, macboinc, Skyost and 4 others like this.
  2. Offline

    bobacadodl

    Nice methods :)
    Just a warning though. Since some of these methods work by getting data from an external server, make sure to either cache the result or run it in an async thread!
     
    Plo124 likes this.
  3. Offline

    Plo124

    bobacadodl
    Yes yes yes, use Async methods with most of these methods.
    The IP geolocation data is stored locally because the odds of your IP suddenly being in another city while on a minecraft server is like 1/9999999999^999999999.99. The weather isnt stored because it can change in an area in even a few minutes (even though i heard this weather updates every 3 hours or so)
     
  4. Offline

    BungeeTheCookie

    Teleportation brother.
     
    KingFaris11 likes this.
  5. Offline

    Phasesaber

    What if the player does this?:

    p.teleport(Space);
     
    KingFaris11 likes this.
  6. Offline

    DevRosemberg

    Phasesaber You would get a compilation Error.
     
    bloodless2010, Skyost and KingFaris11 like this.
  7. Offline

    SuperOmegaCow

    Teleportation in real life.. wow. It is getting the weather in the players area.. irl.. not in game.
     
  8. Offline

    CoderRyan

    getURLSource line 118 is not working. idk why :/
     
  9. Offline

    BungeeTheCookie


    Code:
    Location Space = p.getLocation();
     
     
     
     
     
    p.teleport(Space);
     
    KingFaris11 likes this.
  10. Offline

    DevRosemberg

  11. Offline

    Plo124

    Make sure the IP isnt 127.0.0.1 (localhost or your computer) because this wont work.
     
  12. Offline

    CoderRyan

    Alright thanks dude ahaha Can i add you on skype?? If so add coderryanmc :) Thanks :)
     
  13. Offline

    NerdsWBNerds


    I really want to do this XD
     
    KingFaris11 likes this.
  14. Offline

    ChipDev

    Chip joined the server.
    Chip! Glad your here. get out of the house!
    Chip:Umm.. why?
    Theres a tornado.. like 5 feet away from your computer.
    Chip:Wut?
    Look out your window.
    Chip: eh..
     
    KingFaris11 likes this.
  15. Offline

    BlueMustache

    Plo124
    Surprisingly this could save many lives.

    SCENARIO:
    A boy is online playing minecraft on his friends server, using a plugin which uses this resource.
    His parents are asleep.
    Every once in a while, the server checks the boys location for weather anomalies.
    The server then detects a tornado heading their way, which the boy and the parents would not have known.
    The server then plays an obnoxious sound, and displays a message saying, "WARNING: There has been a tornado detected near by your house. Go check the Television!"
    The boy then realizes that the server was right, alerts his parents, and they all go down in the basement and live.
    END SCENARIO. :'(

    I know that is a little far fetched, but it could happen!
    Do I hear a, "Yes, add Tornado Support!"?
    -Blue

    "Now just this time, everybody lives!" - Christopher Eccleston, 9th Doctor

    ChipDev

    Lol, I didn't even see your post, before I typed this.
    Great minds think a like guess!

    OFFTOPIC: When I program, I often have to correct myself, because I end up typing "flase" instead of "false", does anyone else do that?

    P.S. How are you buffering the requests to the api?
    I am really interested to know.

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 7, 2016
    KingFaris11 likes this.
  16. Offline

    ChipDev

     
  17. Offline

    Plo124

    BlueMustache
    I have looked on many websites for an API to retrieve tornadoes in an area,
    If you have found a website for this, I will happily play around and add it to this thread.
     
  18. Offline

    BlueMustache

    Plo124
    Same here. No free ones.
    Also, there was a tornado warning in my area last night. XD
    I saw lightning striking other clouds, it was pretty cool.

    News.
     
  19. Offline

    ChipDev

    Does anyone think that this is kinda totally on-topic? :rolleyes:
     
  20. Offline

    BlueMustache


    Lol, totally.
     
  21. Offline

    Plo124

    BlueMustache
    Lightning can be awesome, there is a place in the world (not sure) where there is a storm constantly, and there is just continuous lightning.

    This isnt bad, it makes up for a lot of the Earth's Ozone layer, helping to repair the hole in the ozone layer caused by CFC's

    So ontopic ^.^
     
    KingFaris11 and ChipDev like this.
  22. Offline

    SacredWaste

    So... A never ending lightning storm is the solution to a lot of problems.
     
  23. Offline

    Plo124

    SacredWaste
    Why wouldn't it be?
    Appart from Lightning creating Antimatter, its pretty fine to me,
    Even then, Antimatter is just converting Matter into Energy, and is reversable, with no loss.
     
  24. Offline

    SuperOmegaCow

    Plo124
    So many lies... Lightning creates nitrogen... Which is bad. Also, lightning creating antimatter doesn't benefit us in anyway other than for scientifically research. And how the fuck is antimatter, just matter converted to energy... Not to mention we know nothing about it and have no way of reversing it since we know NOTHING about it...
     
  25. Offline

    BlueMustache

  26. Offline

    macboinc

    Sounds interesting!
     
  27. Offline

    BlueMustache


    The only on topic post. :p
     
  28. Offline

    macboinc

    LOL, I like toast. It makes my mouth feel nice.[cake]
     
  29. Offline

    ChipDev

    Much on topic. going to get that for an UBER amount of cash!
     
  30. Offline

    Plo124

    My power bill will go up a lot, I don't think this is a good idea.

    Before TV, telephones and the things that came after that existed, a Tornado would kill many people because no-one would be prepared.
    Next came those technologies, and people watching TV could get alerts, but...
    NOW I'm creating a new era of technology where you get in-game updates about weather and natural distasters.

    Vote for Plo457 in the next elections! xD

    EDIT by Moderator: merged posts, please use the edit button instead of double posting.
     
    Last edited by a moderator: Jun 7, 2016
Thread Status:
Not open for further replies.

Share This Page