API Client Code - Java

Client Library Code

The client library code in java is provided here as a reference. Anybody who needs to make API calls to fetch and update data into their microsite through HTTP calls can use this directly or use part of this code as required.

 

ConnectionConfig.java

This is a data holder class which holds the URL, username and password required for making the initial API connection call. This object would be created by the ConnectionConfigManager factory class and would be used to create the Connection object.

 

import java.io.Serializable;

@SuppressWarnings("serial")
public class ConnectionConfig implements Serializable {
    private String url ;
    private String userName;
    private String password;

    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        if(url != null){
            this.url = url.trim();
        }else{
            this.url = null;
        }
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        if(userName != null){
            this.userName = userName.trim();
        }else{
            this.userName = null;
        }
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        if(password != null){
            this.password = password;
        }else{
            this.password = null;
        }
    }
    
    public ConnectionConfig(String url, String userName, String password) {
        super();
        this.url = url;
        this.userName = userName;
        this.password = password;
    }
    public ConnectionConfig() {
        super();
    }
    
    public static String getBandanaKey(){
        return ConnectionConfig.class.getPackage().getName();
    }
    
    public String toString(){
        return url + "," + userName + "," + password;
    }
}

 

ConnectionConfigManager.java

This is the factory class which creates the ConnectionConfig data holder class. The url, username and password needs to be specified after obtaining it from the microsite as given in the Configure Site for API Communication article

 

 public class ConnectionConfigManager {
    
    private final static ConnectionConfigManager instance = new ConnectionConfigManager();
    
    private ConnectionConfigManager() {
    }
    
    public static ConnectionConfigManager getInstance() {
        return instance;
    }
    
    public ConnectionConfig getConnectionConfig() {
        String url = "http://learnzone.edubrite.com";
        String userName = "api_3e3a7f38-a5ec-11e1-b0fc-151630b0e25e";
        String password = "VBI2MB5qbngOGRLr4cBwV7D3IyLS8BMnC2uXVXTtmwi7S9c7927sHeW8NbwTLF6avpeHdkrnSA76Rj3Wq6egzH_GjIeVOLA4OlwyLMGM058*|389533226000";
        
        return new ConnectionConfig(url, userName, password);
    }
}

 

CommunicationError.java

This is an enum which lists the error codes.

 

 public enum CommunicationError {
    BAD_URL,
    SERVER_NOT_RECHABLE,
    BAD_USERNAME_PASSWORD,
    UNKNOWN_ERROR,
    ENC_DEC_ERROR,
    NO_ERROR
}

 

Connection.java

This is the core client class which stores the entire connection configuration (initialized in the constructor) and provides the functionality of making the initial connection with the server (connect() method) and the method to make all the subsequent API calls (invokeApi() method). In addition to configuration parameters (host, username, password) it also stores the returned sessionid and sessioninfo if connection is successful. It also stores the returned XML data (lastResponseXml) after every call to the site.

 

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

import javax.servlet.http.HttpServletResponse;



import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import com.google.gdata.util.common.base.Pair;


public class Connection {
    
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String SESSION_ID = "SESSION_ID";
    private static final String SESSION_INFO = "SESSION_INFO";
    private static final String REAL_UNAME = "REAL_UNAME";
    
    private final String host;
    private final int port;
    private final String userName;
    private final String password;
    private String sessionId;
    private String sessionInfo;
    private HttpClient client;
    
    private static ThreadLocal<Pair<CommunicationError, Integer>> error = new ThreadLocal<Pair<CommunicationError, Integer>>();
    private static ThreadLocal<Exception> exception = new ThreadLocal<Exception>();
    private AtomicBoolean connected = new AtomicBoolean(false);
    private String lastResponseXml;

    public Connection(ConnectionConfig connectionConfig) {
        client = new HttpClient();
        URL urlO = null;
        try {
            urlO = new URL(connectionConfig.getUrl().trim());
        } catch (Exception e) {
            error.set(Pair.of(CommunicationError.BAD_URL, -1));
        }
        if (urlO != null) {
            host = urlO.getHost();
            port = urlO.getPort();
        } else {
            host = null;
            port = 0;
        }
        if(connectionConfig.getUserName() != null){
            this.userName = connectionConfig.getUserName().trim();
        }else{
            this.userName = null;
        }
        if(connectionConfig.getPassword() != null){
            this.password = connectionConfig.getPassword().trim();
        }else{
            this.password = null;
        }
    }

    public String getSessionId() {
        return sessionId;
    }

    public String getSessionInfo() {
        return sessionInfo;
    }

    private String getPortStr() {
        if (port > 0 && port != 80) {
            return ":" + port;
        } else {
            return "";
        }
    }

    public void disconnect(){
        sessionId = null;
        sessionInfo = null;
        lastResponseXml = null;
        connected.set(false);
        error.set(Pair.of(CommunicationError.NO_ERROR, 0));
        exception.set(null);
    }
    
