All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.automately.java.Automately Maven / Gradle / Ivy

The newest version!
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package com.github.automately.java;

import com.github.automately.java.data.Job;
import com.github.automately.java.data.VirtualFile;
import io.jsync.json.DecodeException;
import io.jsync.json.JsonArray;
import io.jsync.json.JsonObject;
import io.jsync.json.impl.Base64;
import io.jsync.utils.URIUtils;
import okhttp3.*;
import okio.BufferedSink;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * The Automately static class provides a simple interface to interact with the Automately API and MessageBus.
 */
public class Automately {

    // TODO implement better errors
    public static String DEFAULT_API_ENDPOINT = "https://api.automate.ly";

    private static String API_ENDPOINT = DEFAULT_API_ENDPOINT;

    private static String API_USERNAME = "";
    private static String API_KEY = "";

    protected static OkHttpClient httpClient = new OkHttpClient();

    protected static void checkAuthorized(String response){
        checkAuthorized(response, false);
    }

    protected static void checkAuthorized(String response, boolean ignoreDecode) {
        try {
            try {
                JsonObject nResponse = new JsonObject(response.trim());
                if (nResponse.containsField("message") &&
                        nResponse.getString("message", "").equals("Unauthorized") &&
                        nResponse.containsField("description")) {
                    throw new RuntimeException("Unauthorized: " + nResponse.getString("description"));
                }
            } catch (DecodeException ignored){
                // Any unauthorized response will never return an array
                new JsonArray(response.trim());
            }
        } catch (DecodeException ignored) {
            if(!ignoreDecode){
                throw new RuntimeException("Authorization Error: invalid response.");
            }
        }
    }

    protected static void getFormattedError(String errorCode, String message) {
        throw new RuntimeException(errorCode + ": " + message);
    }

    /**
     * This will return the HTTP REST API endpoint that the
     * Automately library will use.
     *
     * @return the REST API Endpoint
     */
    public static String getApiEndpoint() {
        return API_ENDPOINT;
    }

    /**
     * This is used to set the HTTP REST API endpoint that the
     * Automately library will use.
     *
     * @param endpoint the api endpoint the library is using
     */
    public static void setApiEndpoint(String endpoint) {
        while (endpoint.endsWith("/")) {
            endpoint = (String) endpoint.subSequence(0, endpoint.length() - 1);
        }
        API_ENDPOINT = endpoint;
    }

    /**
     * This returns the username that you have specified for the
     * Automately library to use.
     *
     * @return the username the library is using
     */
    public static String getApiUsername() {
        return API_USERNAME;
    }

    /**
     * This will set the username that the Automately library will
     * use.
     *
     * @param username the username you wish to use
     */
    public static void setApiUsername(String username) {
        API_USERNAME = username;
    }

    /**
     * This will return the API key that the Automately
     * library will use.
     *
     * @return the api key the library is using
     */
    public static String getApiKey() {
        return API_KEY;
    }

    /**
     * This will set the apiKey that the Automately library will
     * use.
     *
     * @param apiKey the apiKey you wish to use
     */
    public static void setApiKey(String apiKey) {
        API_KEY = apiKey;
    }

