Friday, January 14, 2011

Php accessing Http Webservice

 Calling.php
<?php
require_once 'TibcoConnector.php';

$xmlToSend ="<ProcessDispositionDocumentsRequest xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"";
$xmlToSend.=" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://services.fsdfs.com/schemas/ProcessDispositionDocumentsRequest/1.0.0\">";
$xmlToSend.=" <ProcessDispositionDocumentRequests>";
$xmlToSend.=" <ProcessDispositionDocumentRequest>";
$xmlToSend.=" <ReferenceID>";
//$xmlToSend.=" SCANNER64254643.TIF3128752232343223";
$xmlToSend.=" SCANNER.TIF3".getCurrentTime().getRandomNumber();
$xmlToSend.=" </ReferenceID>";
$xmlToSend.=" <Document>"."tgov3HxLSWv/7/gi6yAoX7/8fF//r8Fxhft46 QFFn/BcLzx6b/xf8gKFOaY9 QFFaNJqRTYXkBQucPv2L"."</Document>";
$xmlToSend.=" <WorkType>Documentation</WorkType>";
$xmlToSend.=" <ClaimNumber>"."801802803"."</ClaimNumber>";
$xmlToSend.=" <MobileNumber>9430245939</MobileNumber>";
$xmlToSend.=" <PostalCode xsi:nil=\"true\" /></ProcessDispositionDocumentRequest>";
$xmlToSend.=" </ProcessDispositionDocumentRequests></ProcessDispositionDocumentsRequest>";

try {
    $output = new TibcoConnector();
    $responseData=$output->passXmlToTibco($xmlToSend);
    $parsedOutput=parseResponseData($responseData);
    echo $parsedOutput;
    if (strlen($responseData)) {
        echo $responseData;
    } else {
        //    echo "Service is Down- Please try again later";
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

function getRandomNumber(){
    srand(time());
    $random = (rand()%100);
    return $random;
}

function getCurrentTime(){
    $time_now=mktime(date('h'),date('i'),date('s'));
    $currentTime= date('h.i.s',$time_now);
    return $currentTime;
}

function parseResponseData($responeData){
    $targetstring = "No Document ID Generated";
    $targetstring1 = "An item already exists for";
    $targetstring2 = "Error";
    $targetstring3 = "SCANNER";
    if(stristr($responeData, $targetstring) === TRUE) {
        return "No Document ID";
    }
    elseif(stristr($responeData, $targetstring1) === TRUE){
        return "This case number is already present";
    }
    elseif(stristr($responeData, $targetstring2) === TRUE){
        return "Error";
    }
    elseif(stristr($responeData, $targetstring3) === TRUE){
        $start=strpos($responeData,$targetstring3);
        $end=strpos($responeData,"Application");
        $inbetweenString = substr($responeData,$start,$start-$end);
        echo $inbetweenString;
    }
}
?>
Tibco connector
<?php
require_once 'RemoteConnector.php';
class TibcoConnector{
protected $_error;
protected $_flag=true;
protected $_count=0;
    public function passXmlToTibco($theData){
        $url = 'http://webservice to access';
        try {
            $output = new Pos_RemoteConnector($url,$theData);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return $output;
    }
}
Remote Connector.php
<?php
class Pos_RemoteConnector
{
    protected $_url;
    protected $_remoteFile;
    protected $_error;
    protected $_urlParts;
    protected $_status;
    public $_flag=true;
    public function __construct($url,$contents)
    {
        $this->_url = $url;
        $this->_contents='xml='.$contents;
        $this->checkURL();
        if (function_exists('curl_init')) {
            $this->useCurl();
        } else {
            echo "Site is down-Please be patience";
        }
    }

    protected function checkURL()
    {
        $flags = FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED;
        $urlOK = filter_var($this->_url, FILTER_VALIDATE_URL, $flags);
        $this->_urlParts = parse_url($this->_url);
        if (!$urlOK || $this->_urlParts['scheme'] != 'http') {
            throw new Exception($this->_url . ' is not a valid URL');
        }
        $domainOK = preg_match('/^[^.]+?\.\w{2}/', $this->_urlParts['host']);
        if (!$urlOK) {
            throw new Exception($this->_url . ' is not a valid URL');
        }
    }
   
    protected function useCurl()
    {
   
        if ($session = curl_init($this->_url)) {
            curl_setopt($session, CURLOPT_HTTPHEADER,array('Service:DocumentManagement',
                                                            'Method:ProcessDispositionDocuments',
                                                            'Version:1.0',
                                                            'Culture:en-US',
                                                            'TimeStamp:2011-01-11 14:55:02.395',
                                                            'SystemUsername:BPM',
                                                            'SystemPassword:test',
                                                            'LineOfBusiness:HandsetInsurance',
                                                            'Application:iWebDocumentUpload',
                                                            'Client:VerizonWireless',
                                                            'Channel:DOC'));
            curl_setopt($session, CURLOPT_HEADER, 0);
            curl_setopt($session, CURLOPT_POST, 1);
            curl_setopt($session, CURLOPT_POSTFIELDS,$this->_contents);
            curl_setopt($session, CURLOPT_PORT, 8104); //Set the port number
            curl_setopt($session, CURLOPT_TIMEOUT, 1500); // times out after 15s
            curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
            $this->_remoteFile = curl_exec($session);
            $this->_status = curl_getinfo($session, CURLINFO_HTTP_CODE);
            curl_close($session);
        } else {
            $this->_error = 'Cannot establish cURL session';
        }
    }
    public function __toString()
    {
        $returnString=$this->_remoteFile;
     if(isset($returnString)&&!empty($returnString)){
         return ">".$this->_remoteFile;
     }
     else{
        return "Tibco Call failed-Try one more time";
     }
    }

    public function getErrorMessage()
    {
        if (is_null($this->_error)) {
            $this->setErrorMessage();
            }
            return $this->_error;
    }

    protected function removeHeaders()
    {
        $parts = preg_split('#\r\n\r\n|\n\n#', $this->_remoteFile);
        if (is_array($parts)) {
            $headers = array_shift($parts);
            $file = implode("\n\n", $parts);
            if (preg_match('#HTTP/1\.\d\s+(\d{3})#', $headers, $m)) {
                $this->_status = $m[1];
            }
            if (preg_match('#Content-Type:([^\r\n]+)#i', $headers, $m)) {
                if (stripos($m[1], 'xml') !== false || stripos($m[1], 'html') !== false) {
                    if (preg_match('/<.+>/s', $file, $m)) {
                        $this->_remoteFile = $m[0];
                    } else {
                        $this->_remoteFile = trim($file);
                    }
                } else {
                    $this->_remoteFile = trim($file);
                }
            }
        }
    }

    protected function setErrorMessage()
    {
        if ($this->_status == 200 && $this->_remoteFile) {
            $this->_error = '';
        } else {
            switch ($this->_status) {
                case 200:
                case 204:
                    $this->_error = 'Connection OK, but file is empty.';
                    break;
                case 301:
                case 302:
                case 303:
                case 307:
                case 410:
                    $this->_error = 'File has been moved or does not exist.';
                    break;
                case 305:
                    $this->_error = 'File must be accessed through a proxy.';
                    break;
                case 400:
                    $this->_error = 'Malformed request.';
                    break;
                case 401:
                case 403:
                    $this->_error = 'You are not authorized to access this page.';
                    break;
                case 404:
                    $this->_error = 'File not found.';
                    break;
                case 407:
                    $this->_error = 'Proxy requires authentication.';
                    break;
                case 408:
                    $this->_error = 'Request timed out.';
                    break;
                case 500:
                    $this->_error = 'The remote server encountered an internal error.';
                    break;
                case 503:
                    $this->_error = 'The server cannot handle the request at the moment.';
                    break;
                default:
                    $this->_error = 'Undefined error. Check URL and domain name.';
                    break;
            }
        }
    }
}

No comments:

Post a Comment