Package nz.ac.canterbury.kraken

Source Code of nz.ac.canterbury.kraken.JKraken$Resize

/*
* JKraken
* Implementation of Kraken API
*/
package nz.ac.canterbury.kraken;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import nz.co.wetstone.http.SimpleHTTPClient;
import org.json.JSONException;
import org.json.JSONObject;

/**
*
* @author davidm
*/
public class JKraken {

    private Auth auth;
    private boolean debug;

    public JKraken(String key, String secret) {
        auth = new Auth();
        auth.APIKey = key;
        auth.APISecret = secret;
    }

    public JKrakenResult url(Options opts) {
        try {
            JSONObject j = new JSONObject();
            j.put("url", opts.getUrl());
            j.put("wait", opts.isWait());
            if (opts.getResize() != null) {
                j.put("resize", opts.getResize().toJSON());
            }
            j.put("auth", auth.toJSON());
            j.put("webp", opts.isWebp());
            j.put("lossy", opts.isLossy());
            j.put("callback_url", opts.getCallbackUrl());
            if (opts.getExternalStore() != null) {
                j.put(opts.getExternalStore().APIName(), opts.getExternalStore().toJSON());
            }
            return request(j.toString(), "https://api.kraken.io/v1/url");
        } catch (JSONException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
            return error("JSONException");
        }

    }

    private JKrakenResult request(String json, String url) {
        try {
            if (debug) {
                System.out.println("DEBUG::JSON Request: " + json);
            }
            SimpleHTTPClient.URIParameterBuilder builder = new SimpleHTTPClient.URIParameterBuilder();
            builder.setHost(url);
            builder.setStringEntity(json);
            SimpleHTTPClient client = new SimpleHTTPClient();
            client.addHeader("Content-Type", "application/json");
            String response = client.grabPageHTML(SimpleHTTPClient.HTTP_POST, builder);
            if(debug) {
                System.out.println("DEBUG::JSON Response: " + response);
            }
            return createResult(response);
        } catch (IOException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
            return error("IOException");
        } catch (URISyntaxException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
            return error("URISyntaxException");
        }
    }

    private JKrakenResult error(String string) {
        String error = "{"
                + "\"success\":false,"
                + "\"error\":\""+string+"\""
                + "}";
        if(debug) {
            System.out.println("DEBUG::ERROR: " + error);
        }
        return createResult(error);
    }

    public JKrakenResult upload(Options opts) {
        if (opts.getFile() == null) {
            return error("File parameter was not provided");
        }
        try {
            //See if it is a url
            URI uri = new URI(opts.getFile());
            uri = null;
            //is a url then continue with url method
            opts.setUrl(opts.getFile());
            return url(opts);
        } catch (URISyntaxException ex) {
            //Not a url must be a file path
        }
        File file = new File(opts.getFile());
        if (!file.exists()) {
            return error("File " + file.getAbsolutePath() + " does not exist");
        }
        String fileBytes = readFileBytes(file);
        try {
            JSONObject data = new JSONObject();
            data.put("wait", opts.isWait());
            if (opts.getResize() != null) {
                data.put("resize", opts.getResize().toJSON());
            }
            data.put("auth", auth.toJSON());
            data.put("webp", opts.isWebp());
            data.put("lossy", opts.isLossy());
            data.put("callback_url", opts.getCallbackUrl());
            if (opts.getExternalStore() != null) {
                data.put(opts.getExternalStore().APIName(), opts.getExternalStore().toJSON());
            }
            JSONObject j = new JSONObject();
            j.put("file", fileBytes);
            j.put("data", data);
            return request(j.toString(), "https://api.kraken.io/v1/upload");
        } catch (JSONException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
            return error("JSONException");
        }
    }

    public JKrakenResult status() {
        try {
            JSONObject data = new JSONObject();
            data.put("auth", auth.toJSON());
            return request(data.toString(), "https://api.kraken.io/user_status");
        } catch (JSONException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
            return error("JSONException");
        }
    }

    public void setDebug(boolean b) {
        debug = b;
    }

    private String readFileBytes(File file) {
        FileInputStream in;
        try {
            byte[] fileData = new byte[safeLongToInt(file.length())];
            in = new FileInputStream(file);
            in.read(fileData);
            in.close();
            return fileData.toString();
            // content now contains your bits.
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
        } catch (IOException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, "", ex);
        }
        return "";
    }

    private int safeLongToInt(long l) {
        if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
            throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
        }
        return (int) l;
    }

    private JKrakenResult createResult(String response) {
        try {
             JKrakenResult result = new JKrakenResult(new JSONObject(response));
             return result;
        } catch (JSONException ex) {
            Logger.getLogger(JKraken.class.getName()).log(Level.SEVERE, null, ex);
            JKrakenResult r = new JKrakenResult();
            r.setSuccess(false);
            r.setError("JSONException formatting results");
            return r;
        }
       
    }

    private class Auth {

        String APIKey;
        String APISecret;

        JSONObject toJSON() throws JSONException {
            JSONObject j = new JSONObject();
            j.put("api_key", APIKey);
            j.put("api_secret", APISecret);
            return j;
        }
    }

    public static class Options {

        String file;
        String url;
        boolean wait;
        boolean webp;
        boolean lossy;
        ExternalStore externalStore;
        Resize resize;
        String callbackUrl;

        public String getCallbackUrl() {
            return callbackUrl;
        }

        public void setCallbackUrl(String callbackUrl) {
            this.callbackUrl = callbackUrl;
        }

        public String getFile() {
            return file;
        }

        public void setFile(String file) {
            this.file = file;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public boolean isWait() {
            if (getCallbackUrl() == null) {
                return wait;
            }
            return false;
        }

        public void setWait(boolean wait) {
            this.wait = wait;
        }

        public boolean isWebp() {
            return webp;
        }

        public void setWebp(boolean webp) {
            this.webp = webp;
        }

        public boolean isLossy() {
            return lossy;
        }

        public void setLossy(boolean lossy) {
            this.lossy = lossy;
        }

        public ExternalStore getExternalStore() {
            return externalStore;
        }

        public void setExternalStore(ExternalStore externalStore) {
            this.externalStore = externalStore;
        }

        public Resize getResize() {
            return resize;
        }

        public void setResize(Resize resize) {
            this.resize = resize;
        }
    }

    public static class Resize {

        String width;
        String height;
        String strategy;

        JSONObject toJSON() throws JSONException {
            JSONObject j = new JSONObject();
            j.put("width", width);
            j.put("heigth", height);
            j.put("strategy", strategy);
            return j;
        }
    }
}
TOP

Related Classes of nz.ac.canterbury.kraken.JKraken$Resize

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.