SalesForce Integration

Salesforce integration code in java. You can jar this code and use this from coldfusion to communicate with salesforce.

Salesforce integration code in Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Vector;
import javax.xml.rpc.ServiceException;
import org.apache.axis.message.MessageElement;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.w3c.dom.Element;
import com.sforce.soap.partner.*;
import com.sforce.soap.partner.DeleteResult;
import com.sforce.soap.partner.DescribeGlobalResult;
import com.sforce.soap.partner.DescribeLayout;
import com.sforce.soap.partner.DescribeLayoutItem;
import com.sforce.soap.partner.DescribeLayoutResult;
import com.sforce.soap.partner.DescribeLayoutRow;
import com.sforce.soap.partner.DescribeLayoutSection;
import com.sforce.soap.partner.DescribeSObjectResult;
import com.sforce.soap.partner.DescribeSoftphoneLayoutCallType;
import com.sforce.soap.partner.DescribeSoftphoneLayoutInfoField;
import com.sforce.soap.partner.DescribeSoftphoneLayoutItem;
import com.sforce.soap.partner.DescribeSoftphoneLayoutResult;
import com.sforce.soap.partner.DescribeSoftphoneLayoutSection;
import com.sforce.soap.partner.DescribeTab;
import com.sforce.soap.partner.DescribeTabSetResult;
import com.sforce.soap.partner.Field;
import com.sforce.soap.partner.FieldType;
import com.sforce.soap.partner.GetDeletedResult;
import com.sforce.soap.partner.GetUpdatedResult;
import com.sforce.soap.partner.GetUserInfoResult;
import com.sforce.soap.partner.LeadConvert;
import com.sforce.soap.partner.LeadConvertResult;
import com.sforce.soap.partner.LoginResult;
import com.sforce.soap.partner.MergeRequest;
import com.sforce.soap.partner.MergeResult;
import com.sforce.soap.partner.PicklistEntry;
import com.sforce.soap.partner.ProcessRequest;
import com.sforce.soap.partner.ProcessResult;
import com.sforce.soap.partner.ProcessSubmitRequest;
import com.sforce.soap.partner.ProcessWorkitemRequest;
import com.sforce.soap.partner.QueryOptions;
import com.sforce.soap.partner.QueryResult;
import com.sforce.soap.partner.ResetPasswordResult;
import com.sforce.soap.partner.SaveResult;
import com.sforce.soap.partner.SearchRecord;
import com.sforce.soap.partner.SearchResult;
import com.sforce.soap.partner.SessionHeader;
import com.sforce.soap.partner.SetPasswordResult;
import com.sforce.soap.partner.SforceServiceLocator;
import com.sforce.soap.partner.SoapBindingStub;
import com.sforce.soap.partner.UndeleteResult;
import com.sforce.soap.partner.UpsertResult;
import com.sforce.soap.partner.fault.ApiFault;
import com.sforce.soap.partner.fault.InvalidQueryLocatorFault;
import com.sforce.soap.partner.fault.LoginFault;
import com.sforce.soap.partner.fault.UnexpectedErrorFault;
import com.sforce.soap.partner.sobject.SObject;
import com.sforce.soap.partner.AssignmentRuleHeader;

