Giter Club home page Giter Club logo

java-mojang-api's Introduction

Java Mojang API

This repository provides a full Java-wrapper for the Mojang Web-API.
More information on the API may be found on the Wiki page.

Getting Started

  • Clone the repository and compile it with Maven and add it to your build path.
$    git clone https://github.com/SparklingComet/java-mojang-api.git
$    mvn clean install
  • Alternatively, you can use Maven to include the dependency in your project:
<project>
    <!-- Your stuff here... -->
    <repositories>
        <!-- More repositories... -->
	<repository>
	    <id>jitpack.io</id>
	    <url>https://jitpack.io</url>
	</repository>
    </repositories>
	
    <dependencies>
	<!-- More dependencies... -->
	<dependency>
    	    <groupId>com.github.SparklingComet</groupId>
    	    <artifactId>java-mojang-api</artifactId>
    	    <version>-SNAPSHOT</version>
    	</dependency>
    </dependencies>
</project>
  • You can also use Gradle as a dependency manager:
allprojects {
    repositories {
	...
	maven { url 'https://jitpack.io' }
    }
}
	
dependencies {
    compile 'com.github.SparklingComet:java-mojang-api:-SNAPSHOT'
}
  • More information on using dependency managers with this repository may be found on Jitpack.
  • Precompiled binaries will be made available on our CI server soon.

Usage

Once you have imported the library, use the following to establish a connection with Mojang's servers.

Mojang api = new Mojang().connect();

Documentation

  • Generated HTML-Javadoc files are available for download in HTML-format in the docs/ directory.
  • You may also use the live version (click)

License

The project is licensed under the Apache License v2.0 (view).

To license your own project with it, add the file its root and prefix your source files with

