Results 1 to 8 of 8

Thread: groovy/grails/java consume soap/rest-service

  1. #1
    johanneshauni is offline Member
    Join Date
    Sep 2010
    Posts
    5

    Default groovy/grails/java consume soap/rest-service

    Hi!

    We are trying if it is possible to use SugarCRM for our purposes and so I have the task to see if I can get the WebService functional.
    In the application we want to connect with the CRM we use Groovy/Grails.

    So here are the ways i tried to connect and login and what came from it:

    SOAP
    String wsdlURL = "http://localhost/sugarcrm/soap.php?wsdl"
    WSClient proxy = new WSClient(wsdlURL,this.class.classLoader,SoapVersio n.SOAP_1_1)//webService.getClient(wsdlURL)
    //proxy.setBasicAuthentication "root","d8cfaaa6ea09c9a352541d74f9b11678"
    proxy.initialize()
    //def client = proxy.create("com.sugarcrm.sugarcrm.loginRequest")
    //def result = client.login(auth,'test')
    def result
    result = proxy.getVersion()
    render result

    Issue
    It bails out at proxy.initialize() ... what initialize internally does as ut fails is "getClient".
    the stated error is that it that there is a schema defined with a differing schema and location. it obviously can't handle that ... i had a look at the wsdl and found
    <xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/"/>
    <xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" schemaLocation="http://schemas.xmlsoap.org/soap/encoding/"/>
    obviously it is the second line it complains about. i have no idea why or what's wrong (I'm new to soap!).
    Any Ideas?

    REST

    i tried two variants with REST .. via the URLConnection Class and with the grails REST-Client plugin which utilizes HTTPBuilder

    URLConnection

    URL restURL = new URL("http://localhost/sugarcrm/service/v2/rest.php")
    URLConnection conn = restURL.openConnection()
    conn.requestMethod = "POST"
    conn.doOutput = true

    SugarAuthenticationBean auth = new SugarAuthenticationBean(user_auth:[username:'root',password:'d8cfaaa6ea09c9a352541d74 f9b11678'])

    conn.addRequestProperty 'method', 'login'
    conn.addRequestProperty 'input_type', 'json'
    conn.addRequestProperty 'response_type', 'json'
    conn.addRequestProperty 'rest_data', (auth as JSON).toString()

    JSONElement antwort
    if (conn.responseCode == conn.HTTP_OK) {
    antwort = JSON.parse(conn.inputStream,"UTF-8")
    }
    return [msg:antwort.toString()]

    which seems to do the request but the response always seems to be empty ... so it would be very helpful to know how to "design" the request so i would get an appropriate answer (the session id)
    also, the rest.php states that the return parameters of login are id, ... but if i do it this way the result-object is always empty

    HttpBuilder/RESTClient

    SugarAuthenticationBean auth = new SugarAuthenticationBean(user_auth:[username:'root',
    password:'d8cfaaa6ea09c9a352541d74f9b11678'])
    def antwort

    withHttp(uri:"http://localhost/sugarcrm/service/v2/rest.php") {
    post(['method':'login',
    'input_type':'json',
    'response_type':'json',
    'rest_data':auth as JSON]) { HttpResponseDecorator response ->
    response.getParams().each {
    //antwort += it.toString() + "___"
    }
    antwort = response.getParams().isParameterSet('id')
    //antwort = response.getStatus()
    }
    }
    return [msg:antwort]

    this method looks most promising to me (apart from the soap, which i would prefer if i could get it to work as i could simply create Objects which are expected by the server and didn't have to deal with JSON-Syntax of which I don't know if I create them the right way) as I use a method that was explicitely defined for this purpose .. this generates a http-post request.
    again, i get a Status of 200 OK, but that happens regardless of the params i provide ... so I don't know how much progress I actually made.
    again, how to provide the params, and what type are the reply params of?

    any help would be very appreciated.

    thx, Johannes

  2. #2
    johanneshauni is offline Member
    Join Date
    Sep 2010
    Posts
    5

    Default Re: groovy/grails/java consume soap/rest-service

    ok, so i figured it out using simple RESTClient-Class in Groovy:

    String auth = "{'user_auth':{'username':'johannes','password':'d 8cfaaa6ea09c9a352541d74f9b11678'}}"
    def myRC = new RESTClient("http://localhost/")
    def r = myRC.get(path: "sugarcrm/service/v2/rest.php",
    query: [method: "login", input_type: "JSON", response_type: "JSON", rest_data: auth])
    return [msg: r.data]

    however I still cannot login - now I get an invalid user/pw error ...
    if i get no help it seems i got to debug sugar itself ... can't help myself

    greetz, Johannes

  3. #3
    johanneshauni is offline Member
    Join Date
    Sep 2010
    Posts
    5

    Default Re: groovy/grails/java consume soap/rest-service

    hi guys!

    i keep getting the invalid user message from REST, so if anyone has to say anything on the issue that helps ..

    so i tried to get the SOAP-Version working again.
    when i had a look at the wsdl of the 6.0.1 version i saw the namespace definition of the second schema entry was missing the "location" property - and voila 6.0.1 works. Seems to me that this is a bug in the WSDL creation of version 6.0.2

    so i tried my luck since the initialization worked with this:

    String wsdlURL = "http://mydomain.org/soap.php?wsdl"//"http://localhost/sugarcrm/soap.php?wsdl"
    //WSClient proxy = new WSClient(wsdlURL,this.class.classLoader,SoapVersio n.SOAP_1_1)//
    WSClient proxy = webService.getClient(wsdlURL)
    proxy.setBasicAuthentication "myuser","md5pw"
    //proxy.initialize()
    String auth = "{'user_auth':{'username':'myuser','password':'md5 pw'}}"
    //def result = client.login(auth,'SCE')
    def result = proxy.login("{'user_auth':{'username':'myuser',pas sword':'md5pw'}}",'test')
    def sid = result
    return [msg:result]

    but I get:
    groovyx.net.ws.exceptions.InvokeException: java.lang.NullPointerException

    seems to me that there is no login-method

    so, I now found something about WSDL2JAVA (from Apache Axis 2) and created a java file via
    wsdl2java.sh -o . -p de.mydomain.sugarcrm -uri http://mydomain.com/soap.php?wsdl -d adb -s

    i'll let you know if this works. any help appreciated.

    greetz, johannes

  4. #4
    johanneshauni is offline Member
    Join Date
    Sep 2010
    Posts
    5

    Lightbulb Re: groovy/grails/java consume soap/rest-service

    ok, now I tried it with WSDL2JAVA like this:

    try {
    com.ariadne.sugarcrm.SugarsoapStub stub = new com.ariadne.sugarcrm.SugarsoapStub();
    stub._getServiceClient().getOptions().setSoapVersi onURI(org.apache.axiom.soap.SOAP11Constants.SOAP_E NVELOPE_NAMESPACE_URI)
    stub._getServiceClient().getOptions().setProperty( HTTPConstants.CHUNKED,false);
    stub._getServiceClient().getOptions().setProperty( org.apache.axis2.Constants.Configuration.CHARACTER _SET_ENCODING, "US-ASCII")
    stub._getServiceClient().getOptions().setProperty( org.apache.axis2.Constants.Configuration.MESSAGE_T YPE, "application/json");
    com.ariadne.sugarcrm.SugarsoapStub.User_auth auth = new com.ariadne.sugarcrm.SugarsoapStub.User_auth()
    auth.setUser_name("myUser")
    auth.setPassword("mymd5PW")
    auth.setVersion(".01")
    com.ariadne.sugarcrm.SugarsoapStub.Login soapLogin = new com.ariadne.sugarcrm.SugarsoapStub.Login()
    soapLogin.setUser_auth(auth)
    soapLogin.setApplication_name("Ariadne")
    def antwort = stub.login(soapLogin)
    return [msg: antwort]
    } catch (Exception e) {
    render e
    }

    and in the Axis2GrailsPlugin.groovy file in the plugins dir:

    "axisConfig"(org.wso2.spring.ws.SpringAxisConfigur ation) {
    ...
    messageFormatters = [ref("axis2MsgFormatterURL"),
    ref("axis2MsgFormatterForm"), ref("axis2MsgFormatterXML"), ref("axis2MsgFormatterJson")]
    messageBuilders = [ref("axis2MsgBuilderURL"),
    ref("axis2MsgBuilderForm"), ref("axis2MsgBuilderXML"), ref("axis2MsgBuilderJson")]
    ...
    }
    "axis2MsgFormatterJson" (org.wso2.spring.ws.beans.MessageFormatterBean) {
    contentType = "application/json"
    clazz = "org.apache.axis2.json.JSONBadgerfishMessageFormat ter"
    }
    "axis2MsgBuilderJson"(org.wso2.spring.ws.beans.Mes sageBuilderBean) {
    contentType = "application/json"
    clazz = "org.apache.axis2.json.JSONBadgerfishOMBuilder "
    }

    Result:
    org.apache.axis2.AxisFault: Operation '' is not defined in the WSDL for this service

    I read somewhere that this might be due to SOAP1_2 usage which is axis-default and somewhere else I read that Sugar only has 1.1 ... but if you look close you'll find I did set the Soap Version to 1.1, so I have no idea what's the prob

    Any ideas appreciated

    greetz, hauni

  5. #5
    johanneshauni is offline Member
    Join Date
    Sep 2010
    Posts
    5

    Talking Re: groovy/grails/java consume soap/rest-service

    Hi Guys!

    Gave up on the WSDL2Java-Soap Variant.

    Retried SOAP like this:
    Code:
    String wsdlURL = "http://localhost/sugarcrm/soap.php?wsdl"
    //WSClient proxy = new WSClient(wsdlURL,this.class.classLoader,SoapVersion.SOAP_1_1)//
    WSClient proxy = webService.getClient(wsdlURL,SoapVersion.SOAP_1_1)
    
    String auth = "'user_auth':{'user_name':'myUser','password':'myMd5Pw','version':'.01'}"
    String appName = "'application_name':'Ariadne'"
    String loginRequest = "{loginRequest:{${auth},${appName}}}"
    //def loginRequest = proxy.create("com.sugarcrm.www.sugarcrm.loginRequest")
    //loginRequest.user_auth = proxy.create("com.sugarcrm.www.sugarcrm.user_auth")
    //loginReuest.user_auth.user_name = "myUser"
    //loginReuest.user_auth.password = "myPW"
    //loginReuest.user_auth.version = ".01"
    //loginReuest.application_name = "Ariadne"
    def result = proxy.invokeMethod("login",loginRequest)
    return [msg:result]
    couldn't get it to work.

    So i retried REST and had another look at the WSDL and API spec and saw, oh my, username is user_name.
    So this is what got me "Invalid username or password"

    So I got it to work.
    To make it more elegant and reusable I introduced the Factory Pattern with SugarBeans ... here's the working RESTful groovy-code

    CONTROLLER:
    Code:
    	
    def sugar = {
           AbstractSugarBean auth = new SugarAuthenticationBean()
           AbstractSugarBean loginRequest = new SugarLoginRequestBean()
    
    	try {
    	        auth.setBeanProperty(auth.USER_NAME,"myUser")
    		auth.setBeanProperty(auth.PASSWORD,"myMd5Pw")
    		auth.setBeanProperty(auth.VERSION,".01") //not needed
    		loginRequest.setBeanProperty(loginRequest.USER_AUTH,auth.toJson())
    		loginRequest.setBeanProperty(loginRequest.APPLICATION,"MyApplication") //not needed
    	}
    	catch (groovy.lang.MissingPropertyException e) {
    		return [msg: e.toString()]
    	}
    	catch (java.lang.NullPointerException e) {
    		return [msg: e.toString()]
    	}
    	catch (Exception e) {
    		return [msg: e.toString()]
    	}
    
    	def myRC = new RESTClient("http://localhost/")
    	def r = myRC.post(  path: "service/v2/rest.php",
    					query:
    						[method: "login",
    						input_type: "JSON",
    						response_type: "JSON",
    						rest_data: loginRequest.toJson()])
    	return [msg: r.data]
    }
    Since grails.converters.JSON didn't output a JSON-Format Sugar understands I had to write my own ...

    AbstractSugarBean
    Code:
    abstract class AbstractSugarBean {
    
    	protected Map<String,?> beanProperties = [:]
    
    	public void setBeanProperty(String property, String value) {
            beanProperties.putAt(property,value)
        }
    
        public String toJson (Map<String,?> properties = beanProperties) {
            String json = "{"
            properties.eachWithIndex { String key, value, i ->
                json += "'${key}':"
                if(value instanceof java.util.Map) {
                    json +=  toJson(value)
                }
                else {
    	            if(value.charAt(0) == "{") {
    	                json += value
    	            }
    		        else {
    		            json += "'${value}'"
    	            }
                }
                if(i == properties.size()-1) {
                    json += "}"
                }
                else {
                    json += ","
                }
            }
            json
        }
    }
    and the Concrete Beans themselves
    Code:
    class SugarAuthenticationBean extends AbstractSugarBean {
        final String USER_NAME = "user_name"
        final String PASSWORD = "password"
        final String VERSION = "version"
    }
    
    class SugarLoginRequestBean extends AbstractSugarBean {
    	final String USER_AUTH = "user_auth"
    	final String APPLICATION = "application_name"
    }
    so now I'm happy like a dog with its owner.
    hope this helps anyone

    greetz, Johannes
    Last edited by johanneshauni; 2010-10-06 at 02:36 PM. Reason: uups

  6. #6
    othmanelmoulat is offline Sugar Community Member
    Join Date
    Dec 2007
    Posts
    22

    Default Re: groovy/grails/java consume soap/rest-service

    the link below might be helpful
    http://othmanelmoulat.blogetery.com/...rsoap-in-java/

    Thanks
    othman

  7. #7
    angelababy is offline Banned
    Join Date
    Jul 2010
    Posts
    60

    Default Re: groovy/grails/java consume soap/rest-service

    Thanks so much for the wonderful information you provided us

  8. #8
    amusarra is offline Sugar Community Member
    Join Date
    Dec 2007
    Location
    Roma
    Posts
    23

    Default Re: groovy/grails/java consume soap/rest-service

    Antonio Musarra
    Senior Consultant Divisione T. E . M
    Telecomunicazioni Electronics & Media
    ____________________________
    Altran Italia S.p.A

    Via Goito 52
    00185 Roma

    Mob : +39 335 1028122
    Mail : antonio.musarra@altran.it
    http://www.altran.it
    Blog: http://musarra.wordpress.com

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 9
    Last Post: 2011-06-15, 06:30 PM
  2. REST call from Java (Android)
    By Makica in forum Developer Tutorials
    Replies: 2
    Last Post: 2010-08-30, 08:14 PM
  3. Updating fields with REST web service requests
    By jeffknoep in forum Developer Help
    Replies: 0
    Last Post: 2010-04-26, 09:42 AM
  4. Replies: 3
    Last Post: 2009-12-01, 07:35 PM
  5. Replies: 3
    Last Post: 2009-03-27, 08:15 AM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •