The new role of XML in cloud data integration-using XML to integrate Salesforce data with enterprise applications

Source: Internet
Author: User
Keywords Nbsp; xml this one you can
Tags .url api application applications apps business applications change click

Cloud computing: Redefining IT

Cloud computing exploded over the past year, including a variety of applications-such as Salesforce CRM and Google apps-and services-such as Cloud hosted on Amazon elastic Compute EC2 (Amazon ibm®db) 2®, Google App Engine and Salesforce force.com platform. These services are often referred to as platform-as-a-service (PaaS) because they provide a complete platform on which organizations can build and host their IT applications.

common abbreviation


API: Application Programming Interface (Creator programming Interface) HTTPS: Hypertext Transfer Protocol on Secure Sockets Layer (hypertext transmits over secure Sockets Layer) IT: Information Technology (information Marvell) SOAP: Simple Object Access Protocol (Easy objects Access Kyoto) UI: User interface (username Interface) URL: Universal Resource Locator (Universal Resource Locator) XML: Extensible Markup Language (extensible Markup Language)

PaaS products are hosted in a multi-tenant environment, where the hardware and software infrastructure is shared. The purpose of setting these environments is to ensure that each organization's data is isolated in a secure manner from other organizations-like renting an office instead of buying an office without worrying about its maintenance and updating. With PaaS, organizations not only save a lot of costs, but also have unique advantages such as automatic upgrades and 0 maintenance. This model also provides another unique advantage, which is to reduce the risk that IT products often encounter beyond budget and development deadlines.

Salesforce is one of the PaaS providers. The company initially provides managed customer relationship management (CRM) solutions that provide a full range of solutions for common business applications, such as sales, partnership management, and marketing. Using this platform, Salesforce launched Force.com, a complete PaaS, to build custom business applications in the browser or by using the Force.com integrated development Environment (IDE) based on Eclipse. Applications are also tailored to the Apex of a proprietary, Java™-like programming language.

Salesforce allows the use of SOAP to interact with the server, with the advantage that languages and platforms are independent of each other. You can use Web Services Description Language (WSDL) to describe what kind of operation is available on the server. A WSDL document first describes a series of network endpoints called ports, and then defines the XML format for messages or data exchanged with the server.

This example in this article uses the Java API for XML Web Services (JAX). Jax provides a number of tools for simplifying XML and SOAP work, including automatically generating the required objects from a WSDL document and automatically binding XML and Java objects.

Integrated Salesforce and enterprise applications

There are a number of ways to integrate Salesforce and enterprise applications. The first way is to configure a workflow in Salesforce to send a message with the WEB service whenever the data is created, updated, or deleted. This process uses an outbound message WSDL similar to the process of configuring a trigger on a database. Workflow configuration Salesforce to send SOAP messages to a pre-configured URL target at any time when data is created, updated, or deleted. For example, in the mileage example of this article, you can send a mileage report to the internal system as soon as a new report is added.

The second approach provides the ability to interact directly with Salesforce using SOAP Web services. This method uses Salesforce-generated WSDL files that are used by custom WEB services. For this type of integration, Salesforce provides two types of WSDL:

Partner WSDL is loosely typed and can be used in multiple organizations; Partner WSDL is harder to handle because XML must be translated into the correct object representation of the organization. The Enterprise WSDL is strongly typed and bound to a single organization; This makes the WSDL more manageable, but it can only be used for an organization's schema. Again, any change to the object requires the WSDL to be regenerated.

This article shows an integration with Salesforce by extending the example in Force.com workbook (a mileage tracking application). For example, we will use the Enterprise Web Services WSDL.

A security token is required to handle the Salesforce Web. Receive or reset a security token with the Salesforce UI. Click Setup > My Personal information > Reset your security token. Here, you can see an option to reset the security token and send it to your e-mail address, and with the security token, use it with your password to log on. For example, if your password is aaaaaa and the security token is xxxxxxxxxx, you must type aaaaaaxxxxxxxxxx in the password column.

Integrating Salesforce through WEB services

To provide an example of how to use XML integration Salesforce, I developed a sample Java application that can log on to Salesforce, query data, and create new records. All communication with Salesforce is through a secure HTTPS channel. Use the following procedure to establish a Java Web service to integrate Salesforce:

generates Enterprise WSDL documents in Salesforce.

Log in to your company's Salesforce account and click the Setup > Develop > API. Then right-click the WSDL document you want to generate.

generates Java classes and domain objects from WSDL.

For this example, I used the Wsimport tool already contained in the Jax Toolbox. To simplify the process of running wsimport, this example uses the build template, which is also part of the Salesforce example. The Java domain object generated by this tool allows XML documents to be automatically bound to Java objects to simplify communication with the server.

Log on to Salesforce through a Web service.

You must first log in to get a server URL and session ID. The code in Listing 1 shows how to log in.

An important part of logging in is getting the server URL. Salesforce is run on multiple instances, such as na1.salesforce.com or na2.salesforce.com, to improve reliability and performance. Once you log on to the server, you need to use the same URL for all subsequent WEB service calls to maintain session information.