public class SalesForcePartnerAPI {
	public static void main(String[] args) {
		SalesForcePartnerAPI sfpObj = new SalesForcePartnerAPI();

		sfpObj.login("yourLogin@domain.com", "passworddYmtLvyz6TR4FVSoLCIdeBEmis");
		sfpObj.setDebug("yes");

		// sfpObj.getMappings("Account");
		// sfpObj.getMappings("Contact");
		// sfpObj.getMappings("Case");
		sfpObj.getMappings("Lead");
		// sfpObj.getMappings("Warranty_reg__c");
		// sfpObj.getMappings("Warranty_Equipment__c");

		// get all objects and relevant mappings
		// String[] tempObjects = sfpObj.getAllObjects(); if (!(tempObjects == null)) { for (int i = 0; i < tempObjects.length; i++) { sfpObj.getMappings(tempObjects[i].trim()); } }

		String strTemp = "";
		String opCompare = "like"; // like or equalto

		// Account
		strTemp = "Id=|Name=test10 account name 1|";
		// sfpObj.getRecord("Account", strTemp, opCompare);
		// sfpObj.checkRecord("Account", strTemp, opCompare);
		// sfpObj.upsertRecord("Account", strTemp);

		// Contact
		strTemp = "Id=|LastName=test10 contact last name 1|";
		// sfpObj.getRecord("Contact", strTemp, opCompare);
		// sfpObj.checkRecord("Contact", strTemp, opCompare);
		// sfpObj.upsertRecord("Contact", strTemp);

		// Case
		strTemp = "Id=|SuppliedName=test13 case SuppliedName 1|";
		// sfpObj.getRecord("Case", strTemp, opCompare);
		// sfpObj.checkRecord("Case", strTemp, opCompare);
		// sfpObj.upsertRecord("Case", strTemp);

		// Lead
		// strTemp = "Id=|LastName=test13 contact last name 1|company=test13|";
		// strTemp = "Id=|FirstName=Drew - form test
		// 5|LastName=sqa|Company=test|Email=test@test.com|Phone=123 456 7890| Description=Verify software|";
		//strTemp = "Id=|FirstName=testJul10_008 fn's|LastName=testJul10_008 ln's|Company=testJul10_008|Email=testJul10_008@test.com|Phone=1234567890|";
		 strTemp = "Id=|LastName=%Ketan's%|Company=|Email=|";
		try {
			sfpObj.getRecord("Lead", strTemp, opCompare);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		// strTemp = "FirstName=test| LastName=test |abc__CurrentGenerators__c=dfsrCustomPost | Company=test |";
		// sfpObj.getRecord("Lead", strTemp, opCompare);
		// sfpObj.checkRecord("Lead", strTemp, null);
		//sfpObj.upsertRecord("Lead", strTemp);

		// //////////////////
		// custom objects //
		// //////////////////
		opCompare = "equalto"; // cannot retrieve mutiple records for custom
		// objects

		// Warranty_reg__c
		// strTemp =
		// "Id=|Account__c=0015000000HupPPAAZ|Installer__c=0035000000O4NekAAF|Date_of_Installation__c=2007-02-01|";
		// sfpObj.getRecord("Warranty_reg__c", strTemp, opCompare);
		// sfpObj.checkRecord("Warranty_reg__c", strTemp, opCompare);
		// sfpObj.upsertRecord("Warranty_reg__c", strTemp);

		// Warranty_Equipment__c
		// strTemp =
		// "Id=|Warranty_Registration__c=a0R500000001j0EEAQ|Model_Number__c=test10
		// Warranty_Registration__c model number 1|Serial_Number__c=test10
		// Warranty_Registration__c serial number 1|";
		// sfpObj.getRecord("Warranty_Equipment__c", strTemp, opCompare);
		// sfpObj.checkRecord("Warranty_Equipment__c", strTemp, opCompare);
		// sfpObj.upsertRecord("Warranty_Equipment__c", strTemp);

		if (sfpObj.isDebug) {
			System.out.println("-- done");
		}
	}

	private SoapBindingStub binding;
	private LoginResult loginResult = null;
	private String un = null;
	private String pwd = null;
	private boolean loggedIn = false;
	private GetUserInfoResult userInfo = null;
	private String[] tasks = null;
	private String PARTNER_SOBJECT_NS = "urn:sobject.partner.soap.sforce.com";
	private boolean logOn = false;
	private boolean isDebug = false;

	public SalesForcePartnerAPI() {
	}

	public String login(String un, String pwd) {
		String retVal = "";

		try {
			isDebug = false;
			loggedIn = false;
			this.un = un.trim();
			this.pwd = pwd.trim();

			binding = (SoapBindingStub) new SforceServiceLocator().getSoap();
			binding.setTimeout(60000);
			loginResult = binding.login(this.un, this.pwd);

			// set the session header for subsequent call authentication
			binding._setProperty(SoapBindingStub.ENDPOINT_ADDRESS_PROPERTY, loginResult.getServerUrl());

			// Create a new session header object and set the session id to that
			// returned by the login
			SessionHeader sh = new SessionHeader();
			sh.setSessionId(loginResult.getSessionId());
			binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "SessionHeader", sh);

			// Use the following in your login method, before you make your
			// login call to the service. set the call option for client id and
			// bind it to the current soap session
			// String clientID = "KetanJetty/";
			// CallOptions co = new CallOptions();
			// co.setClient(clientID);
			// binding.setHeader("SforceService", "CallOptions", co);

			setAssignmentRules();

			// assignrule.useDefaultRule = True
			// binding.AssignmentRuleHeaderValue = assignrule
			// 'end setting bindings to use current rules

			loggedIn = true;

			// retVal = loginResult.getUserId().getValue();
			retVal = loginResult.getUserId();
		} catch (Exception ex) {
			ex.printStackTrace();
			retVal = "Error [SalesForce]: " + retVal + ex.toString();
			System.err.println(retVal);
		}

		// System.out.println(retVal);
		return retVal;
	}

	public void setAssignmentRules() {

		/*
		 * // lead assignment rules AssignmentRuleHeader arh = new AssignmentRuleHeader(); binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "AssignmentRuleHeader", arh); arh.setUseDefaultRule(new Boolean(true));
		 */

		try {
			String asgnRule = "Test Assignment Rule";
			QueryResult ar = binding.query("SELECT Id FROM AssignmentRule");
			for (int i = 0; i < ar.getSize(); i++) {

				SObject temp = ar.getRecords(i);

				// AssignmentRule rule = (AssignmentRule)ar.getRecords(i);
				// logger.debug("\tID: " + rule.getId() + " Name: " +
				// rule.getName()
				// + " Type: " + rule.getRuleType());
			}

			AssignmentRuleHeader arh = new AssignmentRuleHeader();
			arh.setUseDefaultRule(new Boolean(true));
			// arh.setAssignmentRuleId(ar.getRecords(0).getId());
			binding.setHeader(new SforceServiceLocator().getServiceName().getNamespaceURI(), "AssignmentRuleHeader", arh);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

	}

	public void setDebug(String val) {
		isDebug = false;
		if (val != null) {
			if (val.trim().equalsIgnoreCase("1") || val.trim().equalsIgnoreCase("yes") || val.trim().equalsIgnoreCase("true")) {
				isDebug = true;
			}
		}
	}

	public String[] getMappings(String type) {
		String[] sourceVal = new String[10000];
		String[] retVal = null;

		try {
			DescribeSObjectResult[] rslts = binding.describeSObjects(new String[] { type });

			int k = 0;
			for (int i = 0; i < rslts.length; i++) {
				Field[] flds = rslts[i].getFields();

				for (int j = 0; j < flds.length; j++) {
					if (flds[j].isUpdateable()) {
						sourceVal[k] = rslts[i].getLabel() + "|" + flds[j].getName() + "|" + flds[j].getLabel();
						k++;

						if (isDebug) {
							System.out.println(rslts[i].getLabel() + " [" + rslts[i].getName() + "]: " + flds[j].getLabel() + " [" + flds[j].getName() + "]");
						}
					}
				}
			}

			// resize the array
			retVal = new String[k];
			System.arraycopy(sourceVal, 0, retVal, 0, k);
			sourceVal = null;
		} catch (Exception ex) {
			ex.printStackTrace();
			System.err.println("Error [SalesForce]:" + ex.getMessage());
		}

		return retVal;
	}

	private MessageElement newMessageElement(String name, Object value) throws Exception {
		MessageElement me = new MessageElement("", name.trim()); // , value);
		me.setObjectValue(value);
		Element e = me.getAsDOM();
		e.removeAttribute("xsi:type");
		e.removeAttribute("xmlns:ns1");
		e.removeAttribute("xmlns:xsd");
		e.removeAttribute("xmlns:xsi");
		me = new MessageElement(e);
		return me;
	}

	private String getFieldValue(MessageElement[] value, String name) {
		for (int i = 0; i < value.length; i++) {
			if (value[i].getName().toLowerCase().equals(name.toLowerCase()))
				return value[i].getValue();
		}
		return " ";
	}

	public String createDynamicSql(String recordType, String dataKeyValues, String comparer) {
		String retVal = "";
		StringBuffer sb = new StringBuffer();
		SimpleDateFormat sdf = null;
		Date tempDate = null;
		Date tempDate2000 = null;
		boolean putAND = false;

		String[] avoidKeys = { "Description" };

		try {
			if (dataKeyValues != null && dataKeyValues.length() > 0) {
				sdf = new SimpleDateFormat("yyyy-MM-dd");
				tempDate2000 = sdf.parse("2000-01-01");
				String[] aryKeyValues = dataKeyValues.split("\\|");
				sb.append("select ");

				if (dataKeyValues != null && dataKeyValues.length() > 0) {
					for (int j = 0; j < aryKeyValues.length; j++) {
						if (aryKeyValues[j].length() > 0 && aryKeyValues[j].indexOf("=", 0) > 0) {
							String[] aryKeyValue = aryKeyValues[j].split("\\=");
							if (aryKeyValue != null) {
								// System.out.println(aryKeyValue[0].toString());
								for (int k = 0; k < avoidKeys.length; k++) {
									if (!aryKeyValue[0].toString().trim().equalsIgnoreCase(avoidKeys[k].toString().trim())) {
										if (j > 0) {
											sb.append(", ");
										}

										sb.append(aryKeyValue[0]);
									}
								}
							}
						}
					}
				}

				sb.append(" from " + recordType + " where ");

				// System.out.println(sb.toString());

				for (int i = 0; i < aryKeyValues.length; i++) {
					if (aryKeyValues[i].length() > 0 && aryKeyValues[i].indexOf("=", 0) > 0) {
						String[] aryKeyValue = aryKeyValues[i].split("\\=");
						if (aryKeyValue != null) {
							for (int k = 0; k < avoidKeys.length; k++) {
								if (!aryKeyValue[0].toString().trim().equalsIgnoreCase(avoidKeys[k].toString().trim())) {

									if (aryKeyValue.length > 1 && (aryKeyValue[0].trim().length() > 0 && aryKeyValue[1].trim().length() > 0)) {
										try {
											tempDate = sdf.parse(aryKeyValue[1].trim());
										} catch (Exception exDate) {
											tempDate = null;
										}

										if (tempDate != null) {
											if (tempDate.after(tempDate2000) && aryKeyValue[1].trim().length() == 10) {
												if (putAND) {
													sb.append(" and ");
												}

												sb.append(aryKeyValue[0] + " = " + aryKeyValue[1]);
											}
										} else {
											if (putAND) {
												sb.append(" and ");
											}

											// escape the single quote
											String tempAryKeyValue1 = aryKeyValue[1].toString().trim();

											if (tempAryKeyValue1.contains("'")) {
												tempAryKeyValue1 = tempAryKeyValue1.replaceAll("'", "\\\\'");
											}

											if (comparer != null && comparer.trim().equalsIgnoreCase("like")) {
												sb.append(aryKeyValue[0] + " like '" + tempAryKeyValue1 + "%'");
											} else {
												sb.append(aryKeyValue[0] + " = '" + tempAryKeyValue1 + "'");
											}
										}

										putAND = true;
									}

								}
							}
						}
					}
				}

				retVal = sb.toString();
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retVal = "Error [SalesForce]: " + retVal + ex.toString();
			System.err.println(retVal);
		}

		if (isDebug) {
			System.out.println("from createDynamicSql(): " + retVal);
		}

		return retVal;
	}

	public String getRecord(String recordType, String dataKeyValues, String comparer) throws Exception {
		String retVal = "";
		StringBuffer sb = new StringBuffer();

		try {
			if (dataKeyValues != null && dataKeyValues.trim().length() > 0) {
				String strSqlSelect = createDynamicSql(recordType, dataKeyValues, comparer);
				QueryResult qr = binding.query(strSqlSelect);

				if (qr.getSize() > 0) {
					for (int i = 0; i < qr.getRecords().length; i++) {
						SObject sobj = qr.getRecords(i);
						if (i > 0) {
							sb.append("|");
						}

						if (dataKeyValues != null && dataKeyValues.length() > 0) {
							String[] aryKeyValues = dataKeyValues.split("\\|");

							for (int j = 0; j < aryKeyValues.length; j++) {
								if (aryKeyValues[j].length() > 0 && aryKeyValues[j].indexOf("=", 0) > 0) {
									String[] aryKeyValue = aryKeyValues[j].split("\\=");
									if (aryKeyValue != null) {
										sb.append(recordType + aryKeyValue[0] + "=" + getFieldValue(sobj.get_any(), aryKeyValue[0]) + ";");
									}
								}
							}
						}
					}
				}
			}

			retVal = sb.toString();
		} catch (Exception ex) {
			ex.printStackTrace();
			retVal = "Error [SalesForce]: " + retVal + ex.toString();
			System.err.println(retVal);
		}

		if (isDebug) {
			System.out.println("from getRecord(): " + retVal);
		}

		return retVal;
	}

	public String checkRecord(String recordType, String dataKeyValues, String comparer) throws Exception {
		String retVal = "";

		try {
			if (dataKeyValues != null && dataKeyValues.trim().length() > 0) {
				String strSqlSelect = createDynamicSql(recordType, dataKeyValues, comparer);
				QueryResult qr = binding.query(strSqlSelect);

				if (qr.getSize() > 0) {
					for (int i = 0; i < qr.getRecords().length; i++) {
						SObject sobj = qr.getRecords(i);

						if (dataKeyValues != null && dataKeyValues.length() > 0) {
							String[] aryKeyValues = dataKeyValues.split("\\|");

							for (int j = 0; j < aryKeyValues.length; j++) {
								if (aryKeyValues[j].length() > 0 && aryKeyValues[j].indexOf("=", 0) > 0) {
									String[] aryKeyValue = aryKeyValues[j].split("\\=");
									if (aryKeyValue != null) {
										// sb.append(recordType + aryKeyValue[0]
										// + "=" + getFieldValue(sobj.get_any(),
										// aryKeyValue[0]) + ";");

										if (aryKeyValue[0].trim().equalsIgnoreCase("id")) {
											retVal = getFieldValue(sobj.get_any(), aryKeyValue[0]);
										}
									}
								}
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retVal = "Error [SalesForce]: " + retVal + ex.toString();
			System.err.println(retVal);
		}

		if (isDebug) {
			System.out.println("from checkRecord(): " + recordType + " " + retVal);
		}

		return retVal;
	}

	public String upsertRecord(String recordType, String dataKeyValues) {
		String retVal = "";
		MessageElement[] me = null;
		SObject[] newSObject = null;
		SaveResult[] sr = null;

		try {
			if (dataKeyValues != null && dataKeyValues.trim().length() > 0) {
				String[] aryKeyValues = dataKeyValues.split("\\|");
				me = new MessageElement[aryKeyValues.length];

				for (int i = 0; i < aryKeyValues.length; i++) {
					if (aryKeyValues[i].trim().length() > 0 && aryKeyValues[i].indexOf("=", 0) > 0) {
						String[] aryKeyValue = aryKeyValues[i].split("\\=");
						if (aryKeyValue != null) {
							if (aryKeyValue.length > 1 && (aryKeyValue[0].trim().length() > 0 && aryKeyValue[1].trim().length() > 0)) {
								me[i] = newMessageElement(aryKeyValue[0], aryKeyValue[1]);
							} else if (aryKeyValue[0].trim().length() > 0) {
								me[i] = newMessageElement(aryKeyValue[0], "");
							}
						}
					}
				}

				// String result = getRecord(recordType, dataKeyValues, null);
				String result = checkRecord(recordType, dataKeyValues, null);
				retVal = result;

				if (result != null && result.trim().length() == 0) {
					newSObject = new SObject[1];
					newSObject[0] = new SObject();
					newSObject[0].setType(recordType);
					newSObject[0].set_any(me);

					sr = binding.create(newSObject);

					for (int j = 0; j < sr.length; j++) {
						if (sr[j].isSuccess()) {
							// retVal = recordType + " record is created with an
							// id of: "+ sr[j].getId();
							// retVal = sr[j].getId().getValue();
							retVal = sr[j].getId();
						} else {
							for (int k = 0; k < sr[j].getErrors().length; k++) {
								com.sforce.soap.partner.Error err = sr[j].getErrors()[k];
								retVal = "Error [SalesForce]: " + err.getMessage() + " [" + err.getStatusCode().toString() + "]";
							}
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retVal = "Error [SalesForce]: " + retVal + ex.toString();
			System.err.println(retVal);
		}

		if (isDebug) {
			System.out.println("from upsertRecord(): " + recordType + " " + retVal);
		}

		return retVal;
	}

	public String[] getAllObjects() {
		String[] retVal = new String[0];

		try {
			DescribeGlobalResult describeGlobalResult = binding.describeGlobal();
			if (!(describeGlobalResult == null)) {
				retVal = describeGlobalResult.getTypes();
				if (isDebug) {
					if (!(retVal == null)) {
						for (int i = 0; i < retVal.length; i++) {
							System.out.println(retVal[i]);
						}
					}
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retVal[0] = "Error [SalesForce]: " + retVal + ex.toString();
			System.err.println(retVal);
		}

		return retVal;
	}
}



Ginger CMS
the future of cms, a simple and intuitive content management system ...

ASP.NET MVC Application
best practices like Repository, LINQ, Dapper, Domain objects ...

CFTurbine
cf prototyping engine, generates boilerplate code and views ...

Search Engine LITE
create your own custom search engine for your web site ...

JRun monitor
monitors the memory footprint of JRun engine and auto-restarts a hung engine ...

Validation Library
complete validation library for your web forms ...