Java Connector to SugarCRM Webservices

This would a small post will less explanation and more of code snippets (Too  busy to write description and code has proper comments).

Here is my effort to minimize research work in getting started with sugar CRM webservice invocation in java

Original code was taken from https:/ /github.com /amusarra/SugarCRMJavaSOAPClient  and added more functions to it

/**
 *
 */
package com.northalley.sugarcrm;

import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URL;
import java.rmi.RemoteException;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.ServiceFactory;

import org.apache.axis.AxisFault;

import com.sugarcrm.www.sugarcrm.Entry_value;
import com.sugarcrm.www.sugarcrm.Field;
import com.sugarcrm.www.sugarcrm.Get_entry_list_result_version2;
import com.sugarcrm.www.sugarcrm.Get_entry_result_version2;
import com.sugarcrm.www.sugarcrm.Link_field;
import com.sugarcrm.www.sugarcrm.Link_name_to_fields_array;
import com.sugarcrm.www.sugarcrm.Module_list;
import com.sugarcrm.www.sugarcrm.Name_value;
import com.sugarcrm.www.sugarcrm.New_module_fields;
import com.sugarcrm.www.sugarcrm.New_set_entry_result;
import com.sugarcrm.www.sugarcrm.SugarsoapBindingStub;
import com.sugarcrm.www.sugarcrm.SugarsoapLocator;
import com.sugarcrm.www.sugarcrm.User_auth;

/**
 * This implements basic methods which are used commonly
 *
 * @author ashwin kumar
 */
public class SugarCRMSoapDemoClient {
	private static final String END_POINT_URL = "http://localhost/SugarCE/service/v2/soap.php?wsdl";
	private static final String USER_NAME = "admin";
	private static final String USER_PASSWORD = "sugarcrm";
	private static final String APPLICATION_NAME = Class.class.getName();
	private static final Integer TIMEOUT = 6000;

	/**
	 * Main Program
	 *
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		String sessionID = null;

		try {
			// Create a URL end point for the client
			URL wsdlUrl = null;
			if (END_POINT_URL.isEmpty()) {
				wsdlUrl = new URL(new SugarsoapLocator()
						.getsugarsoapPortAddress()
						+ "?wsdl");
			} else {
				wsdlUrl = new URL(END_POINT_URL);
			}

			System.out.println("URL endpoint created successfully!");

			// Create Service for test configuration
			ServiceFactory serviceFactory = ServiceFactory.newInstance();
			Service service = serviceFactory.createService(wsdlUrl,
					new SugarsoapLocator().getServiceName());

			System.out.println("Service created successfully");
			System.out.println("Service Name:"
					+ service.getServiceName().toString());
			System.out.println("Service WSDL:"
					+ service.getWSDLDocumentLocation().toString());

			// Trying to create a stub
			SugarsoapBindingStub binding = new SugarsoapBindingStub(wsdlUrl,
					service);
			binding.setTimeout(TIMEOUT);
			System.out.println("Stub created successfully!");

			/**
			 * Try to login on SugarCRM
			 *
			 * 1) Prepare a MD5 hash password 2) Prepare a User Auth object 3)
			 * Execute login
			 */

			// 1. Prepare a MD5 hash password
			MessageDigest messageDiget = MessageDigest.getInstance("MD5");
			messageDiget.update(USER_PASSWORD.getBytes());

			// 2. Prepare a User Auth object
			User_auth userAuthInfo = new User_auth();
			userAuthInfo.setUser_name(USER_NAME);
			userAuthInfo.setPassword((new BigInteger(1, messageDiget.digest()))
					.toString(16));

			try {
				// 3. Execute login
				Entry_value loginResult = binding.login(userAuthInfo,
						APPLICATION_NAME, null);
				System.out.println("Login Successfully for " + USER_NAME);
				System.out.println("Your session Id: " + loginResult.getId());
				sessionID = loginResult.getId();
			} catch (RemoteException ex) {
				System.out.println("Login failed. Message: " + ex.getMessage());
				ex.printStackTrace();
			}
			// binding.
			// binding.get_available_modules(session);
			// retreiveEntriesByModule(sessionID, binding, "Accounts",new
			// String[]{"name","description"},0,10);
			retreiveEntriesByModule(sessionID, binding, "Leads", new String[] {
					"name", "description", "account_name", "campaign_name",
					"salutation", "first_name", "last_name", "full_name",
					"title", "department", "email1", "email2" }, 0, 10);
			retreiveEntriesByModule(sessionID, binding, "Campaigns",
					new String[] { "name", "description", "assigned_user_name",
							"status", "campaign_type", "expected_cost" }, 0, 10);
			// retreiveModuleFields(sessionID, binding);
			// retreiveModules(sessionID, binding);
			// createAndRetreiveContact(sessionID, binding);

			/**
			 * Logout
			 */
			try {
				binding.logout(sessionID);
				System.out.println("Logout Successfully for " + USER_NAME);
				sessionID = null;
			} catch (RemoteException ex) {
				System.out.println("Login failed. Message: " + ex.getMessage());
				ex.printStackTrace();
			}

		} catch (MalformedURLException ex) {
			System.out.println("URL endpoing creation failed. Message: "
					+ ex.getMessage());
			ex.printStackTrace();
		} catch (ServiceException ex) {
			System.out.println("Service creation failed. Message: "
					+ ex.getMessage());
			ex.printStackTrace();
		} catch (AxisFault ex) {
			System.out.println("AxisFault. Message: " + ex.getMessage());
			ex.printStackTrace();
		}
	}

	/**
	 * Sample to show how to do creation operation using webservice
	 *
	 * @param sessionID
	 * @param binding
	 */
	private static void createAndRetreiveContact(String sessionID,
			SugarsoapBindingStub binding) {
		/**
		 * Create a new Contact
		 *
		 * 1) Setting a new entry 2) Setting up parameters for set_entry call 3)
		 * Creating a name value list array from a hash map. This is not
		 * necessary just more elegant way to initialize and add name values to
		 * an array
		 */
		HashMap<String, String> nameValueMap = new HashMap<String, String>();
		nameValueMap.put("first_name", "Suresh");
		nameValueMap.put("last_name", "Paladugu");
		nameValueMap.put("title", "IT Senior Consultant");
		nameValueMap.put("description", "Test Client SOAP Java");
		nameValueMap.put("email1", "suresh.paladugu@gmail.com");

		// Creating a new Name_value array and adding each map entry as 'name'
		// and 'value'
		Name_value nameValueListSetEntry[] = new Name_value[nameValueMap.size()];
		int i = 0;
		for (Entry<String, String> entry : nameValueMap.entrySet()) {
			Name_value nameValue = new Name_value();
			nameValue.setName(entry.getKey());
			nameValue.setValue(entry.getValue());
			nameValueListSetEntry[i] = nameValue;
			i++;
		}

		// Trying to set a new entry
		New_set_entry_result setEntryResponse = null;
		try {
			setEntryResponse = binding.set_entry(sessionID, "Contacts",
					nameValueListSetEntry);
		} catch (RemoteException e) {
			System.out.println("Set entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Set entry was successful! Contacts Id: "
				+ setEntryResponse.getId());

		/**
		 * Getting an Contacts Entry (the one we just set)
		 */
		Link_name_to_fields_array[] link_name_to_fields_array = null;
		String[] select_fields = null;

		Get_entry_result_version2 getEntryResponse = null;

		// Trying to get entry
		try {
			getEntryResponse = binding.get_entry(sessionID, "Contacts",
					setEntryResponse.getId(), select_fields,
					link_name_to_fields_array);
		} catch (RemoteException e) {
			System.out.println("Get entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Get entry was successful! Response: ");

		// Getting the fields for entry we got.
		Entry_value[] entryList = getEntryResponse.getEntry_list();
		for (int k = 0; k < entryList.length; k++) {
			Entry_value entry = entryList[k];
			Name_value[] entryNameValueList = entry.getName_value_list();
			for (int j = 0; j < entryNameValueList.length; j++) {
				Name_value entryNameValue = entryNameValueList[j];
				// Outputting only non empty fields
				if (!entryNameValue.getValue().isEmpty()) {
					System.out.println("Attribute Name: '"
							+ entryNameValue.getName() + "' Attribute Value: '"
							+ entryNameValue.getValue() + "'");
				}
			}
		}
	}

	/**
	 *
	 * TO get list of values /rows for a given modules based on selection
	 * criteria
	 *
	 * @param sessionID
	 * @param binding
	 * @param moduleName
	 *            TODO
	 * @param select_fields
	 * @param l
	 * @param offset
	 */
	private static void retreiveEntriesByModule(String sessionID,
			SugarsoapBindingStub binding, String moduleName,
			String[] select_fields, int offset, int rowCount) {
		Link_name_to_fields_array[] link_name_to_fields_array = null;

		Get_entry_result_version2 getEntryResponse = null;
		Get_entry_list_result_version2 entryListResultVersion2 = null;

		// Trying to get entry
		try {
			/*
			 * getEntryResponse = binding.get_entry(sessionID,moduleName, null,
			 * select_fields, link_name_to_fields_array);
			 */
			entryListResultVersion2 = binding.get_entry_list(sessionID,
					moduleName, "", "", offset, select_fields,
					link_name_to_fields_array, rowCount, 0);
			// getEntryResponse = binding.get_entries(sessionID, moduleName,
			// null, new String[]{"name","description"},
			// link_name_to_fields_array);

		} catch (RemoteException e) {
			System.out.println("Get entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		System.out.println("Get entry was successful! Response: ");

		// Getting the fields for entry we got.
		Entry_value[] entryList = entryListResultVersion2.getEntry_list();
		for (int k = 0; k < entryList.length; k++) {
			Entry_value entry = entryList[k];
			Name_value[] entryNameValueList = entry.getName_value_list();
			System.out.println();
			for (int j = 0; j < entryNameValueList.length; j++) {
				Name_value entryNameValue = entryNameValueList[j];
				// Outputting only non empty fields
				if (!entryNameValue.getValue().isEmpty()) {
					System.out.print(entryNameValue.getName() + ":"
							+ entryNameValue.getValue() + "    ;   ");
				}
			}
		}
	}

	/**
	 *
	 * To list out all fields of a given module
	 *
	 * @param sessionID
	 * @param binding
	 * @param moduleName
	 */
	private static void retreiveModuleFields(String sessionID,
			SugarsoapBindingStub binding, String moduleName) {
		/**
		 * Create a new Contact
		 *
		 * 1) Setting a new entry 2) Setting up parameters for set_entry call 3)
		 * Creating a name value list array from a hash map. This is not
		 * necessary just more elegant way to initialize and add name values to
		 * an array
		 */

		/**
		 * Getting an Contacts Entry (the one we just set)
		 */
		Link_name_to_fields_array[] link_name_to_fields_array = null;
		String[] select_fields = null;

		Get_entry_result_version2 getEntryResponse = null;
		New_module_fields moduleFields = null;
		// Trying to get entry
		try {
			moduleFields = binding.get_module_fields(sessionID, moduleName,
					select_fields);
		} catch (RemoteException e) {
			// System.out.println("Get entry failed. Message: " +
			// e.getMessage());
			// e.printStackTrace();
		}
		// System.out.println("Get entry was successful! Response: ");

		if (moduleFields != null) {
			for (Field field : moduleFields.getModule_fields()) {
				System.out.print(field.getName() + ",");
			}

			System.out.println("--Link Fields");
			/**
			 * Now get Link Fields
			 */

			for (Link_field linkField : moduleFields.getLink_fields()) {
				System.out.print("[" + linkField.getName() + " : "
						+ linkField.getBean_name() + " : "
						+ linkField.getRelationship() + "],");
			}
		}

	}

	/**
	 * To list out all modules aavailable to given user
	 *
	 * @param sessionID
	 * @param binding
	 */
	private static void retreiveModules(String sessionID,
			SugarsoapBindingStub binding) {
		/**
		 * Create a new Contact
		 *
		 * 1) Setting a new entry 2) Setting up parameters for set_entry call 3)
		 * Creating a name value list array from a hash map. This is not
		 * necessary just more elegant way to initialize and add name values to
		 * an array
		 */

		/**
		 * Getting an Contacts Entry (the one we just set)
		 */
		Link_name_to_fields_array[] link_name_to_fields_array = null;
		String[] select_fields = null;

		Get_entry_result_version2 getEntryResponse = null;
		Module_list moduleList = null;
		// Trying to get entry
		try {
			moduleList = binding.get_available_modules(sessionID);
		} catch (RemoteException e) {
			System.out.println("Get entry failed. Message: " + e.getMessage());
			e.printStackTrace();
		}
		// System.out.println("Get entry was successful! Response: ");

		for (String moduleName : moduleList.getModules()) {
			System.out.println("\n" + moduleName + "{");
			retreiveModuleFields(sessionID, binding, moduleName);
			System.out.println("}");
		}

	}

}

Project code has been checked into

https://linkwithweb.googlecode.com/svn/trunk/CRM/SugarCRM/JavaSOAPClient/SugarCRMClient

List of all fields by module is also located at

https://linkwithweb.googlecode.com/svn/trunk/CRM/SugarCRM/ModuleWiseFieldsAndLinkedFieldsList.txt

Same can also be extracted by running above program

Njoy working with SugarCRM..

Fell free to contact me if any questions

Spring Integration Webapp( JPA/Hibernate | Webservices (JAX-WS|Apache CXF) | JQuery | EJB3 | Maven | Jboss | Annoatations)

Spring is one of the best Framework’s around in J2EE field which has made integration to various Framework pretty easy. This article is in series of articles which teach about spring integration in details. All source code is checked into svn which can be checked out and tested.

Assumption : Readers has basic knowledge of Servlets and JSP technologies.

Background : Sample project named testspring has been create in modular manner using Maven.  I used 2 differrent database schema names of mysql testjpa/testejb to test this project. I have configured

<property name=”hibernate.hbm2ddl.auto” value=”update” />

so that once proper connectivity is made program on startup will generate all tables in database

Any framework that has to integrated into J2EE frontend technology has to get control from Servlet Container, As all “http”(There can be other requests RMI/JMS..etc) requests are passed on to servlet container first which inturn based on configuration passes to corresponding framework.

All the integrations are generally handle using servlet mapping, or using listeners or filters in Webapplication.

To to integrate spring in webapplication we have to do the following

  • Configure spring Listener and Servlet in web.xml
	<!-- Configuration files for spring  -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
            /WEB-INF/spring/app-config.xml,
            /WEB-INF/spring/app-*-config.xml
        </param-value>
	</context-param>

	<!-- Spring listeners -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<listener>
		<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
	</listener>
	<servlet>
		<servlet-name>dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>dispatcher</servlet-name>
		<url-pattern>/services/*</url-pattern>
	</servlet-mapping>

Now that you have configured spring now start configuring spring beans in Spring configuration files.( As per the above configuration file. All requests with url pattern services/* will get routed to spring dispatcher servlet. Which inturn takes care of request mapping based on Configuration files or using Annotations.

if you have observerd the spring servlet name is “dispatcher”

so the configuration file that is read by default will be dispatcher-servlet.xml and then other files with same name pattern defined in context-param will get loaded.

Attached is my Dispatcher Servlet Sample code

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:beans="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

	<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
	
	<!-- Enables the Spring MVC @Controller programming model -->
	<annotation-driven />

	<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
	<resources mapping="/resources/**" location="/resources/" />
	<resources mapping="/assets/**" location="/assets/" />
	<resources mapping="/CSS/**" location="/CSS/" />
	<resources mapping="/images/**" location="/images/" />
	<resources mapping="/JS/**" location="/JS/" />
	<resources mapping="/swfupload/**" location="/swfupload/" />
	
	<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory 
	<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>       
    -->

	<!-- freemarker config -->
	<beans:bean id="freemarkerConfig"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
		<beans:property name="templateLoaderPath" value="/WEB-INF/freemarker/" />
		<beans:property name="freemarkerVariables">
			<beans:map>
				<beans:entry key="xml_escape" value-ref="fmXmlEscape" />
			</beans:map>
		</beans:property>
	</beans:bean>

	<beans:bean id="fmXmlEscape" class="freemarker.template.utility.XmlEscape" />

	<!--

		View resolvers can also be configured with ResourceBundles or XML
		files. If you need different view resolving based on Locale, you have
		to use the resource bundle resolver.
	-->
	<beans:bean id="viewResolver"
		class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
		<beans:property name="cache" value="true" />
		<beans:property name="prefix" value="" />
		<beans:property name="suffix" value=".html" />

		<!--
			if you want to use the Spring FreeMarker macros, set this property to
			true
		-->
		<beans:property name="exposeSpringMacroHelpers" value="true" />

	</beans:bean>
    
       
       
</beans:beans>

Above code has Configuration to define view resolver (We can integrate different View Technologies in it JSP/Freemarker/Velocity…etc). I’m using freemarker in my example. It also has a commented code which uses jsp as view resolver

The above configuration is basic configuration for Spring MVC. If you have observed it we have defined that spring should discover beans by itself based on annotations rather than configuration stuff. Annotations make is easier for developer to define beans avoiding unnecessary xml configuration which is difficult to remember

Above configuration also lists out url pattern’s that have to be excluded in this flow (Example all css/js/images etc files ).

Below is same Spring MVC controller which is configured through annotations

C:\development\linkwithweb\svn\SpringTutorials\testspring\images

/*
 * Copyright 2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.northalley.template.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.northalley.template.services.WelcomeService;

/**
 * @author ashwin kumar
 * 
 */
@Controller
public class GenericController {

	@Autowired
	@Qualifier("welcomeService")
	private WelcomeService welcomeService;

	/**
	 * Constructor
	 */
	public GenericController() {
	}

	/**
	 * @param searchCriteria
	 * @param formBinding
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/test", method = RequestMethod.POST)
	@ResponseBody
	public Response search(SearchCriteria searchCriteria,
			BindingResult formBinding, WebRequest request) {
		Response response = new Response();
		response.setWelcome(welcomeService.hello("Ashwin"));

		return response;
	}

	@RequestMapping("/freemarkertest")
	public ModelAndView hello() {
		return new ModelAndView("hello", "greeting", "Hello world!");
	}

}

If you look into the code it defines that this class is a Spring MVC Controller(Class that handles all requests)

All the methods that you want to expose in this class should get a RequestMapping annotation with URL pattern and corresponding attributes defined for that

Ex:@RequestMapping(value = “/test”, method = RequestMethod.POST)   (This says any URL with services/test has to be handled by this method).. “services” is base url for spring requests which is configured in web.xml

You can directly render response from here using ResponseBody annotation or you can create model object and pass it to View Technology to render that by creating ModelAndView as response object

In the above example i have @ResponseBody annotation configured for one method and i have configured to receive JSON repsonse for any ResponseBody annotation in my app-config.xml

	<!--
		Define the OXM marshaller which is used to convert the Objects <->
		JSON/XML.
	-->
	<beans:bean id="oxmMarshaller"
		class="org.springframework.oxm.xstream.XStreamMarshaller" />

	<beans:bean id="marshallingHttpMessageConverter"
		class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
		<beans:property name="marshaller" ref="oxmMarshaller" />
		<beans:property name="unmarshaller" ref="oxmMarshaller" />
	</beans:bean>

	<!--
		Required for REST services in order to bind the return value to the
		ResponseBody.
	-->
	<beans:bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<beans:property name="messageConverters">
			<util:list id="beanList">
				<ref bean="marshallingHttpMessageConverter" />
			</util:list>
		</beans:property>
	</beans:bean>

Here is sample Spring MVC Design

Read more about spring MVC in

 

http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

The below one is one of best link which explains all different way you can use Rest Style URL in Spring MVC

http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

 

Now that i have given basic Introduction to Spring MVC integration i’ll take you through JPA Configuration both in Tomcat as well as JBOSS.

JPA can be used in 2 ways ( Using Spring and Using EJB3 container) . As we don’t have EJB container in tomcat we use spring to configure JPA for us.

Let me start with JPA/Hibernate  using Spring in tomcat

I have configured JPA in app-jpa-config.xml in testspring-webapp/WEB-INF/spring   folder (Checkout code from svn to see project structure)

Here is snippet of the JPA config file

<?xml version="1.0" encoding="UTF-8"?>


<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">


	<tx:annotation-driven transaction-manager="transactionManager" />

	<!--
        Data source
    -->
	<beans:bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<beans:property name="driverClassName">
			<beans:value>org.hsqldb.jdbcDriver</beans:value>
		</beans:property>
		<beans:property name="url">
			<beans:value>jdbc:hsqldb:mem:testspring-db</beans:value>
		</beans:property>
		<beans:property name="username">
			<beans:value>sa</beans:value>
		</beans:property>
		<beans:property name="password">
			<beans:value></beans:value>
		</beans:property>
	</beans:bean>

	<!--
        Configuration for Hibernate/JPA
    -->
	<beans:bean id="entityManagerFactory"
		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<beans:property name="persistenceUnitName" value="testspring-jpa" />
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="jpaDialect">
			<beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
		</beans:property>
		<beans:property name="jpaVendorAdapter">
			<beans:bean
				class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<beans:property name="showSql" value="false" />
				<beans:property name="generateDdl" value="true" />
				<beans:property name="databasePlatform"
					value="org.hibernate.dialect.HSQLDialect" />
			</beans:bean>
		</beans:property>
	</beans:bean>

	<beans:bean id="transactionManager"
		class="org.springframework.orm.jpa.JpaTransactionManager">
		<beans:property name="entityManagerFactory" ref="entityManagerFactory" />
		<beans:property name="dataSource" ref="dataSource" />
	</beans:bean>

</beans:beans>

As you see here we have configured persistenceUnitName as “testspring-jpa”. This name has been configured in persistence.xml of  testspring-java project module. Here is the snippet for that

<persistence
  xmlns="http://java.sun.com/xml/ns/persistence"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
  version="1.0">

 <persistence-unit name="testspring-jpa">
 </persistence-unit>

</persistence>

And now that we have configured spring we can create entities in JPA style and use EntityManager to fire our queries.

Here is the sample welcomeService that is used in our Spring MVC controller

/*
  
 */

package org.northalley.template.testspring.services;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.northalley.template.testspring.entities.Welcome;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service("welcomeService")
public class WelcomeServiceImpl implements WelcomeService {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public Welcome hello(String name) {
		if (name == null || name.trim().length() == 0)
			throw new RuntimeException("Name cannot be null or empty");

		Welcome welcome = null;
		try {
			Query q = entityManager
					.createQuery("select w from Welcome w where w.name = :name");
			q.setParameter("name", name);
			welcome = (Welcome) q.getSingleResult();
		} catch (NoResultException e) {
			welcome = new Welcome();
			welcome.setName(name);
			welcome.setMessage("Welcome " + name);
			entityManager.persist(welcome);
		}
		return welcome;
	}
}

Now Lets switch to other part of using JPA with EJB ( This can be tested in jboss)

Here is sample snippet of stateless session bean in testspring-ejb project that is using JPA to get list of users

package org.testspring.ejb.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testspring.ejb.entity.User;

/**
 * @author ashwin kumar
 * 
 */
@Stateless(mappedName = "userDAOBean")
public class UserDAOBean implements UserDAO {
	private static Log log = LogFactory.getLog(UserDAOBean.class);

	private EntityManager em;

	@PersistenceContext(unitName = "TestEntityManager")
	public void setEm(EntityManager em) {
		this.em = em;
	}

	public List<User> getUsers() {
		log.debug("getUsers");
		List<User> users = this.em.createQuery(
				"select user from User user order by user.lastName")
				.getResultList();
		return users;
	}

	// not using this method in this example app
	public User saveUser(User user) {
		log.debug("saveUser: " + user);
		this.em.persist(user);
		this.em.flush();
		return user;
	}
}

Below is code of User Entity i have created

package org.testspring.ejb.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
//if the table name matches your class name, you don't need the 'name' annotation
@Table(name="lt_user") 
public class User extends BaseEntity {
     
    @Id 
    @GeneratedValue(strategy=GenerationType.AUTO) 
    //we don't need the Column annotation here bc the column name and this field name are the same
    private Long id;
    
    @Column(name="first_name",nullable=false,length=50)
    private String firstName;
    
    @Column(name="last_name",nullable=false,length=50)
    private String lastName;
    
    private Date birthday;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
 
}

Now that we are done with basic end to end integration .I’ll also show how to inject EJB in Servlet/Spring MVC

Below is sample servlet which called stateless bean . Same method is used in spring MVC too

package com.testspring.servlet;

import java.io.IOException;
import java.util.Hashtable;
import java.util.List;

import javax.ejb.EJB;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.testspring.ejb.dao.UserDAO;
import org.testspring.ejb.entity.User;

import com.testspring.service.MathService;

/**
 * @author ashwin kumar
 * 
 */
public class UserAdminServlet extends HttpServlet {

	@EJB(mappedName = "testspring-ear-0.0.1-SNAPSHOT/UserDAOBean/local")
	private UserDAO userDao;

	WebApplicationContext context = null;


	/**
	 * @param filterConfig
	 * @throws ServletException
	 */
	public void init(ServletConfig filterConfig) throws ServletException {
		System.out.println("Inti calleddddddddddddddd");
		super.init(filterConfig);
		ServletContext servletContext = filterConfig.getServletContext();
		context = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		// set up an injected bean into application scope
		// servletContext.setAttribute("mybean", context.getBean("aBean"));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println(((MathService) context.getBean("mathService")).add(
				1, 2));

		if (userDao == null) {
			try {
				Hashtable environment = new Hashtable();
				environment.put(Context.INITIAL_CONTEXT_FACTORY,
						"org.jnp.interfaces.NamingContextFactory");
				environment.put(Context.URL_PKG_PREFIXES,
						"org.jboss.naming:org.jnp.interfaces");
				environment.put(Context.PROVIDER_URL, "jnp://localhost:1099"); // remote
				// machine
				// IP

				Context context = new InitialContext(environment);
				userDao = (UserDAO) context
						.lookup("testspring-ear-0.0.1-SNAPSHOT/UserDAOBean/local");
				// context.lookup("userDAOBean");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		List<User> users = userDao.getUsers();
		for (int i = 0; i < users.size(); i++) {
			response.getWriter().append(
					"UserName :" + users.get(i).getFirstName() + " "
							+ users.get(i).getLastName()).append("<br/>");
			response.getWriter().append("id :" + users.get(i).getId()).append(
					"<br/>");
		}
	}
}

 

Now that i have covered all topics from frontend to db, now i’ll take you though how to configure webservices. I’ll show examples with both Apache CXF and JAX-WS

 

Webservices

Similar to spring MVC configuration through servlet , we have to configure both JAX-WS and Apache CXF through their own servlets. Below is servlet configuration to enable them

<!--  jax-ws -->
	<servlet>
		<servlet-name>jaxws-servlet</servlet-name>
		<servlet-class>com.sun.xml.ws.transport.http.servlet.WSSpringServlet</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>jaxws-servlet</servlet-name>
		<url-pattern>/ws/*</url-pattern>
	</servlet-mapping>



<!-- CXF Configuration -->
	<servlet>
		<servlet-name>CXFServlet</servlet-name>
		<servlet-class>
			 org.apache.cxf.transport.servlet.CXFServlet
		</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>CXFServlet</servlet-name>
		<url-pattern>/webservice/*</url-pattern>
	</servlet-mapping>

Now that we have configured respective URL patterns now lets see configuration in Spring that is required to expose Beans as webservices

Webservice configuration for spring is configured in app-ws-config.xml

<?xml version="1.0" encoding="UTF-8"?>

	<!--
	-->

<beans:beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ws="http://jax-ws.dev.java.net/spring/core"
	xmlns:wss="http://jax-ws.dev.java.net/spring/servlet" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://jax-ws.dev.java.net/spring/core  http://jax-ws.dev.java.net/spring/core.xsd
        http://jax-ws.dev.java.net/spring/servlet http://jax-ws.dev.java.net/spring/servlet.xsd
        http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">


	<!-- Web service config for Apache CXF -->
	<import resource="classpath:META-INF/cxf/cxf.xml" />
	<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
	<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

	<jaxws:endpoint id="orderProcess"
		implementor="org.northalley.template.testspring.controller.OrderProcessImpl"
		address="/OrderProcess" />

	<!-- Web service config for JAX-WS -->

	<wss:binding url="/ws">
		<wss:service>
			<ws:service bean="#helloWs" />
		</wss:service>
	</wss:binding>


	<beans:bean id="helloWs"
		class="org.northalley.template.testspring.controller.WebserviceController">
	</beans:bean>


</beans:beans>

Below is how i have expose OrderService as webservice for apache CXF

package org.northalley.template.testspring.controller;

import javax.jws.WebService;

@WebService(endpointInterface = "org.northalley.template.testspring.controller.OrderProcess")
public class OrderProcessImpl implements OrderProcess {

    public String processOrder(Order order) {
        return order.validate();
    }
}

Below is code of bean which is exposed by JAX-WS

/*
 * 
 */
package org.northalley.template.testspring.controller;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

import org.northalley.template.testspring.services.WelcomeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * @author ashwin kumar
 * 
 */
@WebService(name = "/hello")
@SOAPBinding(style = SOAPBinding.Style.RPC, use = SOAPBinding.Use.LITERAL)
public class WebserviceController {

	@Autowired
	@Qualifier("welcomeService")
	private WelcomeService welcomeService;

	/**
	 * Constructor
	 */
	public WebserviceController() {
	}

	/**
	 * @param searchCriteria
	 * @param formBinding
	 * @param request
	 * @return
	 */
	@WebMethod(operationName = "getMessage")
	public String search() {
		return welcomeService.hello("Ashwin").getMessage();

	}

	@WebMethod(operationName = "sayHello")
	public String sayHelloToTheUser(@WebParam(name = "name") String userName) {
		return "Testing: " + " " + userName;
	}

}

Sample WSDL URL’s

http://localhost:8080/testspring-webapp/webservice/OrderProcess?wsdl

http://localhost:8080/testspring-webapp/ws?wsdl

 

And finally one more thing which i haven’t used in example. I have configured HSQLDB to used so that any demo’s need not have an external database but have Inbuilt DB

Here is how you do that

	<!-- H2 Database Console for managing the app's database -->
	<servlet>
		<servlet-name>H2Console</servlet-name>
		<servlet-class>org.h2.server.web.WebServlet</servlet-class>
		<init-param>
			<param-name>-webAllowOthers</param-name>
			<param-value>true</param-value>
		</init-param>
		<load-on-startup>2</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>H2Console</servlet-name>
		<url-pattern>/admin/h2/*</url-pattern>
	</servlet-mapping>

 

If you use http://localhost:8080/appname/admin/h2 you will goto to HSQLDB Admin console

I think i have covered all concepts and code snippets to get you started.

Code has been checked in to

https://linkwithweb.googlecode.com/svn/trunk/SpringTutorials/testspring

 

 

 

Checkout

mvn clean install package

testspring-war ( Webapp code for ear file)  (To be deployed on Jboss

testspring-ejb (Has ejb code)

testspring-ear  — Combining both ejb and war to create ear

———————————————–

testspring-java (Java code used in tomcat)

testspring-webapp ( Web configuration for tomcat)

to test on tomcat follow the below steps

cd testspring-webapp

mvn tomcat:run  and njoy playing with code

Njoy playing with code. Get back to me if you have any questions.

 

 

 

 

 

 

 

 

GIT HTTPS Access Problem

Recently i was working on some OSGI sample and was trying to download code from GIT hub. Here is the problem i face in downloading code

git error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed while accessing https:…………………………….

I work on windows system and i have cygwin installed on my system.

Here is how i fixed it

The problem is that you do not have any of Certification Authority certificates installed on your system. And these certs cannot be installed with cygwin’s setup.exe.

There are two solutions: 1. Ignore ssl certificate verification:

$ env GIT_SSL_NO_VERIFY=true git clone https://github... (This dosen't work in all systems)

2. Actually install root certificates. Curl guys extracted for you certificates from mozilla: (This works in most of the system)

http://curl.haxx.se/docs/caextract.html

cacert.pem file is what you are looking for. This file contains > 250 CA certs (Lots of people you are going to trust with this command) . You need to download this file, split it to individual certificates put them to /usr/ssl/certs (your CApath) and index them.

Here is how to do it: With cygwin setup.exe install curl and openssl packages Execute  (AWK program us used to automate the steps)

$ cd /usr/ssl/certs 
$ curl http://curl.haxx.se/ca/cacert.pem | awk 'split_after==1{n++;split_after=0} /-----END CERTIFICATE-----/ {split_after=1} {print > "cert" n ".pem"}' 
$ c_rehash


You can get more options in
http://returnbooleantrue.blogspot.com/2009/06/using-github-through-draconian-proxies.html

Njoy migrating to GITHub

Liferay Build From Source and Deploy to Local Maven Repository

First of all download source from

http://www.liferay.com/downloads/liferay-portal/available-releases or you can download from svn using following command

svn –username guest co svn://svn.liferay.com/repos/public/portal/trunk portal-trunk

Once you download source extract to one Folder.(Dont have long path it might cross maximum path length in windows if you store this deep inside some path)

Prerequisites

———————–

ANT: Download apache ant and place it in path

Below one is needed for deployment to maven repository

GPG : http://www.gpg4win.org/download.html  (You might have to get older version as build searches for gpg.exe )

Older version can be downloaded from http://ftp.gpg4win.org/

If you want to setup maven repository on your machine then do the following

  1. Download nexus(Opensource Maven Repository) from http://nexus.sonatype.org/downloads/nexus-oss-webapp-1.9.2-bundle.tar.gz
  2. Follow following instructions for Installation http://www.sonatype.com/books/nexus-book/reference/install.html
  3. Start nexus and Open your browser to your newly created nexus (http://localhost:8081/nexus)
  4. Login as administrator (default login is admin / admin123) and Change your password
  5. Go to Repositories and click Add -> Hosted Repository
  6. Create Hosted Repository
  • Repository ID: liferay-ce-snapshots
  • Repository Name: Liferay Snapshot Repository
  • Provider: Maven2 Repository
  • Repository Policy: Snapshot
Now configure your maven to point to local repository
<?xml version="1.0" encoding="UTF-8"?> 
<settings> 
	<mirrors> 
		<mirror> 
			<id>local</id> 
			<name>Local mirror repository</name> 
			<url>http://localhost:8081/nexus/content/groups/public</url> 
			<mirrorOf>*</mirrorOf> 
		</mirror> 
	</mirrors>
	<servers> 
		<server> 
			<id>liferay</id> 
			<username>admin</username> 
			<password>ashwin@123</password> 
		</server> 
	</servers> 
</settings>

Now Goto to folder where you have liferay source

Open build.properties  and paste following in bottom  ( You can use other property file names . Just look at build-common.xml for more property filenames you can use)

 

maven.url=http://localhost:8081/nexus/content/repositories/liferay-ce-snapshots
gpg.passphrase=ashwin
gpg.keyname=Ashwin
lp.version=6.0.6
maven.repository.id=liferay
maven.version=${lp.version}-SNAPSHOT

 

Now Lets generate Key File using GPG which we downloaded before

LiferayGPG
LiferayGPG

 

Once you generate the key. you can now use it in deployment.

Now follow these steps

  1. C:\liferay-portal-src-6.0.6>set ANT_OPTS=”-Xmx1024m -XX:MaxPermSize=256m”
  2. ant jar
  3. ant -f build-maven.xml deploy-artifacts ( This will deploy all the Liferay Artifacs to maven repository you have just configured using nexus)
Now njoy using maven with liferay. Next articles would be to create portlets in Liferay and Using liferay to create portals