    public boolean connect() {
        if(connected.get()){
            return true;
        }
        return connectInternal();
    }
    
    private synchronized boolean connectInternal() {
        disconnect();
        HttpMethod method0 = null, method = null;
        try {
            int code = 0;
            String url = "http://" + host + getPortStr() + "/oltpublish/site/connect.do";
           
            // First connect to initialize the site.
            method0 = new GetMethod(url);
            code = client.executeMethod(method0);
           
            // Second connect to authenticate the username/password and receive back the cookies.
            method = new GetMethod(url);
            List<NameValuePair> nvpList = new ArrayList<NameValuePair>(2);
            nvpList.add(new NameValuePair(USERNAME, userName));
            nvpList.add(new NameValuePair(PASSWORD, password));
            method.setQueryString(nvpList.toArray(new NameValuePair[nvpList.size()]));
            code = client.executeMethod(method);
           
            lastResponseXml = method.getResponseBodyAsString();
           
            // Store the cookies locally.
            if (code == HttpServletResponse.SC_OK) {
                Cookie[] cookies = client.getState().getCookies();
                if (cookies != null && cookies.length > 0) {
                    for (Cookie c : cookies) {
                        if (c.getName().equals(SESSION_ID)) {
                            sessionId = c.getValue();
                        } else if (c.getName().equals(SESSION_INFO)) {
                            sessionInfo = c.getValue();
                        }
                    }
                }
                if (sessionId == null || sessionId.trim().isEmpty() || sessionInfo == null || sessionInfo.trim().isEmpty()) {
                    error.set(Pair.of(CommunicationError.UNKNOWN_ERROR, code));
                    exception.set(null);
                } else{
                    error.set(Pair.of(CommunicationError.NO_ERROR, code));
                    exception.set(null);
                    connected.set(true);
                }
            } else {
                error.set(Pair.of(CommunicationError.BAD_USERNAME_PASSWORD, code));
                exception.set(null);
            }
        } catch (Exception e) {
            exception.set(e);
            error.set(Pair.of(CommunicationError.BAD_URL, -1));
        }finally{
            if(method0 != null){
                method0.releaseConnection();
            }
            if(method != null){
                method.releaseConnection();
            }
        }
        return connected.get();
    }

    private CommunicationError getError(){
        return error.get() == null ? CommunicationError.NO_ERROR : error.get().getFirst();
    }
    
    private String getApiUrl(String uri){
        return "http://" + host + getPortStr() + "/oltpublish/site/" + uri;
    }
    
    public String invokeApi(String uri, String realUserName, Map<String, String> parameters) {
        if (!connected.get()) {
            throw new IllegalStateException(getError().name(), exception.get());
        }
       
        PostMethod method = null;
        String apiResponseStr = null;
        try {
            HttpState state = new HttpState();
            Cookie sessionIdCookie = new Cookie(host, SESSION_ID, sessionId, "/", null, false);
            Cookie sessionInfoCookie = new Cookie(host, SESSION_INFO, sessionInfo, "/", null, false);
            state.addCookie(sessionIdCookie);
            state.addCookie(sessionInfoCookie);
           
            client.setState(state);
            method = new PostMethod(getApiUrl(uri));
           
            method.addRequestHeader(REAL_UNAME, realUserName);
           
            //version
            if (parameters != null && !parameters.isEmpty()) {
                List<NameValuePair> nvpList = new ArrayList<NameValuePair>(parameters.size());
                for (Map.Entry<String, String> entry : parameters.entrySet()) {
                    nvpList.add(new NameValuePair(entry.getKey(), entry.getValue()));
                }
                method.setRequestBody( nvpList.toArray(new NameValuePair[nvpList.size()]));
            }
           
            int code = client.executeMethod(method);
            if (code == HttpServletResponse.SC_OK) {
                error.set(Pair.of(CommunicationError.NO_ERROR, code));
                exception.set(null);
            } else {
                error.set(Pair.of(CommunicationError.UNKNOWN_ERROR, code));
                exception.set(null);
            }
            apiResponseStr = method.getResponseBodyAsString();
        } catch (Exception e) {
            exception.set(e);
            error.set(Pair.of(CommunicationError.BAD_URL, -1));
        }finally{
            if(method != null){
                try{method.releaseConnection();}catch(Exception e){}
            }
        }
        lastResponseXml = apiResponseStr;
        return apiResponseStr;
    }

    public boolean isConnected() {
        return connected.get();
    }

    public CommunicationError getLastError() {
        return getError();
    }
    
    public int getLastHTTPCode() {
        return error.get() == null ? 0 : error.get().getSecond();
    }

    public Exception getLastException() {
        return exception.get();
    }
    
    public String getLastResponseXml() {
        return lastResponseXml;
    }

    public void release() {
        if (client != null && connected.get()) {

        }
    }
}


Rating: