>  >  

Service Call Examples

Table Of Contents

 

1. Microsoft .Net

With Microsoft Visual Studio 2008, you need to right click on your project and choose "Add Service reference...". This will open the following dialog box :

Add Service Reference Dialog Box ...

Put the Wsdl url (https://services.open.xerox.com/Wsdl.svc/ServiceName) in the Address field and click on Go to retrieve the service reference.
A dialog box will then ask you if you want to be authenticated. Choose Yes.

Type your Open Xerox username & password in the dialog box. It may request it several times (don't worry, retype it)


Next, the service information is downloaded and is visible in the Services References folder of the project. Choose a namespace and click on Ok. The service can then be accessed from your code using the generated client software.

FAQs:

1. How can I retrieve token to connect to the service ?
WebRequest request = HttpWebRequest.Create("https://services.open.xerox.com/api/Auth/Authenticate");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
 
StreamWriter sw = new StreamWriter(request.GetRequestStream());
sw.Write("wrap_name=login&wrap_password=password");
sw.Close();
 
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StreamReader reader = new StreamReader(response.GetResponseStream());
String token = reader.ReadToEnd().Substring("wrap_access_token=".Length);
   
2. How can I send a token for REST or SOAP service ?

The token needs to be put in the Url in the query string or in the Authenticate Http Header

// Client with Http Header
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.Authorization] = String.Format("WRAP access_token=\"{0}\"", token);
 
// Client with Token in the query string
WebClient webClient = new WebClient();
webClinet.DownloadString(URL_THAT_NEED_TOKEN+"?wrap_access_token=" + Uri.EscapeDataString(token));
 
// WCF Soap Client with Token in the Http Header
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
    HttpRequestMessageProperty httpRequestProperty = new HttpRequestMessageProperty();
    httpRequestProperty.Headers[HttpRequestHeader.Authorization] = String.Format("WRAP access_token=\"{0}\"", token);
    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
     
    // Call Client Method
    // ...
}
 
// WCF Soap Client with Token in the Soap Header
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
    OperationContext.Current.OutgoingMessageHeaders.Add(MessageHeader.CreateHeader("Authorization", "http://open.xerox.com/", token));  
 
    // Call Client Method
    // ...
}
3. How can I send a token for a .Net Soap Client (non WCF) ?

For 'old' web service client (.Net Framework 2), you need to override the GetWebRequest method of the SoapHttpClientProtocol.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

    public partial class YOUR_SERVICE_CLASS
    {
        public string Token {get;set;}

        protected override System.Net.WebRequest GetWebRequest(Uri uri)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
            req.Headers[HttpRequestHeader.Authorization] = String.Format("WRAP access_token=\"{0}\"",Token);
            return req;
        }
    }

4. How do you accept the certificate in the code ?
using System.Security.Cryptography.X509Certificates;
using System.Net.Security; 
 
...
 
static bool ValidateServerCertificate(Object sender, 
     X509Certificate certificate, X509Chain chain, 
     SslPolicyErrors sslPolicyErrors)
     {
        // Check the certificate and return true to accept it 
        // (here always accepted).
        return true; 
     }
 
...
 
// Before calling the service, add an event to check certificate.
ServicePointManager.ServerCertificateValidationCallback += 
    new RemoteCertificateValidationCallback(ValidateServerCertificate);

2. JAX-WS client (Java)

In JAX-WS, to ccreate a web service client you have to create the service stub first and then the web service client.

2.1 Generating the JAX-WS client stub

The web service client stub can be generated manually with the following method. Please note that this method needs the latest Java Jdk (>= 1.6.0_20) which includes authentification to obtain wsdl file with the wsimport tool.

2.1.1 Create a Java project

Use your preferred IDE to create a standard Java 6 project. Create a package com.xerox.open

2.1.2 Create an authorization file

Create an authorization file to store login/password information for the wsimport tool to retrieve the wsdl.
Put https://[LOGIN]:[PASSWORD]@services.open.xerox.com:443/Wsdl.svc/[SERVICENAME] in this file, and replace the login, password and ServiceName with the corresponding value (remove the '[', ']').

2.1.3 Generate the service stub

In the top directory of the new Java project, run the wsimport command line tool with the following arguments (assuming that the sources are stored in the src directory):

    wsimport -XauthFile authFile.txt -p com.xerox.open -s src -d bin 
    (https://services.open.xerox.com/Wsdl.svc/ServiceName)
    

2.2 Building a Web Service Client using a JAX-WS stub

2.2.1 Certificates

If there are any issues regarding certificates, the certificate can be accepted by using the SSLUtilities from http://en.wikibooks.org/wiki/WebObjects/Web_Services/How_to_Trust_Any_SSL_Certificate or here. Then start your application with the following lines:

SSLUtilities.trustAllHostnames();
SSLUtilities.trustAllHttpsCertificates();
2.2.2 Proxy

If you need to use a proxy, you must set the properties https.proxyHost and https.proxyPort. For example:

System.setProperty("https.proxyHost", "proxy.mycompany.com");
System.setProperty("https.proxyPort", "8000");
2.2.3 Obtaining wsdl file through basic authentication

Open Xerox uses basic authentication to obtain the wsdl file, so you need to use a java.net.Authenticator class.

public static class MyAuthenticator extends Authenticator {
    String user;
 
    char password[];
 
    public MyAuthenticator(String user, char password[]) {
        this.user = user;
        this.password = password;
    }
 
    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(user, password);
    }
}

Then create a MyAuthenticator object and register it as default authenticator:

MyAuthenticator auth = new MyAuthenticator(login, password);
Authenticator.setDefault(auth);

2.3 Wrap Authentication

To call Open Xerox service, you must send the header in the soap message (via http header, SOAP header, ...), so you need to use a class that adds the token in the message. This class is named WrapAuthenticator and you just need to call the setHttpAuthorization static method with your service implementation and the authentication url (https://services.open.xerox.com/api/Auth/Authenticate).

WrapAuthenticator.setHttpAuthorization(calc, authUrl);
Example

Connecting to Open Xerox Calculator service

public static ICalculator connectToWebService(final String login,
        final String password, final String authUrl) {
    // Set the proxy settings if needed
    System.setProperty("http.proxyHost", "[YOUR HTTP PROXY URL]");
    System.setProperty("http.proxyPort", "[YOUR HTTP PROXY PORT]");
    System.setProperty("https.proxyHost", "[YOUR HTTPS PROXY URL]");
    System.setProperty("https.proxyPort", "[YOUR HTTPS PROXY PORT]");
     
    //Trust certificate
    SSLUtilities.trustAllHostnames();
    SSLUtilities.trustAllHttpsCertificates();
 
    // check if authentication is needed
    boolean needAuth = login != null || authUrl != null;
    char[] passwd = password.toCharArray();
    MyAuthenticator auth = null;
    if (needAuth) {
        auth = new MyAuthenticator(login, passwd);
        // use basic auth for getting the WSDL
        Authenticator.setDefault(auth);
    }
    Calculator service = null;
    ICalculator calc = null;
 
    try {
        // use the wsdl location that was used to build the stub
        service = new Calculator();
        calc = service.getCalculatorBasic();
    } catch (Throwable e) {
        System.err
                .println("[ERROR] Cannot connect to Calculator Web Service: "
                        + e.getMessage());
        e.printStackTrace();
        return null;
    }
 
    if (auth != null) {
        // use WRAP authentication for the next calls
        try {
            WrapAuthenticator.setHttpAuthorization(calc, authUrl);
        } catch (MalformedURLException e1) {                
            e1.printStackTrace();
            return null;
        }
    }
    // The service is created. Fill the password with blank
    if (passwd != null) {
        java.util.Arrays.fill(passwd, ' ');
    }
    return calc;
}

3. Php Client

To use an Open Xerox service with Php, you can use the Php example provided below. You need to fill in the wsdl address of the service you want to call, the login and the password and the authentication url to obtain the token. This example simply uses the CURL library to obtain the authentication token and uses it in the SOAP header with this token.

<?php

/**
 * This class provides SOAP access to an Open Xerox Soap Service
 */

class OpenXeroxSoapClient extends SoapClient {

	var $wsdl_string;
	var $user;
	var $password;
	var $proxy_host;
	var $proxy_port;
	var $wrap_access_token;

	/**
	  *	COnstructor: WSDl is mandatory. Other filds for autentication and proxy are not.
	  */
	public function __construct($wsdl, $user = NULL, $password = NULL, $proxy_host = NULL, $proxy_port = NULL){
		$this->wsdl_string = $wsdl;
		$this->user = $user;
		$this->password = $password;
		$this->proxy_host = $proxy_host;
		$this->proxy_port = $proxy_port;
	}
	
	/**
	  *	Add the proxy and authentication information for all the requests.
	  */
	function __doRequest($request, $location, $action, $version, $one_way = 0){
        $headers = array(
			'Method: POST',
			'User-Agent: OpenXerox PHP Client',
			'Content-Type: text/xml',
			'Authorization: WRAP access_token="'.$this->wrap_access_token.'"',
			'SOAPAction: "'.$action.'"'
    	);
 
        $ch = curl_init($location);
		curl_setopt_array($ch,array(
			CURLOPT_VERBOSE=>false,
			CURLOPT_RETURNTRANSFER=>true,
			CURLOPT_POST=>true,
			CURLOPT_FORBID_REUSE => 1, 
			CURLOPT_POSTFIELDS=>$request,
			CURLOPT_HEADER=>false,
			CURLOPT_RETURNTRANSFER => 1,
			CURLOPT_SSL_VERIFYPEER => FALSE,   
			CURLOPT_PROXY => $this->proxy_host,
			CURLOPT_PROXYPORT => $this->proxy_port,		
			CURLOPT_HTTPHEADER=>$headers
    	));
        $response = curl_exec($ch);
    	curl_close($ch); 
        return $response;
    }
	
    
	/** 
	 * Send a POST requst using cURL - used for getting the WRAP token.
	 * @param string $url to request 
	 * @param array $post values to send 
	 * @param array $options for cURL 
	 * @return string 
	 */ 
	private function curl_post($url, array $post = NULL, array $options = array()) { 
		$defaults = array( 
			CURLOPT_POST => 1, 
			CURLOPT_HEADER => 0, 
			CURLOPT_URL => $url, 
			CURLOPT_FRESH_CONNECT => 1, 
			CURLOPT_RETURNTRANSFER => 1, 
			CURLOPT_TIMEOUT => 4, 
			CURLOPT_FORBID_REUSE => TRUE,
			CURLOPT_SSL_VERIFYPEER => FALSE,
			CURLOPT_SSL_VERIFYHOST => FALSE,
			CURLOPT_PROXY => $this->proxy_host,
			CURLOPT_PROXYPORT =>$this->proxy_port,
			CURLOPT_POSTFIELDS => http_build_query($post) 
		); 

		$ch = curl_init(); 
		curl_setopt_array($ch, ($options + $defaults)); 
		if( ! $result = curl_exec($ch)) { 
			trigger_error(curl_error($ch)); 
		} 
		curl_close($ch); 
		return $result; 
	} 
	/**
	 * Connect - Establish the connection to the server. This is done in the constructor
	 * of the soap_client class
	 */
	function connect() {
		// WSDL url verification
		if (!$this->wsdl_string) {
			if (defined("WSDL_URL")) {
				$this->wsdl_string = WSDL_URL;
			} else {
				print("SOAP: URL of the WSDL is not defined. Please set your WSDL_URL environment variable.");
			}
		}

		try {
			// SOAP Client options
			$options = array();
			if ($this->proxy_host && $this->proxy_port) {
				$options['proxy_host'] = $this->proxy_host;
				$options['proxy_port'] = (int)$this->proxy_port;
			}
			// OAuth WRAP implementation
			$post = array();
			if($this->user && $this->password){
				$post['wrap_name'] = $this->user;
				$post['wrap_password'] = $this->password;
				$options["login"] = $this->user;
				$options["password"] = $this->password;
				// get auth token
				$auth_url="https://services.open.xerox.com/api/Auth/Authenticate";
				$auth_content="wrap_name=".$post['wrap_name']."&wrap_password=".$post['wrap_password'];
				$res = $this->curl_post($auth_url, $post);
				$this->wrap_access_token = substr($res,18);
				$options['Authorization'] = 'WRAP access_token='.$this->wrap_access_token;
			}
			
			// construct the SOAP client
			parent::__construct($this->wsdl_string, $options);
			$header = new SoapHeader('https://open.xerox.com/', 'Authorization', $this->wrap_access_token);
			parent::__setSoapHeaders($header);

		} catch (SoapFault $fault) {
			print_r($fault);
		}
	}
}

/*
Sample how to use it with the Language Identifier service (no proxy set & no login)
*/

// WSDL URL & autentication
$wsdl = "https://services.open.xerox.com/Wsdl.svc/LanguageIdentifier";
$user = NULL;
$password = NULL;

// proxy configuration
$proxy_host = NULL;
$proxy_port = NULL;

// SOAP client configuration
$client = new OpenXeroxSoapClient($wsdl, $user, $password, $proxy_host, $proxy_port);
$client->connect();

// call the language identifier
$text = "bonjour";
$result = $client->GetLanguageForString(array("document"=>$text));

// show the results
echo("The language of '".$text."' is: ".$result->GetLanguageForStringResult);
?>

4 Perl Client (SOAP Lite)

To use an Open Xerox service with Perl, you can use the following Perl sample. This sample use SOAP Lite module

# Include module
use SOAP::Lite; 
use LWP::UserAgent; 

# Set variable
my $login="LOGIN"; 
my $password="PASSWORD"; 
my $ua = LWP::UserAgent->new; 

# Retrieve the access token using Open Xerox login & password
$http = HTTP::Request->new(POST => 'https://services.open.xerox.com/api/Auth/Authenticate'); 
$http->content_type('application/x-www-form-urlencoded'); 
$http->content("wrap_name=$login&wrap_password=$password"); 
$res = $ua->request($http); 

# Parse Token
$token=$res->content; 
$token =~ s/wrap_access_token=/WRAP access_token=\"/g; $token=$token."\""; 

# Create Soap Client (set namespace according to the service wsdl)
my $soap = SOAP::Lite 
    -> on_action( sub { join '/', '"http://esp.xerox.com', $_[1]."\"" } ) 
    -> uri('http://esp.xerox.com/') 
    -> proxy('https://services.open.xerox.com/Soap.svc/11/WEBSERVICE',keep_alive=>1); 
# Set token in the Http Header
$soap ->transport->http_request ->header('Authorization' => $token); 

# Call an SOAP Operation
$result=$soap->call('METHOD', SOAP::Data->name('PARAMETER_NAME')->value(VALUE_PARAMETER)); 
 

5 Flex Client

To use an Open Xerox service with Flex, you can use the following methods.

Ask for a token :

public function login(name:String, password:String):void
{
var request:URLRequest = new URLRequest("https://services.open.xerox.com/api/Auth/Authenticate");
request.method = URLRequestMethod.POST;
request.contentType = "application/x-www-form-urlencoded";
request.data = new URLVariables("wrap_name=" + name + "&wrap_password=" + password);
              
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, onLoginComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onLoginFailure);
loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoginSecurityFailure);

loader.load(request);
}

Retrieve the token and send it in the authentication http header:

protected function onLoginComplete(event:Event):void
{
       var fullToken:String = String(URLLoader(event.target).data);
       var authToken:String = fullToken.substr(fullToken.indexOf("=") + 1);
       
// Adds the token in the http header.
       myWebService.httpHeaders = {Authorization:"WRAP access_token=\"" + authToken + "\""};
}

5 Python Client

To use an Open Xerox service with Python, you can use the following sample or here. This sample use httplib, urllib and json module

'''
Created on 5 Mar 2013

Generic simple Python client for OpenXerox services ( https://open.xerox.com ) 

'''

import httplib, urllib, json, logging

class Client:
    sOXService      = "services.open.xerox.com"
    sOXOperation    = "/RestOp/%s/%s"
    sOXAuthentif    = "/api/Auth/OAuth2"
    
    def __init__(self, serviceName):
        """
        initialize the client for a certain service, e.g; "LanguageIdentifier"
        """
        self.serviceName = serviceName
        self.user, self.pwd             = None, None
        self.proxyHost, self.proxyPort  = None, None
        #internals
        self._conn      = None
        
    def setCredentials(self, username, password):
        """
        in case authentification is required (not the case for the LanguageIdentifier)
        """
        assert self._conn == None, "Cannot set credentials while connected. Disconnect first."
        self.user, self.pwd = username, password
            
    def setProxy(self, proxyHost, proxyPort):
        """
        Set an HTTP proxy
        """
        assert self._conn == None, "Cannot set proxy while connected. Disconnect first."
        self.proxyHost, self.proxyPort = proxyHost, proxyPort

    def connect(self):
        self._conn = self._headers = self._UrlPrefix = None #clean start
        if self.proxyHost == None:
            self._conn = httplib.HTTPSConnection(self.sOXService)
            self._UrlPrefix = "" 
        else:
            self._conn = httplib.HTTPConnection(self.proxyHost, self.proxyPort)
            self._UrlPrefix = "https://" +  self.sOXService
        #connection!
        self._conn.connect()
        
        
        self._headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"}
        if self.user != None:
            #authentification!
            params = urllib.urlencode({'username': self.user, 'password': self.pwd})
            self._conn.request("POST", self._UrlPrefix + self.sOXAuthentif, params, self._headers)
            response = self._conn.getresponse()
            if response.status == 200:
                logging.info("OpenXerox Authentication successful")
                data = response.read()
                # Parse Json response to retrieve the access token
                tok = json.loads(data)
                atok = tok['access_token']
                self._headers['Authorization'] = 'WRAP access_token="%s"'%atok
            else:
                logging.info("OpenXerox Authentication failed")
                raise Exception("OpenXerox Authentication failed")

    def do(self, sOperation, dicArgs):
        """
        call the operation with the parameters given as a dictionary
        
        Look at the REST API of the service to understand what to pass in the dictionary (follow Api Docs link on Open Xerox)
        For instance for the 'GetLanguageForString' operation of the 'LanguageIdentifier' service, one must pass something like:
            {'document':'Good morning world!'}
            
        return the data as produced by the operation
        """
        assert self._conn != None, "Cannot call this operation. Connect first."
        logging.debug("%s::%s : '''%s'''"%(self.serviceName, sOperation, dicArgs))
        
        # Set method parameters
        params = urllib.urlencode(dicArgs)
        
        # Call the method of the service (replace the method & service name)
        self._conn.request("POST", self._UrlPrefix + self.sOXOperation%(self.serviceName, sOperation)
                           , params, self._headers)
        response = self._conn.getresponse()
    
        # Get response
        data = response.read()
        logging.debug("\t---> %s"%data)

        return data    

    def disconnect(self):
        self._conn.close()
        self._conn = None
        
# ------------------------------------------------------------------------------------------------------
if __name__ == "__main__":
    logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.DEBUG)
    
    ox = Client("LanguageIdentifier")
    #ox.setProxy("PROXY HOST", PROXY PORT)
    
    #do we want to authentify on OpenXerox?
    if False:
        user=raw_input("OpenXerox username=?")
        pwd=raw_input("OpenXerox password=?")
        ox.setCredentials(user, pwd)
        
    ox.connect()
    
    for i in range(3):
        ox.do("GetLanguageForString", {'document':"good morning world (%d)"%i})
        
    ox.disconnect()