You can access Salesforce from Java using web services allowing you to integrate external systems with your Salesforce instance. There are two main WSDLs you’ll be interested in for this: the enterprise WSDL and the partner WSDL. The partner version as the name suggests, is designed for partners or people writing for multiple organizations. This version is more generic compared to the enterprise version which provides access to the database objects directly with all the field names and types you have defined. Both provide the same core functionality so if you’re only writing for one organization, you’ll generally use the enterprise version.
The first thing you need to do is download a copy of the WSDL file. To do this, go to setup, Develop, API. Here you’ll see a link to “Generate Enterprise WSDL”, click that link and you’ll see a screen to set the version of any installed packages and a Generate button which will create the file for you. You’ll probably see it rendered as an xml file you can right click on this, view source and save the file.
I use Eclipse for my Java development (version 3.4.1 with web standard tools) and I discovered an issue with the default client code generation in that it doesn’t seem to generate complex type arrays correctly. Not many of the API calls require this so unless you use something like
emptyRecycleBin() which works on an array of
IDs you might not even notice.
To use the standard tools, import the WSDL into a project, right click on it select Web Services, Generate Client. You’ll get a new package generated with the services you need to access Salesforce. If you run into the issue I did or need an alternative client generation, you can use Apache Axis2. Download the latest version, read the creating clients section of the docs (basically run the
bin\WSDL2Java script specifying the WSDL and the client form you want) and import the code generated into your IDE. I’d choose the ADB mapping – it’s much simpler to deal with than XML beans and generates far fewer files for you to deal with.
Before you can do anything with your organization, you need to login. To do this, create a Service Stub, setup your login object and call the Stub login method. Get your session id from the login response and use it to setup your session header. Once you’re logged in, you need to use the endpoint provided in the login response for future calls so create a new stub with this URL and then you’re free to use the API calls you need.
Here’s a basic code stub to show you how that works:
SforceServiceStub stub = new SforceServiceStub(); Login login = new Login(); LoginScopeHeader lsh = new LoginScopeHeader(); login.setUsername("YOUR USERNAME"); login.setPassword("YOUR PASSWORD"); LoginResponse lr = stub.login(login, null); SessionHeader sh = new SessionHeader(); sh.setSessionId(lr.getResult().getSessionId()); System.out.println("Logged in!"); SforceServiceStub runStub = new SforceServiceStub(lr.getResult().getServerUrl());