Java tutorial
/* Cirrostratus: Platform independent SOQL Editor for use with SalesForce and Dreamforce cloud databases Copyright (C) 2011 Steve S Gee Jr <ioexcept@gmail.com> Jim Daly <thejamesdaly@gmail.com> Bryan Leboff <leboff@gmail.com> http://cirrostratus.sourceforge.net/ 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 3 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, see <http://www.gnu.org/licenses/gpl-3.0.html>. */ package org.geefive.salesforce.soqleditor; import com.sforce.soap.partner.*; import com.sforce.soap.partner.fault.*; import com.sforce.soap.partner.sobject.*; import com.sforce.ws.ConnectorConfig; import com.sun.xml.bind.api.JAXBRIContext; import com.sun.xml.ws.api.message.Headers; import com.sun.xml.ws.developer.WSBindingProvider; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.namespace.QName; import javax.xml.ws.BindingProvider; import javax.xml.ws.WebServiceException; import javax.xml.ws.handler.MessageContext; import javax.xml.ws.soap.SOAPFaultException; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.NameValuePair; import org.apache.commons.httpclient.cookie.CookiePolicy; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.*; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class RESTfulQuery { private final String REST_QUERY = "/services/data/v20.0/query"; private final String REST_LOGIN = "/services/data/v20.0/sobjects"; private String INSTANCE_ENDPOINT = null; private final String PRODUCTION_ENDPOINT = "https://login.salesforce.com/services/Soap/u/22.0"; private final String DEVELOPMENT_ENDPOINT = "https://test.salesforce.com/services/Soap/u/22.0"; private String SID = ""; private String fullServerURL = ""; private String serverDomain = ""; // private String username = "cet.xoom@gmail.com"; // private String password = "comcast1d7HhhtepjJzk63WfYElKXvOX"; /* cet.xoom@gmail.com comcast1 d7HhhtepjJzk63WfYElKXvOX steve_gee@cable.comcast.com.smb fire1blade BYQhRhYNQLvdWm0WD4AR8JxCL steve_geejr@cable.comcast.com.cet 1mml0ten EnoNKCqLn73lETlqECR9H5T0 */ private String username = "steve_geejr@cable.comcast.com.cet"; private String password = "1mml0tenEnoNKCqLn73lETlqECR9H5T0"; public RESTfulQuery() { try { login(username, password); executeObjectSearch(); } catch (Exception ex) { ex.printStackTrace(); } } private void login(String userName, String pwd) throws Exception { //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // SoapType port = null; LoginResult loginResponse = null; System.out.println("Executing Enterprise SOAP WSDL Login Call with credentials"); System.out.println("username: " + userName); System.out.println("password: " + pwd); // URL wsdlLocation = this.getClass().getClassLoader().getResource(LOGIN_TARGET_ENDPOINT); // URL wsdlLocation = this.getClass().getClassLoader().getResource(TEST_TARGET_ENDPOINT); // if (wsdlLocation == null) { // WebServiceException e = new WebServiceException("enterprise.wsdl not found!"); // throw e; // } ConnectorConfig config = new ConnectorConfig(); config.setPassword(pwd); config.setUsername(userName); config.setServiceEndpoint(DEVELOPMENT_ENDPOINT); config.setAuthEndpoint(DEVELOPMENT_ENDPOINT); PartnerConnection connector = new PartnerConnection(config); // port = new SforceService(wsdlLocation, new QName("urn:enterprise.soap.sforce.com", "SforceService")).getSoap(); // loginResponse = port.login(userName, pwd); loginResponse = connector.login(userName, pwd); System.out.println("Login was successfull."); SID = loginResponse.getSessionId(); fullServerURL = loginResponse.getServerUrl(); serverDomain = fullServerURL.substring(0, (fullServerURL.indexOf("services") - 1)); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); System.out.println("Full Server URL: " + fullServerURL); System.out.println("Server Domain: " + serverDomain); System.out.println("The returned session id is: " + loginResponse.getSessionId()); System.out.println("Your logged in user id is: " + loginResponse.getUserId()); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); } // REST_LOGIN public void executeObjectSearch() throws Exception { HttpClient restClient = new HttpClient(); restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); String restfulURLTarget = serverDomain + REST_LOGIN; System.out.println("RESTful URL Target: " + restfulURLTarget); GetMethod method = null; try { method = new GetMethod(restfulURLTarget); System.out.println("Setting authorization header with SID [" + SID + "]"); method.setRequestHeader("Authorization", "OAuth " + SID); // NameValuePair[] params = new NameValuePair[1]; // params[0] = new NameValuePair("q","SELECT Name, Id, Phone, CreatedById from Account LIMIT 100"); // method.setQueryString(params); int httpResponseCode = restClient.executeMethod(method); System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]"); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); System.out .println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); if (httpResponseCode == HttpStatus.SC_OK) { JSONObject response = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); System.out.println("_____________________________________"); System.out.println("RESPONSE [" + response + "]"); JSONArray resultArray = response.getJSONArray("sobjects"); // StringBuffer soqlQueryResults = new StringBuffer(); // String token = ""; JSONObject inner = null; inner = resultArray.getJSONObject(0); Iterator keys = inner.keys(); HashMap columnNames = new HashMap(); while (keys.hasNext()) { String column = (String) keys.next(); if (!column.equalsIgnoreCase("attributes")) { System.out.println("KEY>> " + column); columnNames.put(column, ""); } } System.out.println("____________________________________________________________________"); JSONArray results = response.getJSONArray("sobjects"); // for (int i = 0; i < results.length(); i++) { for (int i = 0; i < 35; i++) { try { if (results.getJSONObject(i).getString("searchable").equals("true")) { String objectName = results.getJSONObject(i).getString("name"); if (objectName.equals("Asset")) { parseObjectDetails(objectName); } // System.out.println("[" + results.getJSONObject(i).getString("custom") + "] " + results.getJSONObject(i).getString("name")); } } catch (NullPointerException ex) { //just looking for nulls ex.printStackTrace(); } } //end for System.out.println("____________________________________________________________________"); /* Iterator keyset = null; JSONArray results = response.getJSONArray("records"); Vector<String> newRow = null; for (int i = 0; i < results.length(); i++) { keyset = columnNames.keySet().iterator(); newRow = new Vector<String>(); while(keyset.hasNext()){ String columnName = (String)keyset.next(); String columnValue = results.getJSONObject(i).getString(columnName); System.out.println(">> COLUMN_VALUE >> " + columnValue); newRow.addElement(columnValue); } soqlResults.addDataRow(newRow); }//end for */ } } finally { method.releaseConnection(); } } private void parseObjectDetails(String object) throws Exception { System.out.println("xxxxxxxxxxxxxxxxxxxxx " + object + " xxxxxxxxxxxxxxxxxxxxx"); HttpClient restClient = new HttpClient(); restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); // Account/describe/ String restfulURLTarget = serverDomain + REST_LOGIN + "/" + object + "/describe/"; System.out.println("RESTful URL Target: " + restfulURLTarget); GetMethod method = null; try { method = new GetMethod(restfulURLTarget); method.setRequestHeader("Authorization", "OAuth " + SID); int httpResponseCode = restClient.executeMethod(method); System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]"); if (httpResponseCode == HttpStatus.SC_OK) { JSONObject response = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); System.out.println("RESPONSE [" + response + "]"); // Iterator rkeys = response.keys(); // while(rkeys.hasNext()){ // String fieldName = (String)rkeys.next(); // System.out.println("KEY>> " + fieldName); // } // // JSONArray fieldObject = response.getJSONArray("fields"); // Iterator<String> fieldIterator = fieldObject.getJSONObject(0).keys(); // HashMap<String,String> fieldNames = new HashMap<String,String> (); // while(fieldIterator.hasNext()){ // String fieldName = fieldIterator.next(); // fieldNames.put(fieldName, ""); // System.out.println("FIELD KEY>> " + fieldName); // } // FIELD KEY>> byteLength // FIELD KEY>> scale // FIELD KEY>> unique // FIELD KEY>> nillable // FIELD KEY>> idLookup // FIELD KEY>> sortable // FIELD KEY>> inlineHelpText // FIELD KEY>> relationshipName // FIELD KEY>> soapType // FIELD KEY>> type // FIELD KEY>> externalId // FIELD KEY>> calculated // FIELD KEY>> calculatedFormula // FIELD KEY>> htmlFormatted // FIELD KEY>> createable // FIELD KEY>> controllerName // FIELD KEY>> picklistValues // FIELD KEY>> writeRequiresMasterRead // FIELD KEY>> name // FIELD KEY>> nameField // FIELD KEY>> length // FIELD KEY>> digits // FIELD KEY>> defaultValue // FIELD KEY>> autoNumber // FIELD KEY>> custom // FIELD KEY>> referenceTo // FIELD KEY>> precision // FIELD KEY>> updateable // FIELD KEY>> caseSensitive // FIELD KEY>> relationshipOrder // FIELD KEY>> label // FIELD KEY>> dependentPicklist // FIELD KEY>> deprecatedAndHidden // FIELD KEY>> defaultValueFormula // FIELD KEY>> filterable // FIELD KEY>> namePointing // FIELD KEY>> defaultedOnCreate // FIELD KEY>> groupable // FIELD KEY>> restrictedPicklist JSONArray fieldObject = response.getJSONArray("fields"); for (int row = 0; row < fieldObject.length(); row++) { System.out.println("name [" + fieldObject.getJSONObject(row).getString("name") + "]"); // System.out.println("nameField [" + fieldObject.getJSONObject(row).getString("nameField") + "]"); System.out.println("length [" + fieldObject.getJSONObject(row).getString("length") + "]"); System.out.println("digits [" + fieldObject.getJSONObject(row).getString("digits") + "]"); System.out.println( "defaultValue [" + fieldObject.getJSONObject(row).getString("defaultValue") + "]"); System.out .println("autoNumber [" + fieldObject.getJSONObject(row).getString("autoNumber") + "]"); System.out .println("calculated [" + fieldObject.getJSONObject(row).getString("calculated") + "]"); if (fieldObject.getJSONObject(row).getString("calculated").equals("true")) System.out.println("calculatedFormula [" + fieldObject.getJSONObject(row).getString("calculatedFormula") + "]"); System.out.println("..............."); } /* JSONArray resultArray = response.getJSONArray("recordTypeInfos"); System.out.println("ARRAY_LENGTH: " + resultArray.length()); JSONObject inner = null; try{ inner = resultArray.getJSONObject(0); }catch(Exception ex){ inner = resultArray.getJSONObject(1); } Iterator keys = inner.keys(); HashMap columnNames = new HashMap(); while(keys.hasNext()){ String column = (String)keys.next(); if(!column.equalsIgnoreCase("attributes")){ System.out.println("KEY>> " + column); columnNames.put(column, ""); } } */ } } finally { method.releaseConnection(); } System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"); } public void executeQuery() throws Exception { Vector soqlResults = new Vector(); HttpClient restClient = new HttpClient(); restClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109); restClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); // String restfulURLTarget = serverDomain + REST_LOGIN; String restfulURLTarget = serverDomain + REST_QUERY; System.out.println("RESTful URL Target: " + restfulURLTarget); GetMethod method = null; try { method = new GetMethod(restfulURLTarget); System.out.println("Setting authorization header with SID [" + SID + "]"); method.setRequestHeader("Authorization", "OAuth " + SID); NameValuePair[] params = new NameValuePair[1]; params[0] = new NameValuePair("q", "SELECT Name, Id, Phone, CreatedById from Account LIMIT 100"); method.setQueryString(params); int httpResponseCode = restClient.executeMethod(method); System.out.println("HTTP_RESPONSE_CODE [" + httpResponseCode + "]"); System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); System.out .println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXECUTING QUERY %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); if (httpResponseCode == HttpStatus.SC_OK) { try { JSONObject response = new JSONObject( new JSONTokener(new InputStreamReader(method.getResponseBodyAsStream()))); System.out.println("_____________________________________"); System.out.println("RESPONSE [" + response + "]"); // Iterator itr = response.keys(); // while(itr.hasNext()){ // String key = (String)itr.next(); // System.out.println("KEY: " + (String)itr.next()); // } JSONArray resultArray = response.getJSONArray("records"); StringBuffer soqlQueryResults = new StringBuffer(); String token = ""; JSONObject inner = null; System.out.println(resultArray.getString(0)); inner = resultArray.getJSONObject(0); Iterator keys = inner.keys(); HashMap columnNames = new HashMap(); while (keys.hasNext()) { String column = (String) keys.next(); System.out.println("KEY>> " + column); columnNames.put(column, ""); soqlQueryResults.append(token + column); token = " * "; } soqlResults.add(soqlQueryResults.toString()); //System.out.println("******* UNCOMMENT ME FOR RELEASE *******"); Iterator keyset = null; JSONArray results = response.getJSONArray("records"); for (int i = 0; i < results.length(); i++) { soqlQueryResults.setLength(0); keyset = columnNames.keySet().iterator(); token = ""; while (keyset.hasNext()) { String columnName = (String) keyset.next(); if (!columnName.equalsIgnoreCase("attributes")) { soqlQueryResults.append(token + results.getJSONObject(i).getString(columnName)); token = " * "; } } // System.out.println("=====>>>>>>> " + soqlQueryResults.toString()); soqlResults.add(soqlQueryResults.toString()); // System.out.println(results.getJSONObject(i).getString("Id") + ", " // + results.getJSONObject(i).getString("Name") + ", " // + results.getJSONObject(i).getString("Phone") // + ", " + results.getJSONObject(i).getString("CreatedById")); } //end for } catch (JSONException jsonex) { throw jsonex; } } } finally { method.releaseConnection(); } Iterator finalData = soqlResults.iterator(); while (finalData.hasNext()) { System.out.println("-||=========>> " + (String) finalData.next()); } System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EXIT %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"); } private void showHelp() { System.out.println("Test Salesforce Spring-11 RESTful API Calls ..."); System.out.println( "NOTE: This currently only works in a sandbox environment, wsdl changes still required for producion"); System.out.println("Execution Example"); System.out.println("______________________________"); System.out.println("java -jar sfdcRestfulExample.jar <username> <password>"); System.out.println("\t* username\t\tYour Sandbox Login ie: john_doe@my.domain.sandbox"); System.out.println("\t* password\t\tYour Normal Password + Your Security Token from your SFDC Sandbox"); System.out.println( "\t** Password example: If your password is 'topsecret' and your Token is '83K2hc012*sj2_JLwkn01"); System.out.println("\t** then the password you will pass in is: 'topsecret83K2hc012*sj2_JLwkn01'"); } public static void main(String args[]) { new RESTfulQuery(); } }