Sample JAVA program to Query records using REST API

Sample Program:


package packageForREST;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

public class QueryUsingREST {
/* --------- Login Credentials ---------- */
private static String userName;
private static String password;

private static String OAUTH_ENDPOINT = "/services/oauth2/token";
private static String REST_ENDPOINT = "/services/data";
String queryStr;
String baseUri;
Header oauthHeader;
Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");

private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) {
new QueryUsingREST();
}

/* Constructor */
public QueryUsingREST() {
getLoginCredentials();
this.oauth2Login();
this.retrieveRecords();
}

/* Authentication using oauth2 */
public HttpResponse oauth2Login() {
System.out.println("Logging in... Kindly Wait...");
OAuth2Response oauth2Response = null;
HttpResponse response = null;
UserCredentials userCredentials = new UserCredentials();
String loginHostUri = "https://" + 
userCredentials.loginInstanceDomain + OAUTH_ENDPOINT;

try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginHostUri);
StringBuffer requestBodyText = new StringBuffer("grant_type=password");
requestBodyText.append("&username=");
requestBodyText.append(userCredentials.userName);
requestBodyText.append("&password=");
requestBodyText.append(userCredentials.password);
requestBodyText.append("&client_id=");
requestBodyText.append(userCredentials.consumerKey);
requestBodyText.append("&client_secret=");
requestBodyText.append(userCredentials.consumerSecret);
StringEntity requestBody = new StringEntity(requestBodyText.toString());
requestBody.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(requestBody);
httpPost.addHeader(prettyPrintHeader);

response = httpClient.execute(httpPost);
 
if (  response.getStatusLine().getStatusCode() == 200 ) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
oauth2Response = new OAuth2Response(json);
System.out.println("JSON returned by response: +\n" + json.toString(1));
} catch (JSONException je) {
je.printStackTrace();
}  
baseUri = oauth2Response.instance_url + REST_ENDPOINT + "/v" + userCredentials.apiVersion +".0";
oauthHeader = new BasicHeader("Authorization", "OAuth " + oauth2Response.access_token);
System.out.println("\nSuccessfully logged in to instance: " + baseUri);
} else {
System.out.println("An error has occured. Http status: " + response.getStatusLine().getStatusCode());
System.out.println(getBody(response.getEntity().getContent()));
System.exit(-1);
}
} catch (UnsupportedEncodingException uee) {
uee.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return response;
}

/* Method to retrieve records */
public void retrieveRecords() {
System.out.println("\nQuerying Example\n");
try {
queryStr = getUserInput("Enter the query: ");
System.out.println("\nThe query is " + queryStr);
HttpClient httpClient = new DefaultHttpClient();
String uri = baseUri + queryStr;
System.out.println("\nQuery URL: " + uri + "\n");
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader(oauthHeader);
httpGet.addHeader(prettyPrintHeader);

HttpResponse response = httpClient.execute(httpGet);

int statusCode = response.getStatusLine().getStatusCode();
System.out.println("\nStatus code returned is " + statusCode + "\n\n");
if (statusCode == 200) {
String response_string = EntityUtils.toString(response.getEntity());
try {
JSONObject json = new JSONObject(response_string);
System.out.println("Id\t\t\t\tName");
for(Integer i = 0; i < json.length() - 1; i++){
System.out.print(json.getJSONArray("records").getJSONObject(i).getString("Id") + "\t\t");
System.out.print(json.getJSONArray("records").getJSONObject(i).getString("Name") + "\n");
}
System.out.println("\nEnd of the execution");
} catch (JSONException je) {
je.printStackTrace();
}          
} else {
System.out.println("Query was unsuccessful. Status code returned is " + statusCode);
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}

/* Class to hold values returned by the OAuth request. */
static class OAuth2Response {
String id;
String issued_at;
String instance_url;
String signature;
String access_token;

public OAuth2Response() {
}
public OAuth2Response(JSONObject json) {
try {
id =json.getString("id");
issued_at = json.getString("issued_at");
instance_url = json.getString("instance_url");
signature = json.getString("signature");
access_token = json.getString("access_token");

} catch (JSONException e) {
e.printStackTrace();
}
}
}

/* Class to store user login credentials */
class UserCredentials {
String loginInstanceDomain = "na1.salesforce.com";
String apiVersion = "22";
String userName = QueryUsingREST.userName;
String password = QueryUsingREST.password;
String consumerKey = "3MVG99OxTyEMCQ3hvhY_jCIAcS5.TwlxLkUPavrSugAtRMxYIW5Woi.ujyRUbQRWqDPG_JLRVWVcKHqTIp9EL";
String consumerSecret = "4820902082354189113";
String grantType = "password";
}

private String getBody(InputStream inputStream) {
String result = "";
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(inputStream)
);
String inputLine;
while ( (inputLine = in.readLine() ) != null ) {
result += inputLine;
result += "\n";
}
in.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}

/* Method to get login credentials */
private void getLoginCredentials() {
userName = getUserInput("Enter the username: ");
password = getUserInput("Enter the password: ");
}

/* Method to get user input */
private String getUserInput(String prompt) {
String result = "";
try {
System.out.print(prompt);
result = reader.readLine();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return result;
}
}

Sample Input for Query:
/query?q=SELECT+id+,+name+FROM+Account+limit+2

No comments:

Post a Comment