PageRenderTime 6ms CodeModel.GetById 42ms app.highlight 22ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/storage-2009-04-14/library/Microsoft/WindowsAzure/Storage/Queue.php

#
PHP | 560 lines | 299 code | 57 blank | 204 comment | 84 complexity | c1e929e0f2767bc29021218b5fdd2f98 MD5 | raw file
  1<?php
  2/**
  3 * Copyright (c) 2009, RealDolmen
  4 * All rights reserved.
  5 *
  6 * Redistribution and use in source and binary forms, with or without
  7 * modification, are permitted provided that the following conditions are met:
  8 *     * Redistributions of source code must retain the above copyright
  9 *       notice, this list of conditions and the following disclaimer.
 10 *     * Redistributions in binary form must reproduce the above copyright
 11 *       notice, this list of conditions and the following disclaimer in the
 12 *       documentation and/or other materials provided with the distribution.
 13 *     * Neither the name of RealDolmen nor the
 14 *       names of its contributors may be used to endorse or promote products
 15 *       derived from this software without specific prior written permission.
 16 *
 17 * THIS SOFTWARE IS PROVIDED BY RealDolmen ''AS IS'' AND ANY
 18 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 19 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 20 * DISCLAIMED. IN NO EVENT SHALL RealDolmen BE LIABLE FOR ANY
 21 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 22 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 24 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 26 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 27 *
 28 * @category   Microsoft
 29 * @package    Microsoft_WindowsAzure
 30 * @subpackage Storage
 31 * @copyright  Copyright (c) 2009, RealDolmen (http://www.realdolmen.com)
 32 * @license    http://todo     name_todo
 33 * @version    $Id: Blob.php 24241 2009-07-22 09:43:13Z unknown $
 34 */
 35
 36/**
 37 * @see Microsoft_WindowsAzure_Credentials_SharedKey
 38 */
 39require_once 'Microsoft/WindowsAzure/Credentials/SharedKey.php';
 40
 41/**
 42 * @see Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract
 43 */
 44require_once 'Microsoft/WindowsAzure/RetryPolicy/RetryPolicyAbstract.php';
 45
 46/**
 47 * @see Microsoft_Http_Client
 48 */
 49require_once 'Microsoft/Http/Client.php';
 50
 51/**
 52 * @see Microsoft_Http_Response
 53 */
 54require_once 'Microsoft/Http/Response.php';
 55
 56/**
 57 * @see Microsoft_WindowsAzure_Storage
 58 */
 59require_once 'Microsoft/WindowsAzure/Storage.php';
 60
 61/**
 62 * Microsoft_WindowsAzure_Storage_QueueInstance
 63 */
 64require_once 'Microsoft/WindowsAzure/Storage/QueueInstance.php';
 65
 66/**
 67 * Microsoft_WindowsAzure_Storage_QueueMessage
 68 */
 69require_once 'Microsoft/WindowsAzure/Storage/QueueMessage.php';
 70
 71/**
 72 * @see Microsoft_WindowsAzure_Exception
 73 */
 74require_once 'Microsoft/WindowsAzure/Exception.php';
 75
 76
 77/**
 78 * @category   Microsoft
 79 * @package    Microsoft_WindowsAzure
 80 * @subpackage Storage
 81 * @copyright  Copyright (c) 2009, RealDolmen (http://www.realdolmen.com)
 82 * @license    http://phpazure.codeplex.com/license
 83 */
 84class Microsoft_WindowsAzure_Storage_Queue extends Microsoft_WindowsAzure_Storage
 85{
 86	/**
 87	 * Maximal message size (in bytes)
 88	 */
 89	const MAX_MESSAGE_SIZE = 8388608;
 90	
 91	/**
 92	 * Maximal message ttl (in seconds)
 93	 */
 94	const MAX_MESSAGE_TTL = 604800;
 95	
 96	/**
 97	 * Creates a new Microsoft_WindowsAzure_Storage_Queue instance
 98	 *
 99	 * @param string $host Storage host name
100	 * @param string $accountName Account name for Windows Azure
101	 * @param string $accountKey Account key for Windows Azure
102	 * @param boolean $usePathStyleUri Use path-style URI's
103	 * @param Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy Retry policy to use when making requests
104	 */
105	public function __construct($host = Microsoft_WindowsAzure_Storage::URL_DEV_QUEUE, $accountName = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_ACCOUNT, $accountKey = Microsoft_WindowsAzure_Credentials_CredentialsAbstract::DEVSTORE_KEY, $usePathStyleUri = false, Microsoft_WindowsAzure_RetryPolicy_RetryPolicyAbstract $retryPolicy = null)
106	{
107		parent::__construct($host, $accountName, $accountKey, $usePathStyleUri, $retryPolicy);
108		
109		// API version
110		$this->_apiVersion = '2009-04-14';
111	}
112	
113	/**
114	 * Check if a queue exists
115	 * 
116	 * @param string $queueName Queue name
117	 * @return boolean
118	 */
119	public function queueExists($queueName = '')
120	{
121		if ($queueName === '') {
122			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
123		}
124		if (!self::isValidQueueName($queueName)) {
125		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
126		}
127			
128		// List queues
129        $queues = $this->listQueues($queueName, 1);
130        foreach ($queues as $queue) {
131            if ($queue->Name == $queueName) {
132                return true;
133            }
134        }
135        
136        return false;
137	}
138	
139	/**
140	 * Create queue
141	 *
142	 * @param string $queueName Queue name
143	 * @param array  $metadata  Key/value pairs of meta data
144	 * @return object Queue properties
145	 * @throws Microsoft_WindowsAzure_Exception
146	 */
147	public function createQueue($queueName = '', $metadata = array())
148	{
149		if ($queueName === '') {
150			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
151		}
152		if (!self::isValidQueueName($queueName)) {
153		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
154		}
155			
156		// Create metadata headers
157		$headers = array();
158		$headers = array_merge($headers, $this->_generateMetadataHeaders($metadata)); 
159		
160		// Perform request
161		$response = $this->_performRequest($queueName, '', Microsoft_Http_Client::PUT, $headers);			
162		if ($response->isSuccessful()) {
163		    return new Microsoft_WindowsAzure_Storage_QueueInstance(
164		        $queueName,
165		        $metadata
166		    );
167		} else {
168			throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
169		}
170	}
171	
172	/**
173	 * Get queue
174	 * 
175	 * @param string $queueName  Queue name
176	 * @return Microsoft_WindowsAzure_Storage_QueueInstance
177	 * @throws Microsoft_WindowsAzure_Exception
178	 */
179	public function getQueue($queueName = '')
180	{
181		if ($queueName === '') {
182			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
183		}
184		if (!self::isValidQueueName($queueName)) {
185		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
186		}
187		    
188		// Perform request
189		$response = $this->_performRequest($queueName, '?comp=metadata', Microsoft_Http_Client::GET);	
190		if ($response->isSuccessful()) {
191		    // Parse metadata
192		    $metadata = $this->_parseMetadataHeaders($response->getHeaders());
193
194		    // Return queue
195		    $queue = new Microsoft_WindowsAzure_Storage_QueueInstance(
196		        $queueName,
197		        $metadata
198		    );
199		    $queue->ApproximateMessageCount = intval($response->getHeader('x-ms-approximate-message-count'));
200		    return $queue;
201		} else {
202		    throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
203		}
204	}
205	
206	/**
207	 * Get queue metadata
208	 * 
209	 * @param string $queueName  Queue name
210	 * @return array Key/value pairs of meta data
211	 * @throws Microsoft_WindowsAzure_Exception
212	 */
213	public function getQueueMetadata($queueName = '')
214	{
215		if ($queueName === '') {
216			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
217		}
218		if (!self::isValidQueueName($queueName)) {
219		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
220		}
221			
222	    return $this->getQueue($queueName)->Metadata;
223	}
224	
225	/**
226	 * Set queue metadata
227	 * 
228	 * Calling the Set Queue Metadata operation overwrites all existing metadata that is associated with the queue. It's not possible to modify an individual name/value pair.
229	 *
230	 * @param string $queueName  Queue name
231	 * @param array  $metadata       Key/value pairs of meta data
232	 * @throws Microsoft_WindowsAzure_Exception
233	 */
234	public function setQueueMetadata($queueName = '', $metadata = array())
235	{
236		if ($queueName === '') {
237			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
238		}
239		if (!self::isValidQueueName($queueName)) {
240		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
241		}
242		if (count($metadata) == 0) {
243		    return;
244		}
245		    
246		// Create metadata headers
247		$headers = array();
248		$headers = array_merge($headers, $this->_generateMetadataHeaders($metadata)); 
249		
250		// Perform request
251		$response = $this->_performRequest($queueName, '?comp=metadata', Microsoft_Http_Client::PUT, $headers);
252
253		if (!$response->isSuccessful()) {
254			throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
255		}
256	}
257	
258	/**
259	 * Delete queue
260	 *
261	 * @param string $queueName Queue name
262	 * @throws Microsoft_WindowsAzure_Exception
263	 */
264	public function deleteQueue($queueName = '')
265	{
266		if ($queueName === '') {
267			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
268		}
269		if (!self::isValidQueueName($queueName)) {
270		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
271		}
272			
273		// Perform request
274		$response = $this->_performRequest($queueName, '', Microsoft_Http_Client::DELETE);
275		if (!$response->isSuccessful()) {
276			throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
277		}
278	}
279	
280	/**
281	 * List queues
282	 *
283	 * @param string $prefix     Optional. Filters the results to return only queues whose name begins with the specified prefix.
284	 * @param int    $maxResults Optional. Specifies the maximum number of queues to return per call to Azure storage. This does NOT affect list size returned by this function. (maximum: 5000)
285	 * @param string $marker     Optional string value that identifies the portion of the list to be returned with the next list operation.
286	 * @param int    $currentResultCount Current result count (internal use)
287	 * @return array
288	 * @throws Microsoft_WindowsAzure_Exception
289	 */
290	public function listQueues($prefix = null, $maxResults = null, $marker = null, $currentResultCount = 0)
291	{
292	    // Build query string
293	    $queryString = '?comp=list';
294	    if (!is_null($prefix)) {
295	        $queryString .= '&prefix=' . $prefix;
296	    }
297	    if (!is_null($maxResults)) {
298	        $queryString .= '&maxresults=' . $maxResults;
299	    }
300	    if (!is_null($marker)) {
301	        $queryString .= '&marker=' . $marker;
302	    }
303	        
304		// Perform request
305		$response = $this->_performRequest('', $queryString, Microsoft_Http_Client::GET);	
306		if ($response->isSuccessful()) {
307			$xmlQueues = $this->_parseResponse($response)->Queues->Queue;
308			$xmlMarker = (string)$this->_parseResponse($response)->NextMarker;
309
310			$queues = array();
311			if (!is_null($xmlQueues)) {
312				for ($i = 0; $i < count($xmlQueues); $i++) {
313					$queues[] = new Microsoft_WindowsAzure_Storage_QueueInstance(
314						(string)$xmlQueues[$i]->QueueName
315					);
316				}
317			}
318			$currentResultCount = $currentResultCount + count($queues);
319			if (!is_null($maxResults) && $currentResultCount < $maxResults) {
320    			if (!is_null($xmlMarker) && $xmlMarker != '') {
321    			    $queues = array_merge($queues, $this->listQueues($prefix, $maxResults, $xmlMarker, $currentResultCount));
322    			}
323			}
324			if (!is_null($maxResults) && count($queues) > $maxResults) {
325			    $queues = array_slice($queues, 0, $maxResults);
326			}
327			    
328			return $queues;
329		} else {
330			throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
331		}
332	}
333	
334	/**
335	 * Put message into queue
336	 *
337	 * @param string $queueName  Queue name
338	 * @param string $message    Message
339	 * @param int    $ttl        Message Time-To-Live (in seconds). Defaults to 7 days if the parameter is omitted.
340	 * @throws Microsoft_WindowsAzure_Exception
341	 */
342	public function putMessage($queueName = '', $message = '', $ttl = null)
343	{
344		if ($queueName === '') {
345			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
346		}
347		if (!self::isValidQueueName($queueName)) {
348		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
349		}
350		if (strlen($message) > self::MAX_MESSAGE_SIZE) {
351		    throw new Microsoft_WindowsAzure_Exception('Message is too big. Message content should be < 8KB.');
352		}
353		if ($message == '') {
354		    throw new Microsoft_WindowsAzure_Exception('Message is not specified.');
355		}
356		if (!is_null($ttl) && ($ttl <= 0 || $ttl > self::MAX_MESSAGE_SIZE)) {
357		    throw new Microsoft_WindowsAzure_Exception('Message TTL is invalid. Maximal TTL is 7 days (' . self::MAX_MESSAGE_SIZE . ' seconds) and should be greater than zero.');
358		}
359		    
360	    // Build query string
361	    $queryString = '';
362	    if (!is_null($ttl)) {
363	        $queryString .= '?messagettl=' . $ttl;
364	    }
365	        
366	    // Build body
367	    $rawData = '';
368	    $rawData .= '<QueueMessage>';
369	    $rawData .= '    <MessageText>' . base64_encode($message) . '</MessageText>';
370	    $rawData .= '</QueueMessage>';
371	        
372		// Perform request
373		$response = $this->_performRequest($queueName . '/messages', $queryString, Microsoft_Http_Client::POST, array(), false, $rawData);
374
375		if (!$response->isSuccessful()) {
376			throw new Microsoft_WindowsAzure_Exception('Error putting message into queue.');
377		}
378	}
379	
380	/**
381	 * Get queue messages
382	 *
383	 * @param string $queueName         Queue name
384	 * @param string $numOfMessages     Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation.
385	 * @param int    $visibilityTimeout Optional. An integer value that specifies the message's visibility timeout in seconds. The maximum value is 2 hours. The default message visibility timeout is 30 seconds.
386	 * @param string $peek              Peek only?
387	 * @return array
388	 * @throws Microsoft_WindowsAzure_Exception
389	 */
390	public function getMessages($queueName = '', $numOfMessages = 1, $visibilityTimeout = null, $peek = false)
391	{
392		if ($queueName === '') {
393			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
394		}
395		if (!self::isValidQueueName($queueName)) {
396		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
397		}
398		if ($numOfMessages < 1 || $numOfMessages > 32 || intval($numOfMessages) != $numOfMessages) {
399		    throw new Microsoft_WindowsAzure_Exception('Invalid number of messages to retrieve.');
400		}
401		if (!is_null($visibilityTimeout) && ($visibilityTimeout <= 0 || $visibilityTimeout > 7200)) {
402		    throw new Microsoft_WindowsAzure_Exception('Visibility timeout is invalid. Maximum value is 2 hours (7200 seconds) and should be greater than zero.');
403		}
404		    
405	    // Build query string
406	    $query = array();
407    	if ($peek) {
408    	    $query[] = 'peekonly=true';
409    	}
410    	if ($numOfMessages > 1) {
411	        $query[] = 'numofmessages=' . $numOfMessages;
412    	}
413    	if (!$peek && !is_null($visibilityTimeout)) {
414	        $query[] = 'visibilitytimeout=' . $visibilityTimeout;
415    	}   
416    	$queryString = '?' . implode('&', $query);
417	        
418		// Perform request
419		$response = $this->_performRequest($queueName . '/messages', $queryString, Microsoft_Http_Client::GET);	
420		if ($response->isSuccessful()) {
421		    // Parse results
422			$result = $this->_parseResponse($response);
423		    if (!$result) {
424		        return array();
425		    }
426
427		    $xmlMessages = null;
428		    if (count($result->QueueMessage) > 1) {
429    		    $xmlMessages = $result->QueueMessage;
430    		} else {
431    		    $xmlMessages = array($result->QueueMessage);
432    		}
433
434			$messages = array();
435			for ($i = 0; $i < count($xmlMessages); $i++) {
436				$messages[] = new Microsoft_WindowsAzure_Storage_QueueMessage(
437					(string)$xmlMessages[$i]->MessageId,
438					(string)$xmlMessages[$i]->InsertionTime,
439					(string)$xmlMessages[$i]->ExpirationTime,
440					($peek ? '' : (string)$xmlMessages[$i]->PopReceipt),
441					($peek ? '' : (string)$xmlMessages[$i]->TimeNextVisible),
442					base64_decode((string)$xmlMessages[$i]->MessageText)
443			    );
444			}
445			    
446			return $messages;
447		} else {
448			throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
449		}
450	}
451	
452	/**
453	 * Peek queue messages
454	 *
455	 * @param string $queueName         Queue name
456	 * @param string $numOfMessages     Optional. A nonzero integer value that specifies the number of messages to retrieve from the queue, up to a maximum of 32. By default, a single message is retrieved from the queue with this operation.
457	 * @return array
458	 * @throws Microsoft_WindowsAzure_Exception
459	 */
460	public function peekMessages($queueName = '', $numOfMessages = 1)
461	{
462	    return $this->getMessages($queueName, $numOfMessages, null, true);
463	}
464	
465	/**
466	 * Clear queue messages
467	 *
468	 * @param string $queueName         Queue name
469	 * @throws Microsoft_WindowsAzure_Exception
470	 */
471	public function clearMessages($queueName = '')
472	{
473		if ($queueName === '') {
474			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
475		}
476		if (!self::isValidQueueName($queueName)) {
477		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
478		}
479
480		// Perform request
481		$response = $this->_performRequest($queueName . '/messages', '', Microsoft_Http_Client::DELETE);	
482		if (!$response->isSuccessful()) {
483			throw new Microsoft_WindowsAzure_Exception('Error clearing messages from queue.');
484		}
485	}
486	
487	/**
488	 * Delete queue message
489	 *
490	 * @param string $queueName         					Queue name
491	 * @param Microsoft_WindowsAzure_Storage_QueueMessage $message Message to delete from queue. A message retrieved using "peekMessages" can NOT be deleted!
492	 * @throws Microsoft_WindowsAzure_Exception
493	 */
494	public function deleteMessage($queueName = '', Microsoft_WindowsAzure_Storage_QueueMessage $message)
495	{
496		if ($queueName === '') {
497			throw new Microsoft_WindowsAzure_Exception('Queue name is not specified.');
498		}
499		if (!self::isValidQueueName($queueName)) {
500		    throw new Microsoft_WindowsAzure_Exception('Queue name does not adhere to queue naming conventions. See http://msdn.microsoft.com/en-us/library/dd179349.aspx for more information.');
501		}
502		if ($message->PopReceipt == '') {
503		    throw new Microsoft_WindowsAzure_Exception('A message retrieved using "peekMessages" can NOT be deleted! Use "getMessages" instead.');
504		}
505
506		// Perform request
507		$response = $this->_performRequest($queueName . '/messages/' . $message->MessageId, '?popreceipt=' . $message->PopReceipt, Microsoft_Http_Client::DELETE);	
508		if (!$response->isSuccessful()) {
509			throw new Microsoft_WindowsAzure_Exception($this->_getErrorMessage($response, 'Resource could not be accessed.'));
510		}
511	}
512	
513	/**
514	 * Is valid queue name?
515	 *
516	 * @param string $queueName Queue name
517	 * @return boolean
518	 */
519    public static function isValidQueueName($queueName = '')
520    {
521        if (preg_match("/^[a-z0-9][a-z0-9-]*$/", $queueName) === 0) {
522            return false;
523        }
524    
525        if (strpos($queueName, '--') !== false) {
526            return false;
527        }
528    
529        if (strtolower($queueName) != $queueName) {
530            return false;
531        }
532    
533        if (strlen($queueName) < 3 || strlen($queueName) > 63) {
534            return false;
535        }
536            
537        if (substr($queueName, -1) == '-') {
538            return false;
539        }
540    
541        return true;
542    }
543    
544	/**
545	 * Get error message from Microsoft_Http_Response
546	 * 
547	 * @param Microsoft_Http_Response $response Repsonse
548	 * @param string $alternativeError Alternative error message
549	 * @return string
550	 */
551	protected function _getErrorMessage(Microsoft_Http_Response $response, $alternativeError = 'Unknown error.')
552	{
553		$response = $this->_parseResponse($response);
554		if ($response && $response->Message) {
555		    return (string)$response->Message;
556		} else {
557		    return $alternativeError;
558		}
559	}
560}