    /**
     * This method will return a JsonObject with some basic
     * user information from the cluster such as your private
     * api key and your public api key.
     *
     * @return
     */
    public static JsonObject getUserInfo() {
        Request request = new Request.Builder().url(API_ENDPOINT + "/user_info/")
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                .get().build();
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String responseEntity = response.body().string();
                try {
                    checkAuthorized(responseEntity);
                    return new JsonObject(responseEntity);
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static Collection getPublicFiles() {
        return getPublicFiles(0, 10, null, null, true, Automately.getApiUsername());
    }

    public static Collection getPublicFiles(int page) {
        return getPublicFiles(page, 10, null, null, true, Automately.getApiUsername());
    }

    public static Collection getPublicFiles(int page, int count) {
        return getPublicFiles(page, count, null, null, true, Automately.getApiUsername());
    }

    public static Collection getPublicFiles(int page, int count, String path) {
        return getPublicFiles(page, count, path, null, true, Automately.getApiUsername());
    }

    public static Collection getPublicFiles(int page, int count, String path, String name) {
        return getPublicFiles(page, count, path, name, true, Automately.getApiUsername());
    }

    public static Collection getPublicFiles(int page, int count, String path, String name, boolean recursive) {
        return getPublicFiles(page, count, path, name, recursive, Automately.getApiUsername());
    }

    public static Collection getPublicFiles(int page, int count, String path, String name, boolean recursive, String username) {

        String url = API_ENDPOINT + "/files/public?page=" + page + "&count=" + count + "&recursive=" + recursive;

        if (path != null) {
            url += "&path=" + URLEncoder.encode(path);
        }

        if (name != null) {
            url += "&name=" + URLEncoder.encode(name);
        }

        if (!username.equals(getApiUsername())) {
            url += "&public_user=" + URLEncoder.encode(username);
        } else {
            url += "&public_user=" + getApiUsername();
        }

        // We don't need auth for public stuff
        Request request = new Request.Builder().url(url)
                .addHeader("Content-type", "application/json")
                .get().build();

        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();
                try {
                    //checkAuthorized(entity);

                    JsonArray converted = new JsonArray(entity);
                    HashSet newData = new HashSet<>();
                    for (Object value : converted) {
                        if (value instanceof JsonObject) {
                            newData.add(new VirtualFile((JsonObject) value));
                        }
                    }
                    return newData;
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                } catch (RuntimeException e) {
                    getFormattedError("API Error", "There was an authorization issue. The file(s) you are looking for may not exist.");
                }
            }
        } catch (IOException ignored) {
        }
        return Collections.emptySet();
    }

    public static VirtualFile getPublicFile(String token) {
        return getPublicFile(token, getApiUsername());
    }

    public static VirtualFile getPublicFile(String token, String username) {

        String url = API_ENDPOINT + "/files/public/" + token;

        if (username != null) {
            url += "?public_user=" + URLEncoder.encode(username);
        }

        Request request = new Request.Builder().url(url)
                .addHeader("Content-type", "application/json")
                .get().build();

        // We really don't care about the response

        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();

                try {
                    checkAuthorized(entity);
                    return new VirtualFile(new JsonObject(entity));
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                } catch (RuntimeException e) {
                    getFormattedError("API Error", "There was an authorization issue. The file(s) you are looking for may not exist.");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static boolean downloadPublicFile(String token, Path destination) {
        return downloadPublicFile(token, destination, getApiUsername());
    }

    public static boolean downloadPublicFile(String token, Path destination, String username) {

        String url = API_ENDPOINT + "/files/public/" + token + "/download";

        if (username != null) {
            url += "?public_user=" + URLEncoder.encode(username);
        }

        Request request = new Request.Builder().url(url)
                .addHeader("Content-type", "application/json")
                .get().build();

        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                if (response.code() == 200) {
                    byte[] data = response.body().bytes();
                    Files.deleteIfExists(destination);
                    Files.write(destination, data);
                    return Files.exists(destination);
                }
            }
        } catch (IOException ignored) {
        }
        return false;
    }

    public static Collection getFiles() {
        return getFiles(0, 10, null, null, true);
    }

    public static Collection getFiles(int page) {
        return getFiles(page, 10, null, null, true);
    }

    public static Collection getFiles(int page, int count) {
        return getFiles(page, count, null, null, true);
    }

    public static Collection getFiles(int page, int count, String path) {
        return getFiles(page, count, path, null, true);
    }

    public static Collection getFiles(int page, int count, String path, String name) {
        return getFiles(page, count, path, name, true);
    }

    public static Collection getFiles(int page, int count, String path, String name, boolean recursive) {

        String url = API_ENDPOINT + "/files/?page=" + page + "&count=" + count + "&recursive=" + recursive;

        if (path != null) {
            url += "&path=" + URLEncoder.encode(path);
        }

        if (name != null) {
            url += "&name=" + URLEncoder.encode(name);
        }

        Request request = new Request.Builder().url(url)
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();

        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();
                try {
                    checkAuthorized(entity);

                    JsonArray converted = new JsonArray(entity);

                    HashSet newData = new HashSet<>();

                    for (Object value : converted) {
                        if (value instanceof JsonObject) {
                            newData.add(new VirtualFile((JsonObject) value));
                        }
                    }
                    return newData;

                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return Collections.emptySet();
    }

    public static VirtualFile getFile(String token) {
        Request request = new Request.Builder().url(API_ENDPOINT + "/files/" + token)
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();
        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();

                try {
                    checkAuthorized(entity);
                    return new VirtualFile(new JsonObject(entity));
                } catch (DecodeException ignored) {
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static VirtualFile updateFile(String token, String name, String pathAlias, byte[] data) {

        try {

            if (name == null || name.isEmpty()) {
                throw new IllegalArgumentException("The file name cannot be empty.");
            }

            if (pathAlias == null || pathAlias.isEmpty()) {
                throw new IllegalArgumentException("The pathAlias cannot be empty.");
            }

            RequestBody requestBody = new RequestBody() {
                @Override
                public MediaType contentType() {
                    return MediaType.parse("application/octet-stream");
                }

                @Override
                public void writeTo(BufferedSink sink) throws IOException {
                    sink.write(data);
                }
            };

            Request request = new Request.Builder().url(API_ENDPOINT + "/files/")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-File-Name", name)
                    .addHeader("X-File-Size", String.valueOf(data.length))
                    .addHeader("X-Existing-File-Token", token)
                    .addHeader("X-Path-Alias", pathAlias)
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                    .put(requestBody).build();

            Response response = httpClient.newCall(request).execute();

            if (response != null) {
                String responseEntity = response.body().string();
                try {
                    checkAuthorized(responseEntity);
                    return new VirtualFile(new JsonObject(responseEntity));
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static VirtualFile createFile(String name, String pathAlias, byte[] data, boolean isPublic) {

        try {

            if (name == null || name.isEmpty()) {
                throw new IllegalArgumentException("The file name cannot be empty.");
            }

            if (pathAlias == null || pathAlias.isEmpty()) {
                throw new IllegalArgumentException("The pathAlias cannot be empty.");
            }

            RequestBody requestBody = new RequestBody() {
                @Override
                public MediaType contentType() {
                    return MediaType.parse("application/octet-stream");
                }

                @Override
                public void writeTo(BufferedSink sink) throws IOException {
                    sink.write(data);
                }
            };

            Request request = new Request.Builder().url(API_ENDPOINT + "/files/")
                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-File-Name", name)
                    .addHeader("X-File-Size", String.valueOf(data.length))
                    .addHeader("X-Path-Alias", pathAlias)
                    .addHeader("X-Is-Public", String.valueOf(isPublic))
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                    .post(requestBody).build();

            Response response = httpClient.newCall(request).execute();

            if (response != null) {
                String responseEntity = response.body().string();
                try {
                    checkAuthorized(responseEntity);
                    return new VirtualFile(new JsonObject(responseEntity));
                } catch (DecodeException ignored) {
                    ignored.printStackTrace();
                }
            }
        } catch (IOException ignored) {
            ignored.printStackTrace();
        }
        return null;
    }

    public static boolean deleteFile(String token) {
        try {

            Request request = new Request.Builder().url(API_ENDPOINT + "/files/" + token)
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).delete().build();

            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                if (response.code() == 204) {
                    return true;
                }
            }
        } catch (IOException ignored) {
        }
        return false;
    }

    public static boolean downloadFile(String token, Path destination) {

        String url = API_ENDPOINT + "/files/" + token + "/download";

        Request request = new Request.Builder().url(url)
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                .get().build();

        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                if (response.code() == 200) {
                    byte[] data = response.body().bytes();
                    Files.deleteIfExists(destination);
                    Files.write(destination, data);
                    return Files.exists(destination);
                }
            }
        } catch (IOException ignored) {
        }
        return false;
    }


    private static String getPathAlias(String fullPath) {
        String path = fullPath;
        path = path.trim();
        String alias;
        if (!path.endsWith("/") && Paths.get(path).getParent() != null) {
            Path mPath = Paths.get(path).getParent();
            alias = mPath.toString().replace("\\", "/");
        } else if (path.endsWith("/")) {
            Path mPath = Paths.get(path);
            alias = mPath.toString().replace("\\", "/");
        } else {
            alias = "/";
        }
        if (!alias.startsWith("/")) {
            alias = "/" + alias;
        }
        if (!alias.endsWith("/")) {
            alias = alias + "/";
        }
        // Make sure we return sanitized
        return URIUtils.removeDotSegments(alias.trim());
    }

    private static String getFilename(String fullPath) {
        String path = fullPath;
        path = URIUtils.removeDotSegments(path.trim());
        if (!path.endsWith("/") && !path.equals(".")) {
            return Paths.get(path).getFileName().toString().trim();
        }
        return "";
    }

    public static boolean pathExists(String fullPath) {
        String name = getFilename(fullPath);
        String path = getPathAlias(fullPath);
        Collection files = getFiles(0, 1, path, name, true);
        return files.iterator().hasNext();
    }

    public static boolean fileExists(String fullPath) {
        String name = getFilename(fullPath);
        String path = getPathAlias(fullPath);
        Collection files = getFiles(0, 1, path, name, false);
        return files.iterator().hasNext();
    }

    public static VirtualFile findFile(String fullPath) {
        String name = getFilename(fullPath);
        String path = getPathAlias(fullPath);
        Collection files = getFiles(0, 1, path, name, false);
        if (files.iterator().hasNext()) {
            return files.iterator().next();
        }
        return null;
    }

    public static Job startJob(boolean attachConsole, JsonObject config) {
        return startJob(null, null, attachConsole, config);
    }

    public static Job startJob(JsonObject config) {
        return startJob(null, null, false, config);
    }

    public static Job startJob(String scriptData, String scriptPath) {
        return startJob(scriptData, scriptPath, false);
    }

    public static Job startJob(String scriptData, String scriptPath, boolean attachConsole) {
        return startJob(scriptData, scriptPath, attachConsole, new JsonObject());
    }

    public static Job startJob(String scriptData, String scriptPath, boolean attachConsole, JsonObject config) {
        try {

            if (config == null) {
                config = new JsonObject();
            }

            JsonObject job = new JsonObject();

            config.putBoolean("_broadcastPrintStream", attachConsole);

            if(scriptData != null){

                JsonObject scriptConfig = new JsonObject();
                scriptConfig.putString("scriptData", scriptData);
                scriptConfig.putString("scriptPath", scriptPath != null && !scriptPath.isEmpty() ? scriptPath : "/");

                config.putObject("script", scriptConfig);
            }

            job.putObject("config", config);

            byte[] data = new JsonObject().putObject("job", job).encode().getBytes();

            Request request = new Request.Builder().url(API_ENDPOINT + "/jobs/")
                    .addHeader("Content-type", "application/json")
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                    .post(RequestBody.create(MediaType.parse("application/json"), data))
                    .build();

            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();

                try {
                    checkAuthorized(entity);
                    JsonObject decoded = new JsonObject(entity);

                    // Looks like there was an error
                    if(response.code() == 500){
                        getFormattedError(decoded.getString("message", "Error"), decoded.getString("description", "Error Starting Job"));
                        return null;
                    }
                    return new Job(decoded);
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static boolean stopJob(String jobToken) {

        try {

            Request request = new Request.Builder().url(API_ENDPOINT + "/jobs/" + jobToken)
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).delete().build();

            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                return response.code() == 204;
            }
        } catch (IOException ignored) {
        }
        return false;
    }

    public static Collection getRunningServices() {
        return getRunningServices(0, 0);
    }

    public static Collection getRunningServices(int page) {
        return getRunningServices(page, 0);
    }

    public static Collection getRunningServices(int page, int count) {

        Request request = new Request.Builder().url(API_ENDPOINT + "/jobs?all_data=true&page=" + page + "&count=" + count + "&running=true&services=true")
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();
        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();

                try {
                    checkAuthorized(entity);
                    JsonArray decoded = new JsonArray(entity);

                    HashSet newData = new HashSet<>();
                    for (Object value : decoded) {
                        if (value instanceof JsonObject) {
                            newData.add(new Job((JsonObject) value));
                        }
                    }
                    return newData;
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return Collections.emptySet();
    }

    public static Collection getRunningJobs() {
        return getRunningJobs(0, 0);
    }

    public static Collection getRunningJobs(int page) {
        return getRunningJobs(page, 0);
    }

    public static Collection getRunningJobs(int page, int count) {

        Request request = new Request.Builder().url(API_ENDPOINT + "/jobs?all_data=true&page=" + page + "&count=" + count + "&running=true")
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();
        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();

                try {
                    checkAuthorized(entity);
                    JsonArray decoded = new JsonArray(entity);

                    HashSet newData = new HashSet<>();
                    for (Object value : decoded) {
                        if (value instanceof JsonObject) {
                            newData.add(new Job((JsonObject) value));
                        }
                    }
                    return newData;
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return Collections.emptySet();
    }

    public static Collection getJobs() {
        return getJobs(0, 0);
    }

    public static Collection getJobs(int page) {
        return getJobs(page, 0);
    }

    public static Collection getJobs(int page, int count) {

        Request request = new Request.Builder().url(API_ENDPOINT + "/jobs?all_data=true&page=" + page + "&count=" + count)
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();
        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();

                try {
                    checkAuthorized(entity);
                    JsonArray decoded = new JsonArray(entity);

                    HashSet newData = new HashSet<>();
                    for (Object value : decoded) {
                        if (value instanceof JsonObject) {
                            newData.add(new Job((JsonObject) value));
                        }
                    }
                    return newData;
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return Collections.emptySet();
    }

    public static Job getJob(String token) {

        Request request = new Request.Builder().url(API_ENDPOINT + "/jobs/" + token)
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();
        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();
                try {
                    checkAuthorized(entity);
                    return new Job(new JsonObject(entity));
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static String getJobConsole(String token) {
        Request request = new Request.Builder().url(API_ENDPOINT + "/jobs/" + token + "/console")
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes())).get().build();
        // We really don't care about the response
        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                String entity = response.body().string();
                if (response.code() == 200) {
                    try {
                        checkAuthorized(entity);
                        // This means the job isn't running so let's get the job status
                        if (entity.contains("Error: The job may not be running anymore.")) {
                            return null;
                        }
                        return entity;
                    } catch (DecodeException ignored) {
                    }
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }


    public static Collection getKeys() {
        return getKeys(0, 0);
    }

    public static Collection getKeys(int page) {
        return getKeys(page, 0);
    }

    public static Collection getKeys(int page, int count) {

        Request request = new Request.Builder().url(API_ENDPOINT + "/keys?&page=" + page + "&count=" + count)
                .addHeader("Content-type", "application/json")
                .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":"  + API_KEY).getBytes())).get().build();

        try {
            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                if(response.code() == 403){
                    getFormattedError("Access Denied", "You are not authorized to make the request.");
                }
                String entity = response.body().string();
                try {
                    checkAuthorized(entity);
                    JsonArray decoded = new JsonArray(entity);

                    HashSet newData = new HashSet<>();
                    for (Object value : decoded) {
                        if (value instanceof JsonObject) {
                            newData.add((JsonObject) value);
                        }
                    }
                    return newData;
                } catch (DecodeException ignored) {
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return Collections.emptySet();
    }

    public static JsonObject generateKey(String nickname, String description, boolean isDefault){
        return generateKey(nickname, description, isDefault, null);
    }

    public static JsonObject generateKey(String nickname, String description, boolean isDefault, String userPassword){

        try {

            Request request = new Request.Builder().url(API_ENDPOINT + "/keys?confirm=yes" +
                    "&nickname=" + ((nickname != null && !nickname.isEmpty()) ? nickname : "") +
                    "&description=" + ((description != null && !description.isEmpty()) ? description : "") +
                    "&default=" + (isDefault ? "yes" : "no"))
                    .addHeader("Content-type", "application/json")
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                    .addHeader("X-Auth-Password", userPassword != null ? Base64.encodeBytes(userPassword.getBytes()) : "")
                    .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "")).build();

            Response response = httpClient.newCall(request).execute();

            if(response != null){
                if(response.code() == 403){
                    getFormattedError("Access Denied", "You are not authorized to make the request.");
                }
                String responseEntity = response.body().string();
                try {
                    checkAuthorized(responseEntity);

                    return new JsonObject(responseEntity);
                } catch (DecodeException ignored){
                    getFormattedError("Decode Exception", "There was an issue decoding the response.");
                }
            }
        } catch (IOException ignored) {
        }
        return null;
    }

    public static boolean revokeKey(String keyId, String userPassword){

        try {

            Request request = new Request.Builder().url(API_ENDPOINT + "/keys/" + keyId)
                    .addHeader("Authorization", "Basic " + Base64.encodeBytes((API_USERNAME + ":" + API_KEY).getBytes()))
                    .addHeader("X-Auth-Password", userPassword != null ? Base64.encodeBytes(userPassword.getBytes()) : "")
                    .delete().build();

            Response response = httpClient.newCall(request).execute();
            if (response != null) {
                if(response.code() == 403){
                    getFormattedError("Access Denied", "You are not authorized to make the request.");
                } else if(response.code() == 400){
                    getFormattedError("Access Denied", "Revocation failed. Is it a default key?");
                }
                return response.code() == 204;
            }
        } catch (IOException ignored) {
        }
        return false;
    }

    private static MessageBus defaultMessageBus = null;

    public static MessageBus messageBus(){
        return defaultMessageBus != null ? defaultMessageBus : (defaultMessageBus = new MessageBus());
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy