public function execute(Request $request, Response $response)
 {
     parent::execute($request, $response);
     Logger::info("Starting processing of listener request from {$this->request->getClientIp()}");
     try {
         $this->doIngressSecurity();
         $soapData = $request->getRawRequest();
         $tl = Logger::getTaggedLogger('RawData');
         $tl->info($soapData);
         $response->sendHeaders();
         /* --- Unfortunately because of how PHP handles SOAP requests we cannot do the fully wrapped
         					loop like we could in the REST listener. Instead it is up to the listener itself to
         					do the required call to $this->processMessage( $msg ).
         
         					It is also expected that inside the handle() context that an exception will throw a SOAP
         					fault through $this->server->fault() instead of doing a $response->kill_response() call.
         			*/
         $this->server->setObject($this);
         $this->server->handle($soapData);
         /* We disable output late in the game in case there was a last minute exception that could
         			be handled by the SOAP listener object inside the handle() context. */
         $response->setOutputDisabled();
     } catch (ListenerSecurityException $ex) {
         Logger::notice('Message denied by security policy, death is me.', null, $ex);
         $response->setStatusCode(403, "Not authorized.");
     } catch (\Exception $ex) {
         Logger::error('Listener threw an unknown exception, death is me.', null, $ex);
         $response->setStatusCode(500, "Unknown listener exception.");
     }
     Logger::info('Finished processing listener request');
 }
 public function execute(Request $request, Response $response)
 {
     parent::execute($request, $response);
     Logger::info("Starting processing of listener request from {$this->request->getClientIp()}");
     try {
         $this->doIngressSecurity();
         $msgs = $this->parseEnvelope($request);
         if (is_array($msgs)) {
             foreach ($msgs as $msg) {
                 $this->processMessage($msg);
             }
         }
         $this->ackEnvelope();
     } catch (ListenerSecurityException $ex) {
         Logger::notice('Message denied by security policy, death is me.', null, $ex);
         $response->setStatusCode(403, "Not authorized.");
     } catch (ListenerDataException $ex) {
         Logger::error('Listener received request it could not process, death is me.', null, $ex);
         $response->setStatusCode(500, 'Received data could not be processed.');
     } catch (Core\ConfigurationException $ex) {
         Logger::alert('Some sad panda gave me a bad configuration.', null, $ex);
         $response->setStatusCode(500, "Configuration error.");
     } catch (\Exception $ex) {
         Logger::error('Listener threw an unknown exception, death is me.', null, $ex);
         $response->setStatusCode(500, "Unknown listener exception");
     }
     Logger::info('Finished processing listener request');
 }
 /**
  * Do the actual work of the script.
  */
 public function execute()
 {
     $this->datastore = BaseQueueConsumer::getQueue($this->getOption('queue'));
     $startTime = time();
     $messageCount = 0;
     // Open the file for read
     $infile = $this->getArgument('file');
     $f = fopen($infile, 'r');
     if (!$f) {
         $this->error("Could not open {$infile} for read", true);
     }
     // Do the loop!
     while (($line = fgets($f)) !== false) {
         if (substr($line, 0, 4) === 'raw=') {
             $message = $this->decodeLegacyMessage($line);
         } else {
             $message = json_decode($line, true);
         }
         if ($message === null) {
             Logger::error("Invalid line: {$line}");
             continue;
         }
         $this->datastore->push($message);
         $messageCount++;
         if ($messageCount % 1000 == 0) {
             print '.';
         }
     }
     print '\\n';
     $elapsedTime = time() - $startTime;
     Logger::info("Imported {$messageCount} messages from {$infile} in {$elapsedTime} seconds.");
 }
 public function parse($path)
 {
     $csv = new HeadedCsvReader($path, ',', 4096, 0);
     while ($csv->valid()) {
         try {
             $this->parseLine($csv);
             $csv->next();
         } catch (DataFileException $ex) {
             Logger::error($ex->getMessage());
         }
     }
     return $this->fileData;
 }
 /**
  * Do the actual work of the script.
  */
 public function execute()
 {
     Logger::info('Info log message');
     Logger::debug('Debug log message');
     Logger::notice('Notice...');
     Logger::getTaggedLogger('RawData')->info('This should be tagged RawData');
     Logger::warning('Warning!', array('foo' => 'bar'));
     try {
         $this->throwException();
     } catch (SmashPigException $ex) {
         Logger::error('ERROR!!!!', null, $ex);
     }
 }
 public function execute(ListenerMessage $msg)
 {
     // Bail out if not a refund
     if (get_class($msg) !== self::MESSAGE_CLASS) {
         return true;
     }
     $refundId = $msg->getGatewayTransactionId();
     Logger::info("Looking up ID of original transaction for refund {$refundId}");
     try {
         $parentId = AmazonApi::findRefundParentId($refundId);
         $msg->setParentId($parentId);
         return true;
     } catch (SmashPigException $ex) {
         Logger::error($ex->getMessage());
         return false;
     }
 }
 public function parseFile($path)
 {
     $this->path = $path;
     $this->file = fopen($path, 'r');
     $ignoreLines = 1;
     for ($i = 0; $i < $ignoreLines; $i++) {
         fgets($this->file);
     }
     while ($line = fgetcsv($this->file, 0, ';', '"', '\\')) {
         try {
             $this->parseLine($line);
         } catch (NormalizationException $ex) {
             // TODO: actually throw these below
             Logger::error($ex->getMessage());
         }
     }
     fclose($this->file);
     return $this->fileData;
 }
 public function cancel($pspReference)
 {
     $data = new WSDL\cancel();
     $data->modificationRequest = new WSDL\ModificationRequest();
     $data->modificationRequest->merchantAccount = $this->account;
     $data->modificationRequest->originalReference = $pspReference;
     $tl = new TaggedLogger('RawData');
     $tl->info('Launching SOAP cancel request', $data);
     try {
         $resp = $this->soapClient->cancel($data);
     } catch (\Exception $ex) {
         Logger::error('SOAP cancel request threw exception!', null, $ex);
         return false;
     }
     if ($resp->cancelResult->response == '[cancel-received]') {
         return $resp->cancelResult->pspReference;
     } else {
         Logger::error('SOAP cancel request did not work as expected!', $resp);
         return false;
     }
 }
 /**
  * Will run all the actions that are loaded (from the 'actions' configuration
  * node) and that are applicable to this message type. Will return true
  * if all actions returned true. Otherwise will return false. This implicitly
  * means that the message will be re-queued if any action fails. Therefore
  * all actions need to be idempotent.
  *
  * @returns bool True if all actions were successful. False otherwise.
  */
 public function runActionChain()
 {
     $retval = true;
     // TODO: Cache this?
     $actions = Context::get()->getConfiguration()->val('actions');
     foreach ($actions as $actionClassName) {
         $action = new $actionClassName();
         if ($action instanceof IListenerMessageAction) {
             Logger::debug("Running action {$actionClassName}.");
             if (!$action->execute($this)) {
                 Logger::info("Action {$actionClassName} did not execute properly, will re-queue.");
                 $retval = false;
                 break;
             } else {
                 Logger::debug("Action returned success.");
             }
         } else {
             Logger::error("Entry under actions node '{$actionClassName}' does not implement IListenerActionMessage");
         }
     }
     return $retval;
 }
 /**
  * Do the actual work of the script.
  */
 public function execute()
 {
     $this->datastore = new StompDataStore($this->getOption('queue'));
     $this->damagedDatastore = new StompDataStore($this->getOption('damaged-queue'));
     $startTime = time();
     $messageCount = 0;
     $successCount = 0;
     do {
         $jobObj = $this->datastore->queueGetObject();
         if (!$jobObj) {
             // No more jobs available to run :'(
             break;
         }
         $success = false;
         if ($jobObj instanceof \SmashPig\Core\Jobs\RunnableJob) {
             try {
                 if ($jobObj->execute()) {
                     $success = true;
                 } else {
                     Logger::info("Job tells us that it did not successfully " . "execute. Sending to damaged message queue.");
                 }
             } catch (Exception $ex) {
                 Logger::error("Job threw exception. Sending to damaged message queue.", null, $ex);
             }
         } else {
             Logger::warning(get_class($jobObj) . " is not an instance of RunnableJob. " . "Could not execute and sending to damaged message queue.");
         }
         if ($success) {
             $successCount += 1;
         } else {
             $this->damagedDatastore->addObject($jobObj);
         }
         $this->datastore->queueAckObject();
     } while (time() - $startTime < $this->getOption('time-limit') && ++$messageCount < $this->getOption('max-messages'));
     $elapsedTime = time() - $startTime;
     Logger::info("Processed {$messageCount} ({$successCount} successful) jobs in {$elapsedTime} seconds.");
 }
 /**
  * Remove objects with the same serialization type and correlation ID from the
  * persistent store.
  *
  * @param KeyedOpaqueStorableObject $protoObj Prototype to remove.
  *
  * @return int Count of messages removed.
  */
 public function removeObjects(KeyedOpaqueStorableObject $protoObj)
 {
     $className = get_class($protoObj);
     $count = 0;
     // Look up all by correlation ID and then remove them if they match in keys/classes
     $idpath = $this->keysPath . '/correlationId/' . DiskFileDataStore::escapeName($protoObj->correlationId) . '/*';
     $classpath = $this->keysPath . '/class/' . $this->escapeName($className);
     foreach (glob($idpath) as $filename) {
         $filePathParts = explode(DIRECTORY_SEPARATOR, $filename);
         $filename = end($filePathParts);
         if (file_exists($classpath . '/' . $filename)) {
             // It's a match! DELETE IT ALL!
             unlink($this->objectsPath . '/' . $filename);
             $this->removeKeyedLinkingFile('class', $className, $filename);
             foreach (explode('.', $filename) as $key) {
                 $parts = explode('=', $key);
                 if (count($parts) === 2) {
                     $this->removeKeyedLinkingFile($parts[0], $parts[1], $filename);
                 } elseif (count($parts) === 1) {
                     // Do nothing here; it's a non keyable value (or the cid, but that's handled elsewhere)
                 } else {
                     Logger::error("Whilst removing a disk linked file '{$filename}', I encountered a strange key '{$key}' and might have missed a file.");
                 }
             }
             $count++;
         }
     }
     return $count;
 }
 /**
  * Writes an error message to the console
  *
  * @param string $string Message to write
  * @param bool   $fatal  True if the script should exit immediately and set an error code
  */
 public static function error($string, $fatal = false)
 {
     if ($fatal) {
         Logger::alert($string);
         exit(1);
     } else {
         Logger::error($string);
     }
 }
 protected function createAdyenMsgObjFromItem(WSDL\NotificationRequestItem $item)
 {
     Logger::info('Creating Adyen message object from data.');
     $msg = AdyenMessage::getInstanceFromWSDL($item);
     if ($msg === false) {
         Logger::error('Listener message object could not be created. Unknown type!', $item);
         return false;
     } else {
         $className = get_class($msg);
         Logger::info("Listener message of type {$className} created.");
     }
     return $msg;
 }
 /**
  * Acknowledges and replaces, into the backing data store, the current queue message
  */
 public function queueIgnoreObject()
 {
     if (!$this->queueMsg) {
         throw new DataStoreTransactionException("No STOMP transaction currently in progress. Cannot requeue a non-existent message!");
     }
     Logger::debug("Acking STOMP message {$this->queueMsg->headers['message-id']}");
     $this->stompObj->ack($this->queueMsg);
     Logger::debug("Re-adding STOMP message to queue");
     $sent = $this->stompObj->send($this->queue_id, $this->queueMsg->body, $this->queueMsg->headers);
     if (!$sent) {
         Logger::error("Could not re-queue message to '{$this->queue_id}' on '{$this->uri}'", $this->queueMsg);
         throw new DataStoreException("Could not re-queue message to '{$this->queue_id}' on '{$this->uri}'");
     }
     $this->queueMsg = null;
     Logger::info("STOMP message requeued from '{$this->queue_id}' on '{$this->uri}'");
 }
 /**
  * @param array $message The data
  * @param Exception $ex The problem
  * @param int| null $retryDate If provided, retry after this timestamp
  * @return int ID of message in damaged database
  */
 protected function sendToDamagedStore($message, Exception $ex, $retryDate = null)
 {
     if ($retryDate) {
         Logger::notice('Message not fully baked. Sticking it back in the oven, to ' . "retry at {$retryDate}", $message);
     } else {
         Logger::error('Error processing message, moving to damaged store.', $message, $ex);
     }
     return $this->damagedDb->storeMessage($message, $this->queueName, $ex->getMessage(), $ex->getTraceAsString(), $retryDate);
 }
 /**
  * Message object specific processing -- security/validation/actions/acknowledgement of message
  * from envelope.
  *
  * This function should not throw an exception -- the intent is to allow envelope processing
  * to continue as normal even if this Message is not normal.
  *
  * @param ListenerMessage $msg Message object to operate on
  *
  * @return bool True if the message was successfully processed.
  */
 protected function processMessage(ListenerMessage $msg)
 {
     try {
         if ($this->doMessageSecurity($msg) && $msg->validate() && $msg->runActionChain() && $this->ackMessage($msg)) {
             return true;
         } else {
             return false;
         }
     } catch (\Exception $ex) {
         Logger::error('Failed message security check: ' . $ex->getMessage());
     }
     // We caught exceptions: therefore the message was not correctly processed.
     return false;
 }