SugarSoap In java

SugarCRM provides Web Services API via the NuSOAP PHP implementation of the SOAP protocol. The SugarSoap API are built using the NuSOAP library and included in the Sugar Community Edition, Sugar Professional Edition and Sugar Enterprise Edition.
This guide leads you through the steps of creating sugarsoap clients stubs In java using Xfire .Codehaus XFire is a next-generation java SOAP framework. We will use it to consume the SugarSoap webservice in Java clients.

1- Locate The SugarSoap WSDL file:

This guide suppose you already have a working sugarcrm installation. If you don’t have one, download and install the free Sugar Community Edition . Refer to section Installing and Upgrading Sugar to guide you through the installation procedure.
For example, In my Linux machine I unpacked the Sugar Community Edition 5.5.0 bundle into my apache server web apps directory ‘/srv/www/htdocs/SugarCE-Full-5.5.0’ . After completing the installation, I access my local sugarcrm application by browsing to URL : http://localhost/SugarCE-Full-5.5.0/. This URL could vary depending on your own choices of server, host and port. For the rest of this guide I’ll use the reference $sugar_base_url to refer to the base URL you use to access your sugarcrm installation (for me, $sugar_base_url =http://localhost/SugarCE-Full-5.5.0/ ).

The SugarSoap WSDL (Web Services Description Language) is located at:
$sugar_base_url/soap.php?wsdl

in my case it’s located at http://localhost/SugarCE-Full-5.5.0/soap.php?wsdl . Mark well this sugarsoap WSDL URL because we will need it for generating the sugarsoap clients stubs.

2- Getting XFire and other libraries:

To use Xfire we need the necessary library files. Go to xfire web site download page and download the file xfire-distribution-x.x.x.zip ( replace ‘x.x.x’ by the version number .the latest xfire version is xfire-distribution-1.2.6.zip at the time of writing this guide).
unzip it in a local folder. add the xfire-all-1.2.6.jar file from the distribution and its lib directory into your project classpath.
If you are using eclipse IDE, you can get the Xfire Eclipse plugin which is a nice and easy to use tool for generating Xfire clients stubs from WSDL files.

3.Generating SugarSoap Clients stubs with Xfire:

Ant is a useful and flexible tool to automate the building of your java project. Most java IDE generates a build.xml file for you , so why not use Ant to generate our sugarsoap clients stubs?

Edit your build .xml file and add the following ant target at the end of the file :

