読者です 読者をやめる 読者になる 読者になる

かれ4

かれこれ4個目のブログ

課金のAPIが欲しいとか作ってみたとか、途中経過とか

七夕のお願い
課金API
必要な物
aws sdk for java (1.2.1使った)
それに付いてる3rdpartyの中身 (多分httpClientしか使ってない)

使い方はActivityClient.java のmainに書いてあり

githubにあげるのもめんどいからここにコピペ

MailPassAWSCredentials.java

package jp.jawsug.account;

import com.amazonaws.auth.AWSCredentials;

public class MailPassAWSCredentials implements AWSCredentials {

    private String mailAddress;

    private String password;

    public MailPassAWSCredentials(String mail, String pass) {
        this.mailAddress = mail;
        this.password = pass;
    }

    @Override
    public String getAWSAccessKeyId() {
        return this.mailAddress;
    }

    @Override
    public String getAWSSecretKey() {
        return this.password;
    }
}

ActivityClient.java

ここが大事な所。
勝手にログインして、AccountActivityのページのソース取ってきてくれる。

package jp.jawsug.account;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import com.amazonaws.auth.AWSCredentials;

public class ActivityClient {

    public static void main(String[] args) {
        ActivityClient a = new ActivityClient(new MailPassAWSCredentials("メールアドレス", "パスワード"));
        a.get();
    }

    private AWSCredentials cred;

    private HttpClient client;

    private static String LOGIN_ENDPOINT = "https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=aws&openid.return_to=https%3A%2F%2Faws-portal.amazon.com%2Fgp%2Faws%2Fdeveloper%2Faccount%2Findex.html%3Fie%3DUTF8%26action%3Dactivity-summary&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.pape.max_auth_age=3600&siteState=&pageId=aws.ssop&openid.pape.preferred_auth_policies=http%3A%2F%2Fschemas.openid.net%2Fpape%2Fpolicies%2F2007%2F06%2Fmulti-factor-physical&marketplaceId=ATVPDKIKX0DER&accountStatusPolicy=P1&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&authCookies=1";

    public ActivityClient(MailPassAWSCredentials cred) {
        this.cred = cred;
        this.client = new DefaultHttpClient(new ThreadSafeClientConnManager());
    }

    public Activity get() {
        HttpUriRequest loginuri = new HttpGet(ActivityClient.LOGIN_ENDPOINT);
        try {
            HttpResponse response = this.client.execute(loginuri);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                String buf = "";
                Pattern p = Pattern.compile(".*?<input.*?name=\"(.*?)\".*?value=\"(.*?)\".*");
                Pattern p2 = Pattern.compile(".*?<form.*?action=\"(.*?)\"");
                String action = "";
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                Map<String, String> tmpParams = new HashMap<String, String>();
                while ((buf = br.readLine()) != null) {
                    Matcher m = p.matcher(buf);
                    if (m.matches()) {
                        tmpParams.put(m.group(1), m.group(2));
                    }
                    else {
                        Matcher m2 = p2.matcher(buf);
                        if (m2.matches()) {
                            action = m2.group(1);
                        }
                    }
                }
                tmpParams.put("email", this.cred.getAWSAccessKeyId());
                tmpParams.put("password", this.cred.getAWSSecretKey());
                tmpParams.put("appAction", "SIGNIN");

                for (Entry<String, String> e : tmpParams.entrySet()) {
                    NameValuePair nameValuePair = new BasicNameValuePair(e.getKey(), e.getValue());
                    params.add(nameValuePair);
                }

                if (!action.equals("")) {
                    HttpPost login = new HttpPost(action);
                    login.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
                    HttpResponse r = this.client.execute(login);
                    if (r.getStatusLine().getStatusCode() >= 300 && r.getStatusLine().getStatusCode() < 400) {
                        this.client.getConnectionManager().closeExpiredConnections();
                        Header[] headers = r.getHeaders("location");
                        for (Header header : headers) {
                            String url = header.getValue();
                            HttpGet g = new HttpGet(url);
                            HttpResponse r2 = this.client.execute(g);
                            br = new BufferedReader(new InputStreamReader(r2.getEntity().getContent()));
                            buf = "";
                            StringBuilder sb = new StringBuilder();
                            while ((buf = br.readLine()) != null) {
                                System.out.println(buf);
                            }
                            return Activity.factory(sb);
                        }
                    }

                }
                else {
                    System.out.print("##[Activity.get()]::");
                    System.out.println("action is blank");
                }
            }
        }
        catch (ClientProtocolException e) {
            e.printStackTrace();

        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Activity.java

package jp.jawsug.account;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Activity {

    public static Activity factory(CharSequence body) {
        // 本当は全部パースして、サービス毎に出せるようにしたかったんだ。。。
        return new Activity();

    }

    private Activity() {

    }

    public List<HashMap<String, Float>> getBilling(SERVICE service, REGION region) {
        ArrayList<HashMap<String, Float>> list = new ArrayList<HashMap<String, Float>>();

        return list;
    }

    enum SERVICE {
        EC2("Amazon Elastic Compute Cloud"), EMR("Amazon Elastic MapReduce "), CloudFront("Amazon CloudFront"), SimpleDB("Amazon SimpleDB "), RDS("Amazon Relational Database Service "), FWS("Amazon Fulfillment Web Service"), SQS("Amazon Simple Queue Service"), SNS(
                "Amazon Simple Notification Service "), SES("Amazon Simple Email Service"), CloudWatch("Amazon CloudWatch "), Route53("Amazon Route 53 "), VPC("Amazon Virtual Private Cloud"), FPS("Amazon Flexible Payments Service"), DevPay("Amazon DevPay"), S3("Amazon Simple Storage Service"), MechanicalTurk(
                "Amazon Mechanical Turk "), AlexaWebInfomationService("Alexa Web Information Service"), AlexaTopSites("Alexa Top Sites"), PremiumSupport("AWS Premium Support");

        private String name;

        private SERVICE(String name) {
            this.name = name;
        }

        public String getName() {
            return this.name;
        }

    }

    enum REGION {
        US_WEST, US_EAST, EU, AP_SOUTHEAST, AP_NORTHEAST, NONE
    }

}