package packageForREST;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
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.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 SampleInsert {
/* ——— 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 baseUri;
Header oauthHeader;
Header prettyPrintHeader = new BasicHeader(“X-PrettyPrint”, “1”);
/* Id of inserted Employee */
private static String employeeId;
private static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
/* Main Method */
public static void main(String[] args) {
new SampleInsert();
}
/* Constructor */
public SampleInsert() {
getLoginCredentials();
this.oauth2Login();
this.insertEmployee();
}
/* 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 insert Employee */
public void insertEmployee() {
String uri = baseUri + “/sobjects/Employee__c/”;
try {
String name;
String age;
JSONObject employee = new JSONObject();
name = getUserInput(“Enter the name: “);
age = getUserInput(“Enter the age: “);
employee.put(“Employee_Name__c”, name);
employee.put(“Age__c”, age);
System.out.println(“nEmployee record to be inserted:n” + employee.toString(1));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(uri);
httpPost.addHeader(oauthHeader);
httpPost.addHeader(prettyPrintHeader);
StringEntity body = new StringEntity(employee.toString(1));
body.setContentType(“application/json”);
httpPost.setEntity(body);
HttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
String response_string = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(response_string);
employeeId = json.getString(“id”);
System.out.println(“New Employee id from response: ” + employeeId);
} else {
System.out.println(“Insertion unsuccessful. Status code returned is ” + statusCode);
}
} catch (JSONException e) {
System.out.println(“Issue creating JSON or processing results”);
e.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
}
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 hold user credentials */
class UserCredentials {
String loginInstanceDomain = “na1.salesforce.com”;
String apiVersion = “22”;
String userName = SampleInsert.userName;
String password = SampleInsert.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 user input */
private String getUserInput(String prompt) {
String result = “”;
try {
System.out.print(prompt);
result = reader.readLine();
} 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: “);
}
}
Sample JAVA program to insert record using REST API
Sample Program: