teletype.model.vk.Auth.java Source code

Java tutorial

Introduction

Here is the source code for teletype.model.vk.Auth.java

Source

/*
* Copyright (C) 2015 Andrii Bilorus <andrei.belorus@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/

package teletype.model.vk;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.Header;
import org.apache.http.impl.client.BasicCookieStore;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.io.StringWriter;
import java.net.URI;

import teletype.controller.LoginControllerHelper;

/**
 * Class is used for authorization in vk.com
 * For more information about VK API see <a href="http://vk.com/dev/auth_mobile">http://vk.com/dev/auth_mobile</a>
 * @author Andrii Bilorus
 */
public class Auth {

    String login;
    String password;
    String appID;

    public Auth() {

    }

    public Auth(String login, String password) {
        this.login = login;
        this.password = password;
        this.appID = "4816528";
    }

    public void authorize() throws VKAuthException, IOException {

        // Phase 1. Send authorization request.
        // Opening OAuth Authorization Dialog
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setScheme("https").setHost("oauth.vk.com").setPath("/authorize").setParameter("client_id", appID)
                .setParameter("scope", "messages,friends,status")
                .setParameter("redirect_uri", "https://oauth.vk.com/blank.html").setParameter("display", "wap")
                .setParameter("v", "5.28").setParameter("response_type", "token");

        BasicCookieStore cookieStore = new BasicCookieStore();
        HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
        URI uri = getUri(uriBuilder);
        HttpPost request = new HttpPost(uri);
        HttpResponse response = httpClient.execute(request);
        request.abort();

        // Get ip_h and to_h parameters for next request 
        StringBuilder contentText = getContentText(response);

        String ip_h = parseResponse(contentText, "ip_h", 18);
        //System.out.println("ip_h : " + ip_h);

        String to_h = parseResponse(contentText, "=\"to\"", 212);
        //System.out.println("to_h : " + to_h);

        uriBuilder = new URIBuilder();
        uriBuilder.setScheme("https").setHost("login.vk.com").setPath("/").setParameter("act", "login")
                .setParameter("soft", "1").setParameter("q", "1").setParameter("ip_h", ip_h)
                .setParameter("from_host", "oauth.vk.com").setParameter("to", to_h).setParameter("expire", "0")
                .setParameter("email", login).setParameter("pass", password);

        request = new HttpPost(getUri(uriBuilder));
        response = httpClient.execute(request);
        request.abort();

        //System.out.println("Incorrect login url: " + uriBuilder.toString());

        // Phase 2. Providing Access Permissions
        // TODO: if got access request then call externall web browser. possible do it ourselves.

        // Phase 3. Open url with webengine and receiving "access_token".
        // It does not work with httpClient
        LoginControllerHelper.callHiddenWebBrowser(uriBuilder.toString());

        //if (true) return;

        /*
        printHeader(response);
            
        // Phase 2. Got redirect to authorization page.
        // Filling the form and sending it.
        //String HeaderLocation = response.getFirstHeader("location").getValue();
        request = new HttpPost(HeaderLocation);
        response = httpClient.execute(request);
        //System.out.println("==================>");
        request.abort();
        //String url = response.getFirstHeader("location").getValue();
            
        // Phase 3. Got permissions request.
        // Open web browser and sending link there.
        //System.out.println("URL is: " + url);
        // Calling externall web browser.
        ControllerHelper.callHiddenWebBrowser(url);
        //ControllerHelper.callWebBrowser(url);
            
        /*
         * It works by calling external web-browser.
         * All redirects ok and gives the token.
         * But doesn't work using HttpClient.
         * Server redirects me to error page.
         *
            
        request = new HttpPost(url);
        response = httpClient.execute(request);
        System.out.println("Sending last ==================>\n");
            
        HeaderLocation = response.getFirstHeader("location").getValue();
            
        //String access_token = HeaderLocation.split("#")[1].split("&")[0].split("=")[1];
        System.out.println("Header is: " + HeaderLocation);
        */
    }

    private URI getUri(URIBuilder uriBuilder) {
        URI uri = null;
        try {
            uri = uriBuilder.build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return uri;
    }

    private String getResponseUrl(StringBuilder contentText) {
        int begin = contentText.indexOf("action=") + 8;
        int end = contentText.indexOf("\"", begin);
        return contentText.substring(begin, end);
    }

    private String parseResponse(StringBuilder contentText, String value, int charCount) {
        int indexOf = contentText.indexOf(value);
        String returnValue = contentText.substring(indexOf + 13, indexOf + 13 + charCount);
        return returnValue;
    }

    private StringBuilder getContentText(HttpResponse response) throws IOException {
        Integer status = response.getStatusLine().getStatusCode();
        if (status == 200 || status == 302 || status == 401) {
            StringWriter content = new StringWriter();
            try {
                IOUtils.copy(response.getEntity().getContent(), content);
            } catch (IOException e) {
                System.out.println("Unexpected error: " + e.toString());
                e.printStackTrace();
                throw e;
            }
            return new StringBuilder(content.toString());
        } else {
            System.out.println("Unexpected behavior. Http response status: " + status);
        }
        return new StringBuilder();
    }
    /*
        private void printHeader(HttpResponse response) {
    for (Header h : response.getAllHeaders()) {
        System.out.println("Name: " + h.getName() + " - Value: " + h.getValue());
    }
        }
        */

}