/*
 *     Copyright 2016-2017 SparklingComet @ http://shanerx.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

java-mojang-api's People

Contributors

ineanto avatar justbru00 avatar piegamesde avatar sparklingcomet avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

java-mojang-api's Issues

Error resolving status.mojang.com

This appears to be caused by Mojang shutting down the status service.
https://wiki.vg/Mojang_API#API_Status_-_Outdated

I will try and write a PR that removes the status API.

Full stack trace:

java.lang.RuntimeException: com.mashape.unirest.http.exceptions.UnirestException: java.net.UnknownHostException: status.mojang.com: No address associated with hostname
        at org.shanerx.mojang.Mojang.getJSONArray(Mojang.java:406) ~[survivalserver-1.3.1.jar:?]
        at org.shanerx.mojang.Mojang.connect(Mojang.java:70) ~[survivalserver-1.3.1.jar:?]
        at net.introvertscove.survivalserver.plugin.utils.UUIDFetcher.init(UUIDFetcher.java:21) ~[survivalserver-1.3.1.jar:?]
        at net.introvertscove.survivalserver.plugin.utils.UUIDFetcher.getLastName(UUIDFetcher.java:164) ~[survivalserver-1.3.1.jar:?]
        at net.introvertscove.survivalserver.plugin.utils.UUIDFetcher$3.run(UUIDFetcher.java:127) ~[survivalserver-1.3.1.jar:?]
        at org.bukkit.craftbukkit.v1_17_R1.scheduler.CraftTask.run(CraftTask.java:101) ~[patched_1.17.1.jar:git-Paper-327]
        at org.bukkit.craftbukkit.v1_17_R1.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:57) ~[patched_1.17.1.jar:git-Paper-327]
        at com.destroystokyo.paper.ServerSchedulerReportingWrapper.run(ServerSchedulerReportingWrapper.java:22) ~[patched_1.17.1.jar:git-Paper-327]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630) ~[?:?]
        at java.lang.Thread.run(Thread.java:831) ~[?:?]
Caused by: com.mashape.unirest.http.exceptions.UnirestException: java.net.UnknownHostException: status.mojang.com: No address associated with hostname
        at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:143) ~[survivalserver-1.3.1.jar:?]
        at com.mashape.unirest.request.BaseRequest.asString(BaseRequest.java:56) ~[survivalserver-1.3.1.jar:?]
        at org.shanerx.mojang.Mojang.getJSONArray(Mojang.java:401) ~[survivalserver-1.3.1.jar:?]
        ... 10 more
Caused by: java.net.UnknownHostException: status.mojang.com: No address associated with hostname
        at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method) ~[?:?]
        at java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:932) ~[?:?]
        at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1517) ~[?:?]
        at java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:851) ~[?:?]
        at java.net.InetAddress.getAllByName0(InetAddress.java:1507) ~[?:?]
        at java.net.InetAddress.getAllByName(InetAddress.java:1366) ~[?:?]
        at java.net.InetAddress.getAllByName(InetAddress.java:1300) ~[?:?]
        at org.apache.http.impl.conn.SystemDefaultDnsResolver.resolve(SystemDefaultDnsResolver.java:45) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:111) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107) ~[survivalserver-1.3.1.jar:?]
        at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) ~[survivalserver-1.3.1.jar:?]
        at com.mashape.unirest.http.HttpClientHelper.request(HttpClientHelper.java:138) ~[survivalserver-1.3.1.jar:?]
        at com.mashape.unirest.request.BaseRequest.asString(BaseRequest.java:56) ~[survivalserver-1.3.1.jar:?]
        at org.shanerx.mojang.Mojang.getJSONArray(Mojang.java:401) ~[survivalserver-1.3.1.jar:?]
        ... 10 more

Eclipse Error

Hello!
I get the following error if I use the java-mojang-api in eclipse oxygen.
I imported the project via "Git Repositories". Is there a bug in the API or do I make something wrong?

Exception in thread "main" java.lang.NullPointerException
at org.shanerx.mojang.Mojang.connect(Mojang.java:62)
at bot.HalloWelt.main(HalloWelt.java:10)
`package bot;

import org.shanerx.mojang.Mojang;

public class HalloWelt
{
public static void main (String args[])
{
System.out.println("Start");
Mojang api = new Mojang().connect();
}
}`

Screenshot of eclipse http://prntscr.com/ja3jlb
I would be very grateful if someone could help me.

README.md typo

It looks like in the usage example of the README.md file a bracket is missing after Mojang.ServiceType.AUTH_MOJANG_COM:

if (api.getStatus(Mojang.ServiceType.AUTH_MOJANG_COM != Mojang.ServiceStatus.GREEN) {
	System.err.println("The Auth Server is not available right now.");
}

Error on Mojang#connect()

Upon trying to connect via Mojang#connect() I get a NullPointerException. I tracked this down to Mojang#connect() expecting https://status.mojang.com/check to return a Json OBJECT while it gives an array with the rough format

[
   {
     "service": "status"
   },
   {
     "service2": "status"
   }
]

Help! java.lang.NoClassDefFoundError from java.lang.ClassNotFoundException

I'm trying to use this in a Spigot plugin but at runtime, it fails with java.lang.NoClassDefFoundError: org/shanerx/mojang/Mojang from Caused by: java.lang.ClassNotFoundException: org.shanerx.mojang.Mojang. I'm not super familiar with all this but I think this is an issue with Maven not bundling the Mojang class? There are no errors or problems in my IDE (VS Code). The file (from mvn -s settings.xml install -f pom.xml) is zipped below.

eyeofonyx-1.0.0.jar.zip

Here is the error when run:

java.lang.NoClassDefFoundError: org/shanerx/mojang/Mojang
        at io.github.stonley890.commands.CmdRoyalty.<init>(CmdRoyalty.java:25) ~[eyeofonyx-1.0.0.jar:?]
        at io.github.stonley890.Main.onEnable(Main.java:38) ~[eyeofonyx-1.0.0.jar:?]
        at org.bukkit.plugin.java.JavaPlugin.setEnabled(JavaPlugin.java:279) ~[paper-api-1.19.4-R0.1-SNAPSHOT.jar:?]
        at io.papermc.paper.plugin.manager.PaperPluginInstanceManager.enablePlugin(PaperPluginInstanceManager.java:189) ~[paper-1.19.4.jar:git-Paper-524]
        at io.papermc.paper.plugin.manager.PaperPluginManagerImpl.enablePlugin(PaperPluginManagerImpl.java:104) ~[paper-1.19.4.jar:git-Paper-524]
        at org.bukkit.plugin.SimplePluginManager.enablePlugin(SimplePluginManager.java:507) ~[paper-api-1.19.4-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.craftbukkit.v1_19_R3.CraftServer.enablePlugin(CraftServer.java:555) ~[paper-1.19.4.jar:git-Paper-524]
        at org.bukkit.craftbukkit.v1_19_R3.CraftServer.enablePlugins(CraftServer.java:466) ~[paper-1.19.4.jar:git-Paper-524]
        at net.minecraft.server.MinecraftServer.loadWorld0(MinecraftServer.java:638) ~[paper-1.19.4.jar:git-Paper-524]
        at net.minecraft.server.MinecraftServer.loadLevel(MinecraftServer.java:437) ~[paper-1.19.4.jar:git-Paper-524]
        at net.minecraft.server.dedicated.DedicatedServer.initServer(DedicatedServer.java:308) ~[paper-1.19.4.jar:git-Paper-524]
        at net.minecraft.server.MinecraftServer.runServer(MinecraftServer.java:1104) ~[paper-1.19.4.jar:git-Paper-524]
        at net.minecraft.server.MinecraftServer.lambda$spin$0(MinecraftServer.java:320) ~[paper-1.19.4.jar:git-Paper-524]
        at java.lang.Thread.run(Thread.java:833) ~[?:?]
Caused by: java.lang.ClassNotFoundException: org.shanerx.mojang.Mojang
        at org.bukkit.plugin.java.PluginClassLoader.loadClass0(PluginClassLoader.java:183) ~[paper-api-1.19.4-R0.1-SNAPSHOT.jar:?]
        at org.bukkit.plugin.java.PluginClassLoader.loadClass(PluginClassLoader.java:150) ~[paper-api-1.19.4-R0.1-SNAPSHOT.jar:?]
        at java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[?:?]
        ... 14 more

Here is my pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>io.github.stonley890</groupId>
  <artifactId>eyeofonyx</artifactId>
  <version>1.0.0</version>
  <packaging>jar</packaging>

  <name>Eye of Onyx</name>
  <url>http://www.github.com/Stonley890/Eye-Of-Onyx</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>17</maven.compiler.source>
    <maven.compiler.target>17</maven.compiler.target>
  </properties>

  <repositories>
    <repository>
      <id>spigot-repo</id>
      <url>https://hub.spigotmc.org/nexus/content/repositories/snapshots/</url>
    </repository>
    <repository>
      <id>jitpack.io</id>
      <url>https://jitpack.io</url>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>org.spigotmc</groupId>
      <artifactId>spigot-api</artifactId>
      <version>1.19.4-R0.1-SNAPSHOT</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>com.github.SparklingComet</groupId>
      <artifactId>java-mojang-api</artifactId>
      <version>-SNAPSHOT</version>
    </dependency>
  </dependencies>

  <build>
    <defaultGoal>clean package</defaultGoal>
    <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
    <resources>
      <resource>
        <directory>src/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <pluginManagement>
      <plugins>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-shade-plugin</artifactId>
          <version>3.4.1</version>
          <executions>
            <execution>
              <phase>package</phase>
              <goals>
                <goal>shade</goal>
              </goals>
              <configuration>
                <createDependencyReducedPom>false</createDependencyReducedPom>
                <finalName>Eye Of Onyx</finalName>
                <outputFile>${project.basedir}/target</outputFile>
              </configuration>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

</project>

Main.java

package io.github.stonley890;

import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;

import io.github.stonley890.commands.CmdEyeOfOnyx;
import io.github.stonley890.commands.CmdRoyalty;
import io.github.stonley890.files.RoyaltyBoard;
import io.github.stonley890.listeners.ListenJoin;

/*
 * The main ticking thread.
*/

