Native5 APIs Native5 APIs
  • Namespace
  • Class
  • Tree

Namespaces

  • Native5
    • Services
      • Identity
      • Job
      • Messaging
      • Users
    • Users
  • PHP

Classes

  • Job
  • JobManager
  1 <?php
  2 /**
  3  *  Copyright 2012 Native5. All Rights Reserved
  4  *
  5  *  Licensed under the Apache License, Version 2.0 (the "License");
  6  *  You may not use this file except in compliance with the License.
  7  *
  8  *  Unless required by applicable law or agreed to in writing, software
  9  *  distributed under the License is distributed on an "AS IS" BASIS,
 10  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 11  *  See the License for the specific language governing permissions and
 12  *  limitations under the License.
 13  *  PHP version 5.3+
 14  *
 15  * @category  Jobs 
 16  * @package   Native5\Services\Jobs
 17  * @author    Barada Sahu <barry@native5.com>
 18  * @copyright 2012 Native5. All Rights Reserved 
 19  * @license   See attached LICENSE for details
 20  * @version   GIT: $gitid$ 
 21  * @link      http://www.docs.native5.com 
 22  */
 23 
 24 namespace Native5\Services\Job;
 25 
 26 use Native5\Api\ApiClient;
 27 
 28 /**
 29  * JobManager 
 30  * 
 31  * @category  Jobs 
 32  * @package   Native5\Services\Jobs
 33  * @author    Shamik Datta <shamik@native5.com>
 34  * @copyright 2012 Native5. All Rights Reserved 
 35  * @license   See attached NOTICE.md for details
 36  * @version   Release: 1.0 
 37  * @link      http://www.docs.native5.com 
 38  */
 39 class JobManager extends ApiClient {
 40     const API_PATH = 'job/';
 41     const CREATE_JOB = 'create/';
 42     const GET_JOB = '';
 43     const UPDATE_JOB_STATE = 'state/';
 44     const UPDATE_JOB_STATUS = 'status/';
 45     const SET_JOB_RESULT = 'result/';
 46     const DELETE_JOB = 'delete/';
 47 
 48     private $_logger;
 49 
 50     public function __construct() {
 51         parent::__construct();
 52         $this->_logger = $GLOBALS['logger'];
 53     }
 54 
 55     /**
 56      * createJob Create an entry for a long running job
 57      * 
 58      * @param string $serviceName 
 59      * @access public
 60      * @return boolean true if successful, false otherwise
 61      *
 62      * @assert (null) throws Exception
 63      * @assert (array()) throws Exception
 64      * @assert ("testingJob") != null
 65      */
 66     public function createJob($serviceName) {
 67         if (!($_serviceName = $this->_checkString($serviceName)))
 68             throw new \Exception("Invalid non-string or non-numeric service name: ".print_r($serviceName, true));
 69 
 70         $path = self::API_PATH.self::CREATE_JOB;
 71         $request = $this->_remoteServer->post($path)
 72             ->setPostField('name', $_serviceName);
 73 
 74         try {
 75             $response = $request->send();
 76         } catch(\Guzzle\Http\Exception\BadResponseException $e) {
 77             $this->_logger->info($e->getResponse()->getBody('true'), array());
 78             return false;
 79         }
 80  
 81         // Long running job ID
 82         $respBody = $response->getBody(true);
 83         $GLOBALS['logger']->info("Created job with id: ".$respBody, array());
 84 
 85         return $respBody;
 86     }
 87 
 88     public function deleteJob($jobId) {
 89         $jobId = $this->_processJobId($jobId);
 90         $path = self::API_PATH.$jobId.'/'.self::DELETE_JOB;
 91         
 92         $request = $this->_remoteServer->post($path);
 93         try {
 94             $response = $request->send();
 95         } catch(\Guzzle\Http\Exception\BadResponseException $e) {
 96             $this->_logger->info($e->getResponse()->getBody('true'), array());
 97             return false;
 98         }
 99  
100         // True/False
101         $result = $this->_convertToBoolean($response->getBody(true));
102         $GLOBALS['logger']->info("Delete status job for id [ $jobId ]: ".$result, array());
103 
104         return $result;
105     }
106 
107     public function updateJobState($jobId, $state) {
108         // Check for a valid string state
109         if (!($state = $this->_checkString($state)))
110             throw \Exception("Invalid non-string or non-numeric state string: ".print_r($state, true));
111 
112         $jobId = $this->_processJobId($jobId);
113         $path = self::API_PATH.$jobId.'/'.self::UPDATE_JOB_STATE;
114         
115         $res = $this->_sendPut($path, 'state', $state);
116         // True/False
117         $GLOBALS['logger']->info("Updated Job State: ".($res ? "True" : "False"), array());
118 
119         return $res;
120     }
121 
122     public function updateJobStatus($jobId, $status) {
123         // Check for a valid status constant
124         if (($status !== Job::STATUS_CREATED) && ($status !== Job::STATUS_RUNNING) && 
125                 ($status !== Job::STATUS_COMPLETED_SUCCESS ) && ($status !== Job::STATUS_COMPLETED_ERROR))
126             throw new \Exception("Status should be one of the STATUS_ constants defined in the Job class - received: ".print_r($status, true));
127 
128         $jobId = $this->_processJobId($jobId);
129         $path = self::API_PATH.$jobId.'/'.self::UPDATE_JOB_STATUS;
130         
131         $res = $this->_sendPut($path, 'status', $status);
132         // True/False
133         $GLOBALS['logger']->info("Updated Job Status: ".($res ? "True" : "False"), array());
134 
135         return $res;
136     }
137 
138     public function setJobResult($jobId, $result) {
139         $jobId = $this->_processJobId($jobId);
140         $path = self::API_PATH.$jobId.'/'.self::SET_JOB_RESULT;
141         
142         $res = $this->_sendPut($path, 'result', json_encode($result));
143         // True/False
144         $GLOBALS['logger']->info("Set Job Result: ".($res ? "True" : "False"), array());
145 
146         return $res;
147     }
148 
149     /**
150      * getJob Get details of a long running job entry
151      * 
152      * @param string $jobId The job Id
153      *
154      * @access public
155      * @return @see JobStatus 
156      *
157      * @assert (null) throws Exception
158      * @assert (array()) throws Exception
159      */
160     public function getJob($jobId)
161     {
162         $jobId = $this->_processJobId($jobId);
163         $path = self::API_PATH.$jobId.'/'.self::GET_JOB;
164 
165         $request =  $this->_remoteServer->get($path);
166         $request->getQuery();
167         try {
168             $response = $request->send();
169         } catch(\Guzzle\Http\Exception\BadResponseException $e) {
170             $this->_logger->info($e->getResponse()->getBody('true'), array());
171             return false;
172         }
173  
174         return $this->_buildJob($response->json());
175     }
176 
177     private function _buildJob ($jobData) {
178         if (empty($jobData) || !is_array($jobData) || !isset($jobData['SERVICE']) || !isset($jobData['STATUS']))
179             return false;
180 
181         $job = new Job();
182         $job->setServiceName($jobData['SERVICE']);
183         $job->setStatus($jobData['STATUS']);
184         $job->setState(( !empty($jobData['STATE']) ? $jobData['STATE'] : null ));
185         $job->setResult(( !empty($jobData['RESULT']) ? json_decode($jobData['RESULT'], true) : null ));
186 
187         return $job;
188     }
189 
190     private function _sendPut ($apiPath, $key, $val) {
191         $request = $this->_remoteServer->put($apiPath)
192             ->setPostField($key, $val);
193         try {
194             $response = $request->send();
195 
196         } catch(\Guzzle\Http\Exception\BadResponseException $e) {
197             $this->_logger->info($e->getResponse()->getBody('true'), array());
198             return false;
199         }
200  
201         return $this->_convertToBoolean($response->getBody(true));
202     }
203 
204     private function _processJobId($jobId) {
205         if (!($_jobId = $this->_checkString($jobId)))
206             throw new \Exception("Invalid non-string or non-numeric job id: ".$jobId);
207 
208         return $_jobId;
209     }
210 
211     private function _checkString($item) {
212         if (!is_string($item) && !is_numeric($item))
213             return false;
214             
215         $item = "$item";
216         return $item;
217     }
218 
219     private function _convertToBoolean($item) {
220         if (strcmp($item, 'true') === 0)
221             return true;
222         else
223             return false;
224     }
225 }
226 
227