timbru31/spigot-anti-piracy-backend

Provide basic Java example

MaTaMoR opened this issue · 5 comments

Hi, first thanks for your hard work providing this system to prevent leaks. I have tried to use this but i can't manage to think how i'm supposed to do the request using a plugin.

The provided java implementation is this one:
String rawData = "user_id="; String userId = someObject().getUserID(); String encodedData = null; try { encodedData = rawData + URLEncoder.encode(userId, "UTF-8"); } catch (UnsupportedEncodingException e) { // catch error or not. up to you return; }

But what i do with that, how do i do the request now ? Would be really uselful if you could provide me with a full example of it.

You need basic knowledge about Java and HTTP(S) requests. E.g.
http://stackoverflow.com/a/1359700/1902598

The response comes back in JSON, so you need to parse that. E.g.
http://stackoverflow.com/a/18998203/1902598

I'll try to make a small Java example, though!

Yeah i have basic knowledge of HTML, i have done similar stuff for mojang API requests, what i can't understand is, once i have the enconded data how the request is done, what link i have to use, my IP and what else ?

{ip}:encondedData ? That's what i don't know, a java example would help a lot.

what link i have to use, my IP and what else ?

You need to host your own instance of this project - so I can't tell you the IP or URL you need to make the request to.

Yeah i understand that, i installed the programm as the instruction says and i think it's working, let's say my server IP is 0.0.0.0, then how i would make the request with that IP ?

I'll add something like this later today to the repo:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.net.UnknownHostException;

public class Snippet {
    private static final int TIMEOUT = 5000;
    private static final int SERVER_ERROR = 500;
    private Plugin plugin;

    public Snippet(Plugin plugin) {
        this.plugin = plugin;
    }

    public int sendPost(String userId) throws HTTPTokenException {
        return sendPost(userId, "https://your-url/", true);
    }

    // HTTP POST request
    public int sendPost(String userId, String apiHost, boolean useSSL) throws CustomException {
        // URL
        URL url = null;
        try {
            url = new URL(apiHost);
        } catch (MalformedURLException e) {
            return -1;
        }

        // HTTPS Connection
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = null;
        try {
            con = (HttpURLConnection) url.openConnection();
        } catch (IOException e) {
            // handle error case, e.g. throw a custom error
            return -1;
        }

        // Get user id
        String rawData = "user_id=";
        String encodedData = null;
        try {
            encodedData = rawData + URLEncoder.encode(userId, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // handle error case, e.g. throw a custom error
            return -1;
        }

        // Make POST request
        try {
            con.setRequestMethod("POST");
        } catch (ProtocolException e) {
            // handle error case, e.g. throw a custom error
            return -1;
        }
        con.setRequestProperty("Content-Length", String.valueOf(encodedData.length()));
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        con.setRequestProperty("Bukkit-Server-Port", String.valueOf(plugin.getServer().getPort()));
        con.setConnectTimeout(TIMEOUT);
        con.setReadTimeout(TIMEOUT);
        // Send POST request
        con.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.write(encodedData.getBytes("UTF-8"));
            wr.flush();
            wr.close();
        } catch (UnknownHostException e) {
            // Handle being offline nice
            return -1;
        } catch (IOException e) {
            if (useSSL) {
                return sendPost(userId, "http://your-url", false);
            }
            // handle error case, e.g. throw a custom error
            return -1;
        }

        // Get response
        int responseCode = 0;
        try {
            responseCode = con.getResponseCode();
        } catch (IOException e) {
            // Handle case when server is down gracefully.
            return responseCode;
        }

        String inputLine;
        StringBuffer response = new StringBuffer();
        // Ignore all server errors
        if (responseCode >= SERVER_ERROR) {
            return responseCode;
        } else if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"))) {
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            } catch (IOException e) {
                // handle error case, e.g. throw a custom error
                return responseCode;
            }
        } else {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"))) {
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
            } catch (IOException e) {
                // handle error case, e.g. throw a custom error
                return responseCode;
            }
        }
        JSONObject responseJSON;
        try {
            responseJSON = new JSONObject(response.toString());
        } catch (JSONException e) {
            // handle error case, e.g. throw a custom error
            return responseCode;
        }
        boolean blacklisted = responseJSON.getBoolean("blacklisted");
        // handle blacklisted case, e.g. throw a custom error
        return responseJSON;
    }
}