public class Main extends JavaPlugin {

    private static Main plugin;

    public static String version;

    @Override
    public void onEnable() {
        // Register variables
        plugin = this;
        version = getDescription().getVersion();

        // Create config if needed
        getConfig().options().copyDefaults();
        saveDefaultConfig();

        // Set up royalty board file
        RoyaltyBoard.setup();
        // RoyaltyBoard.get().options().copyDefaults();
        RoyaltyBoard.save();

        // Initialize command executors
        getCommand("eyeofonyx").setExecutor(new CmdEyeOfOnyx());
        getCommand("royalty").setExecutor(new CmdRoyalty());

        // Initialize listeners
        getServer().getPluginManager().registerEvents(new ListenJoin(), plugin);

        // Start message
        Bukkit.getLogger().info(
                "Eye of Onyx " + version + ": A plugin that manages the royalty board on Wings of Fire: The New World");
    }

    // Allow other classes to access plugin instance
    public static Main getPlugin() {
        return plugin;
    }
}

And here is commands/CmdRoyalty.java

package io.github.stonley890.commands;

import java.util.Arrays;
import java.util.UUID;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.scoreboard.Scoreboard;
import org.shanerx.mojang.Mojang;

import io.github.stonley890.Main;
import io.github.stonley890.files.RoyaltyBoard;
import net.md_5.bungee.api.ChatColor;

public class CmdRoyalty implements CommandExecutor {

    // Get plugin instance (main thread)
    Plugin plugin = Main.getPlugin();
    // Get Mojang services
    Mojang mojang = new Mojang().connect();
    // Get server scoreboard service (for teams)
    Scoreboard scoreboard = Bukkit.getScoreboardManager().getMainScoreboard();
    // Easy access royalty board
    FileConfiguration board = RoyaltyBoard.get();
    // Team names
    String[] teamNames = {
            "HiveWing", "IceWing", "LeafWing", "MudWing", "NightWing", "RainWing", "SandWing", "SeaWing", "SilkWing",
            "SkyWing"
    };
    // Tribe IDs
    String[] tribes = {
        "hive", "ice", "leaf", "mud", "night", "rain", "sand", "sea", "silk", "sky"
    };
    // Valid positions
    String validPositions[] = {
        "ruler", "heir_apparent", "heir_presumptive", "noble_apparent", "noble_presumptive"
    };

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

        // Fail if not enough arguements
        if (args.length < 1) {
            return false;
        } // If arg[0] is "set"
        else if (args[0].equalsIgnoreCase("set") && args.length > 2) {

            // Try to get online Player, otherwise lookup OfflinePlayer
            Player targetPlayer;
            if (Bukkit.getPlayerExact(args[1]) == null) {
                targetPlayer = (Player) Bukkit.getOfflinePlayer(UUID.fromString(mojang.getUUIDOfUsername(args[1])));
            } else {
                targetPlayer = Bukkit.getPlayerExact(args[1]);
            }

            // Get tribe from scoreboard team
            String playerTribe = null;
            try {

                // Get team of player by iterating through list
                for (int i = 0; i < teamNames.length; i++) {
                    if (scoreboard.getTeam(teamNames[i]).hasEntry(targetPlayer.getName()))
                        playerTribe = tribes[i];
                }

                // If target has no associated tribe team, fail
                if (playerTribe == null) {
                    sender.sendMessage(ChatColor.RED + "Target does not have a tribe tag!");
                    return false;
                }

                // Check if third arguement contains a valid position
                if (Arrays.stream(validPositions).anyMatch(args[2]::contains)) {

                    // Set value in board.yml
                    board.set(playerTribe + "." + args[2] + ".uuid", targetPlayer.getUniqueId());
                    RoyaltyBoard.save();
                    sender.sendMessage(ChatColor.YELLOW + "" + targetPlayer.getName() + " is now " + args[2]);

                } else {
                    sender.sendMessage(
                            ChatColor.RED + "Invalid position. Valid positions: " + Arrays.toString(validPositions));
                }
            } catch (IllegalArgumentException e) {
                // getTeam() throws IllegalArgumentException if teams do not exist
                sender.sendMessage(ChatColor.RED + "Required teams do not exist!");
            }

        } else if (args[0].equalsIgnoreCase("list")) {
            if (args[1] == null) {
                StringBuilder strBuild = new StringBuilder();

                for (int i = 0; i < teamNames.length; i++) {
                    strBuild.append("\n" + ChatColor.GOLD + teamNames[i] + "---" + ChatColor.RESET + "\n[ RULER: " + mojang.getPlayerProfile((String) board.get(tribes[i] + ".ruler.uuid")).getUsername()
                    + "\n[ HEIR APPARENT: " + mojang.getPlayerProfile((String) board.get(tribes[i] + ".heir_apparent.uuid")).getUsername()
                    + "\n[ HEIR PRESUMPTIVE: " + mojang.getPlayerProfile((String) board.get(tribes[i] + ".heir_presumptive.uuid")).getUsername()
                    + "\n[ NOBLE APPARENT: " + mojang.getPlayerProfile((String) board.get(tribes[i] + ".noble_apparent.uuid")).getUsername()
                    + "\n[ NOBLE PRESUMPTIVE: " + mojang.getPlayerProfile((String) board.get(tribes[i] + ".noble_presumptive.uuid")).getUsername());
                }

                sender.sendMessage(ChatColor.YELLOW + "ROYALTY BOARD" + strBuild.toString());
            }
        }

        RoyaltyBoard.save();
        return true;
    }
}

Casting error when getting UUID from username

I am getting the following error when I try to use the getUUIDOfUsername() method
Caused by: java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

Why do I need the connect method?

Why do I need to use the connect method?

What is the difference between:

Mojang mojang = new Mojang().connect();

and:

Mojang mojang = new Mojang();

The connect method documentation says Should <strong>always</strong> be called after creating the API object., but why?

the method connect does not affect other methods, such as getUUIDOfUsername

Then what is the need for it?

The thing is, right now https://status.mojang.com/check doesn't work
can i refuse to call the connect method? what are the consequences? at first glance everything seems to work fine
image

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.