<target name="wsGen">

        <!-- Replace ${basedir} by your project base directory  and ${sugar_base_url} by your sugar URL (ex : http://localhost/SugarCE-Full-5.5.0-->

        <property name="dependencyfinder.home" value="${basedir}"/>
        <path id="dependencyfinder">
            <pathelement location="${basedir}/lib"/>
            <fileset dir="${basedir}/lib">
                <include name="**/*.jar"/>
            </fileset>
        </path>

        <taskdef name="wsgen">
                 classname="org.codehaus.xfire.gen.WsGenTask"
                 classpathref="dependencyfinder"/>

        <wsgen overwrite="true"
               package="com.sun.star.addon.sugarcrm.sugarsoap"
               outputDirectory="${basedir}/src"
               wsdl="${sugar_base_url}/soap.php?wsdl"
               />
    </target>

${basedir}/lib points to the directory where you copied all your xfire distribution jar files and xfire distribution lib folder jars.

From your command line change to your build.xml file directory and run command :

$ ant wsGen

this will generate the SugarSoap clients stubs under src directory in java package : com.sun.star.addon.sugarcrm.sugarsoap
package com.sun.star.addon.sugarcrm.sugarsoap holds the main sugarsoap java stubs classes mainly the class Sugarsoap

4.Writing a SugarSoap Java client:

Now it’s time to write a simple java client to test our sugarsoap service. Below is a java code snippet that demonstrates how to login to your sugarcrm web application :

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.rpc.ServiceException;
import com.sun.star.addon.sugarcrm.sugarsoap.Sugarsoap;
import com.sun.star.addon.sugarcrm.sugarsoap.SugarsoapLocator;
import com.sun.star.addon.sugarcrm.sugarsoap.SugarsoapPortType;

public class SugarTest {

	Sugarsoap service = new SugarsoapLocator();
	SugarsoapPortType soap = null;
	public static void main(String[] arg) {

		try {
			soap = service.getsugarsoapPort(new URL("http://localhost/SugarCE-Full-5.5.0/"));
			String session = soap.login("your username", "your password",
					" sugarsoap test");
			if (session == null)
				System.err
						.println("there was an error connecting to sugarcrm service");
			else
				System.out
						.println("login to sugar service successfull. sessionId="
								+ session);

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			_logger.error(e);
			return;

		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			_logger.error(e);
			return;

		}

	}

	/**
	 * Logs the user into the Sugar application.
	 *
	 * @param username
	 * @param password
	 * @param application
	 * @return sugar session id
	 */
	String login(String username, String password, String application) {

		Set_entry_result loginRes = null;
		String session = null;

		try {

			_logger.info("connecting to " + this.sugarURL + " as " + username);
			User_auth user_auth = new User_auth(username,
					MD5.getHashString(password), "1");
			loginRes = this.soap.login(user_auth, application);

			if (loginRes == null) {
				// null result means something wrong went with authentication
				return null;
			}
			session = loginRes.getId();
			String userid = this.soap.get_user_id(session.getId());
			boolean error = (!loginRes.getError().getNumber().equals("0"));

			if (error) {

				if (userid == "-1") {
					String text = "Error connecting to "
							+ this.sugarURL
							+ ": Connection is available, but SOAP is not responsive due to PHP configuration.";
					_logger.error("Error initializing connection:" + text);

					return null;

				}

				_logger.error("sugar login error :"
						+ loginRes.getError().getNumber() + " "
						+ loginRes.getError().getName() + " "
						+ loginRes.getError().getDescription());
				return null;

			} else {
				// sugar login successful
				_logger.info("login to sugar application successful");

			}

		} catch (Exception e) {

			// Caught an unexpected exception!
			_logger.error(e.getMessage(), e);
			return null;

		}
		return session;
	}

}

this snippet simply create a service instance and use it to create a soap Object instance. soap Object is the entry class for all sugarsoap methods.
The login() method snippet describe how to connect to your sugarcrm instance and returns the sugar session id if login is successfull.Note that you need to encode your sugar password using the MD5 algorithm.

5.Conclusion:

Once you complete the previous steps in setting up sugarsoap java stubs clients with xfire, you can start exploring and using the power of the sugarcrm services by calling the various sugarsoap API methods .
xfire is not the only java webservice library to generate sugarsoap client. you can also use other java webservice tools like axis and CXF and others. in a comming post I’ll describe a simple method to generate sugarsoap client using eclipse IDE and axis2.
The supported calls in the official sugarsoap API are listed and described in this section of the Sugar Developer Guide: Web Services

SugarCRM and Java Integration : Introduction

Overview Of The SugarCRM Platform:

SugarCRM is a widely adopted Customer Relationship Management System. the product is basically built on the LAMP (Linux, Apache, MySQL & PHP) open source stack. However, ever since the version 4.5 release in August 2006, the application also runs reasonably well on Microsoft’s Windows Server operating system and SQL Server database.
SugarCRM is released under the Mozilla Public License and the GNU-GPL license and has taken a lead among the approximately 20 open source CRM applications.

In my opinion SugarCRM company Has adopted a modern philosophy in software development .The company opted for a strategy to open their technology to complementors and create economic incentives (such as free or low licensing fees, or financial subsidies) for other firms to join their CRM ecosystem and adopt the SugarCRM platform technology as their own. In fact SugarCRM firm followed two main strategies in their software development model .The first strategy is based on the mantra of “free, but not free”. SugarCRM give one part of the system away to some users (community or the general consumer) but charge others (corporate users). However it seems they didn’t opted for the strategy of “open, but “not open” make access to the interfaces easily available but keep critical parts of the technology proprietary or very distinctive. Instead they choose to give complete access to the underlying source code , allowing clients & companies to customize, integrate and extend the SugarCRM application with in-house technical resources to control their own requirements.

By looking to their SugarForge.org web site, you can see the wealth of projects that have been developed as extensions or Integrations to the SugarCRM system. Available source code, good documentation, training programs and a relatively active community provide the hallmarks for a successful open source effort.

SugarCRM Integration:

While the core of SugarCRM application is designed to manage a Company’s Customer Relationship, it is very likely that at some points the company might feel the need to do some integration with its CRM system. For example it might integrate its phone system to automatically make entries to SugarCRM when inbound or outbound calls have been made, connect registration of a web application with sugar system to create new accounts automatically to SugarCRM, connect a LIMS in various ways to Sugar ..and so on…

I had the chance to be involved in a project to Integrate SugarCRM with OpenOffice.org suite applications using the Java Programming language. This project was first funded by Appinux.com who hired me to develop a “OpenOffice Addon for SugarCRM. The project is open sourced and freely available to sugarCRM community.
Unfortunately -due to funding limitations-I could only release a minimal version of the plugin which I’m hosting at sourceforge.net : “OpenOffice Addon for SugarCRM
I’m now in charge of the project & have future plans to enhance it with more features and better design. Due to luck of funding and limitation of time, my progress might be slow in this project . but i’m committed to bring it to a decent degree of maturity in future. Of-course Java Developers are welcome to join the project if they are interested!

This being said , I’m planning to blog every now and then about the “OpenOffice Addon for SugarCRM project ; covering topics on SugarSoap API , Sugar and Java Integration , Sugar and OpenOffice Integration and other topics that might raise interesting during the ongoing project development process.

In the next article I’ll introduce the SugarSoap In Java Tutorial. SugarSoap is the SOAP Based SugarCRM webservice which enables Java developers to connect to Sugarcrm and interface with the variety of sugar services exposed by SugarSoap API.