Listing 1. Log on to Salesforce

public void Dologin (string userName, string password) {if (username.length () = 0 | | password.length () = = 0) {throw new RuntimeException ("User name length and/or password length cant be 0 length. \ n ", New IllegalArgumentException (" Invalid Password or User name\n ")); else {try {URL wsdllocation = This.getclass (). getClassLoader (). GetResource ("etc/enterprise.wsdl"); if (wsdllocation = = null) {webserviceexception e = new Webserviceexception ("enterprise.wsdl not found!");//exceptionlogger ( ), E); Throw e; Port = new Sforceservice (wsdllocation, New QName ("urn:enterprise.soap.sforce.com", "Sforceservice")). Getsoap (); catch (Webserviceexception WSE) {//exceptionlogger ("Error Creating Salesface Port", WSE); throw WSE; try {loginresponse = port.login (userName, password);} catch (Exception e) {System.out.println ("Error Logging in" Salesforce.com "+ e); Return; } System.out.println ("Login was successful."); System.out.print ("The Returned session ID is:"); SysTem.out.println (Loginresponse.getsessionid ()); System.out.print ("Your logged in user ID is:"); System.out.println (Loginresponse.getuserid () + "\ n"); System.out.print ("The server URL is:"); System.out.println (Loginresponse.getserverurl () + "\ n"); On a successful login, your should synch set up your sessions ID//and the URL for subsequent calls ....


Once a customer session is established, it is possible to invoke the server and interact with it through a WEB service call. This article describes two of these actions: reading data from the server through a query and adding new records to the server.

Querying Salesforce through WEB services

To query for Salesforce data, you must use a special language called Salesforce Object query Language (SOQL). You can use a SOQL query to search for a specific object or a specific field of an object, which is very similar to a specific field in a SELECT query table. You can also use SOQL queries to count the number of records that meet the query criteria and to make a specific sort of the results.

The best way to familiarize yourself with SOQL is to use Schema Explorer in the force.com IDE (see Figure 1). To open a Schema explorer in a project, you can double-click the Salesforce.schema of the project root. In Schema Explorer, you can browse through all the objects in your organization, and by drilling through the various objects, you can select specific objects or fields to automatically generate a query. You can also include related objects into a query by drilling into a list of child relationships for an object.


Figure 1. Schema Explorer

When you have perfected the SOQL query you want to perform, you can embed it in a WEB service invocation. The result generated by this query is the XML representation of the data. This XML document is automatically bound to the Java domain object that you previously generated with Jax.

For this sample application, just get all the mileage records. The results of this query are then bound to the domain object that was generated at setup time, as shown in Listing 2.


Listing 2. Mileage Search Query Results

public void Getmileagereports (Forcelogin login) throws Unexpectederrorfault, Invalidsobjectfault, Invalididfault, Invalidquerylocatorfault, Malformedqueryfault, invalidfieldfault {queryresult queryresult = login.port. Query ("Select Contact__c, Date__c, Miles__c from Mileage__c "); if (queryresult.getsize () > 0) {list<sobject> records = Queryresult.getrecords (); for (Sobject record:records) { Mileagec Mileagec = (MILEAGEC) record; System.out.println (Mileagec.getmilesc (). GetValue () + "" + MILEAGEC.GETCONTACTC (). GetValue ());}}


One thing to note when writing these queries is to separate the custom objects and fields from the standard objects and fields. Custom objects are custom Salesforce database tables dedicated to an organization. To differentiate between custom objects and fields and standard Salesforce objects with the same name, append a __c to each object name.

The query in Listing 2 gets all the records from the Mileage object. Note that the __c Convention distinguishes custom field names from this mileage object name. After that, you can iterate through the query results and bind them to the Mileagec object, which is a domain object generated from the Enterprise WSDL. The Mileagec object is automatically populated with actual mileage record data.

The previous query returns all the mileage records that tend to exceed the data you need. Fortunately, you can specify a filter condition-for example, a date or a contact-so that you can extract only the subset of records that you want from all records. Suppose you want to find a mileage report with more than 300 mileage, you can change this query to:

Select Name, miles__c from Mileage__c where Miles__c > 300


Another way to filter data is to get only those data that has changed over time. To do this, you can use the Getupdated method instead of running a query that gets the object to update and the start and end times. Getupdated will return all objects that have been modified during the specified time period. The code in Listing 3 returns all the mileage records that have been changed in the last one months.


Listing 3. Get updated mileage Records

GregorianCalendar cal = Port.getservertimestamp (). Gettimestamp (). Togregoriancalendar (); GregorianCalendar calend = (GregorianCalendar) cal.clone (); Cal.add (Gregoriancalendar.month,-1);D atatypefactory datatypefactory = Datatypefactory.newinstance (); Getupdatedresult updatedrecords = port.getupdated ("Mileage", Datatypefactory.newxmlgregoriancalendar (CAL), Datatypefactory.newxmlgregoriancalendar (calend));


getdeleted operations are similar to getupdated. This method has the same method signature as the getupdated and returns all records that were deleted within a certain time period.

Another way to query Salesforce is to use the Salesforce Object Search Language (SOSL). SOSL is similar to text-based search, which enables more free search. With SOSL, you can search for multiple, unrelated objects, even when you don't know which objects contain the data you want, or you can use it to search. Queries made with SOSL can also return multiple unrelated objects.

Listing 4-An example of a SOSL query from the Salesforce Jax sample-is a good example of this approach. The code in Listing 4 queries the contact, leader, and account number of a telephone, showing how to search across multiple unrelated objects.


Listing 4. Phone number search across multiple objects

SearchResult SearchResult = port. Search ("Find {4159017000} in Phone fields returning contacts (ID, phone, firstname, LastName), lead (IDs, phone, FirstName, LastName), account (ID, phone, name) "); List<searchrecord> records = Searchresult.getsearchrecords (); list<contact> contacts = new arraylist<contact> (); List<lead> leads = new arraylist<lead> (); list<account> accounts = new arraylist<account> (); if (records!= null &&!records.isempty ()) {for (Searchrecord recordtype:records) {Sobject record = Recordtype.getrecord (); If (record instanceof contacts) {Contacts.add (contacts) record);} else if (record instanceof leads) {Leads.add (lead) record ); else if (record instanceof account) {Accounts.add);} }


In this example, the search method is used instead of query to execute a SOSL query. The results are mapped to a SearchResults object, and individual records in the search results are then checked to determine their type.

Adding data to Salesforce from the Web

To add data to the Salesforce, you can use the same domain object that is generated from the Enterprise WSDL. These objects are populated like standard objects and then serialized to the server in XML for persistence. One difficulty here is creating relationships between different objects. Suppose you need to add a new mileage record for a particular contact. First, you need to find the contact ID you want to use. In this example, you need to search for a contact named Edna, as shown in Listing 5.


Listing 5. Find a specific contact in a database

queryresult qr = login.port. Query ("Select Id, FirstName, LastName, accountid" + "from the contact where FirstName = ' Edna '") ; String ContactID = null; if (qr.getsize () > 0) {Contact contacts = (Contact) qr.getrecords ()-Get (0); ContactID = Contact.getid (). GetValue ();}


This query provides the ID of the first contact in the list. (In a real application, you may want to do more extensive error checking to ensure that the records are correct.) When you have this user ID, you can save it in a new mileage record, see listing 6.


Listing 6. Create a new mileage record

Mileagec Mileagec = new Mileagec (); GregorianCalendar cal = new GregorianCalendar (); Cal.settime (New Date ()); Xmlgregoriancalendar activitydate = Datatypefactory.newinstance (). Newxmlgregoriancalendar (CAL); Mileagec.setdatec (Sofactory.createmileagecdatec (activitydate)); Mileagec.setmilesc (Sofactory.createmileagecmilesc (New Double (300))); MILEAGEC.SETCONTACTC (SOFACTORY.CREATEMILEAGECCONTACTC (ContactID));


After adding a new mileage record, you then need to invoke the Create method on the Web service to save the record to Salesforce. Note that create accepts a list of objects, allowing you to add a batch of mileage records. Listing 7 shows the code to save the data to Salesforce.


Listing 7. Save a new mileage record to a database

Call the Create method passing the array of tasks as sobjects ArrayList list = new ArrayList (); List.add (MILEAGEC); list<saveresult> saveresults = login.port.create (list); for (Saveresult saveresult:saveresults) {if (saveresult.issuccess ()) {System.out.println ("Saveresult success, id=" + Saveresult.getid ()); else {System.out.println ("Saveresult error");//There were errors during the create call, go through the//errors and write them to the screen list<error> errorlist = Saveresult.geterrors (); for (Error error:errorlist) {System.out.println ("error code is:" + error.getstatuscode (). toString ()); System.out. println ("Error message:" + error.getmessage () + "\ n");}}


The code above is used to save the record to Salesforce and return a list of saved results, which shows whether the save was successful. The error message returned from Salesforce is usually easy to understand, so it's easy to figure out what's going on. However, this simple approach does not ensure that data is correctly saved to Salesforce. For critical data, you can consider automatically saving again until the save succeeds.

In the same way, you can update the data in Salesforce. The easiest way to do this is to query the records you want to change before you import them into an object. You can update this object, and then call the Update method.

Another way to update data is to merge backup records. With a merge operation, you can specify a master record and the records to be merged. In this way, you can update the master record with the data from all the merged records. You can combine three records at once.

Concluding

By leveraging the power of XML, you can easily integrate cloud data into an existing enterprise application. XML provides a common data format that can be converted between different services and languages. This sample application in this article demonstrates how to interact with Salesforce through XML Web services, especially SOAP.

The technology that uses WEB services to integrate local (on-site) applications with cloud data can also be widely used in other applications, from Google Apps to Basecamp. With the integration of cloud services, enterprises and organizations can use existing software inputs to quickly build a wide variety of new applications in the cloud.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.