dispatchBySeller

@author Tom Haskins-Vaughan <tom@harvestcloud.com>
@since  2012-05-14

@todo   Peform some sanity checks

@param  \HarvestCloud\CoreBundle\Entity\ExchangeManager $exchange
166121
public function dispatchBySeller(\HarvestCloud\CoreBundle\Entity\Exchange $exchange)
    {
        $this->setStatusCode(self::STATUS_IN_TRANSIT_TO_HUB);

        // Create Hub Fee Invoice
        $hubFeeInvoice = new \HarvestCloud\CoreBundle\Entity\Invoice\HubFeeInvoice($this);
        $hubFeeInvoice->post();
        $this->setHubFeeInvoice($hubFeeInvoice);

        // Create Order Invoice
        $invoice = new \HarvestCloud\CoreBundle\Entity\Invoice\OrderInvoice($this);
        $invoice->post();
        $this->setOrderInvoice($invoice);

        // Create Posting Fee Invoice
        $postingFeeInvoice = new \HarvestCloud\CoreBundle\Entity\Invoice\PostingFeeInvoice($this, $exchange);
        $postingFeeInvoice->post();
        $this->setPostingFeeInvoice($postingFeeInvoice);
    }
1161666
@Override
   public Object invoke(Exchange exchange, Object o)
   {
      BindingOperationInfo bop = exchange.getBindingOperationInfo();
      MethodDispatcher md = (MethodDispatcher) exchange.getService().get(MethodDispatcher.class.getName());
      List<Object> params = null;
      if (o instanceof List) {
         params = CastUtils.cast((List<?>) o);
      } else if (o != null) {
         params = new MessageContentsList(o);
      }
      final Object tb = (factory == null) ? targetBean : this.getServiceObject(exchange);
      final Method method = (bop == null) ? null : md.getMethod(bop);
      if (method == null)
      {
         throw Messages.MESSAGES.missingBindingOpeartionAndDispatchedMethod();
      }
      //performance optimization, adjustMethodAndParams currently looks for @UseAsyncMethod (which is expensive) and only performs actions if it's found
      final Method fm = checkForUseAsyncMethod ? adjustMethodAndParams(md.getMethod(bop), exchange, params, tb.getClass()) : method;
      return invoke(exchange, tb, fm, params);
   }
956298
private function dispatchEvent(AbstractResource $resource, $locale)
    {
        return $this->dispatcher->dispatch(
            'export_scorm_'.$resource->getResourceNode()->getResourceType()->getName(),
            'Claroline\\ScormBundle\\Event\\ExportScormResourceEvent',
            [$resource, $locale]
        );
    }
725438
public function getExchangeRate(ExchangeRateQuery $exchangeQuery): ExchangeRateContract
    {
        $currencyPair = $exchangeQuery->getCurrencyPair();

        $response = $this->request(
            sprintf(
                self::LATEST_URL,
                strtolower($currencyPair->getBaseCurrency()),
                strtolower($currencyPair->getQuoteCurrency())
            )
        );

        $data = StringUtil::jsonToArray($response);

        if (!$data['success']) {
            $message = !empty($data['error']) ? $data['error'] : 'Unknown error';

            throw new Exception($message);
        }

        $date = (new \DateTime())->setTimestamp($data['timestamp']);

        return $this->createRate($currencyPair, (float) ($data['ticker']['price']), $date);
    }
347354
private function dispatchEvent($em, $event)
    {
        $eventArgs = new LifecycleEventArgs(null, $em);

        $em->getEventManager()
           ->dispatchEvent($event, $eventArgs);
    }
688687
public function exchangeArray($input)
    {
        foreach ($input as $item) {
            $this->throwExceptionIfObjectIsNotInstanceOfTheClass($item);
        }

        parent::exchangeArray($input);
    }
282077
private void dispatchRequest(final HttpServerExchange exchange, final ServletRequestContext servletRequestContext, final ServletChain servletChain, final DispatcherType dispatcherType) throws Exception {
        HttpHandler next=null;
        try{
            //lets get access of superclass private fields using reflection:
            Field nextField = ServletInitialHandler.class.getDeclaredField("next");
            nextField.setAccessible(true);
            next = (HttpHandler)nextField.get(this);
            nextField.setAccessible(false);
        }catch(NoSuchFieldException | IllegalAccessException e){
            throw new ServletException(e);
        }

        servletRequestContext.setDispatcherType(dispatcherType);
        servletRequestContext.setCurrentServlet(servletChain);
        if (dispatcherType == DispatcherType.REQUEST || dispatcherType == DispatcherType.ASYNC) {
            super.handleFirstRequest(exchange, servletChain, servletRequestContext, servletRequestContext.getServletRequest(), servletRequestContext.getServletResponse());
        } else {
            next.handleRequest(exchange);
        }
    }
625035
public void handleDirectRequest(HttpServerExchange exchange) {
        Log.Info(this,"direct request received "+exchange);
        getDirectRequestResponse(exchange.getRequestPath()).then( (s,err) -> {
            exchange.setResponseCode(200);
            exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html; charset=utf-8");
            exchange.getResponseSender().send(s == null  ? ""+err : s );
        });
    }
579772
public function initialize($instance, ServiceLocatorInterface $serviceLocator)
	{
        if ($instance instanceof CurrencyExchangerAwareInterface) {
            if ($serviceLocator instanceof AbstractPluginManager) {
            	$serviceLocator = $serviceLocator->getServiceLocator();
            }

            $exchanger = $serviceLocator->get(CurrencyExchangerInterface::class);
            $instance->setCurrencyExchanger($exchanger);
        }
	}
347625
protected function createExchangeForMessageFromURI(MessageInterface $message, $from)
    {
        $version = $message->getContext()->get(Context::FLOWS_VERSION);
        $params = $this->itineraryResolver->getItineraryParams($from, $version);
        $itinerary = $params[InternalRouter::KEY_ITINERARY];

        $exchange = new Exchange($message, clone $itinerary);
        $exchange->setHeader(Exchange::HEADER_HANDLER, $this->getId());
        $exchange->setHeader(Exchange::HEADER_FROM, $from);

        foreach ($this->itineraryResolver->filterItineraryParamsToPropagate($params) as $key => $value) {
            $exchange->setHeader($key, $value);
        }

        return $exchange;
    }
1262536
public function indexAction()
    {
        // We first set the currentLocation to be that of the Exchange's
        // default Location
        $currentLocation = $this->get('exchange_manager')
            ->getExchange()
            ->getProfile()
            ->getDefaultLocation()
        ;

        // If user is authenticated, use the current Profile's default Location
        if ($this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY')){
            $currentLocation = $this->getCurrentProfile()->getDefaultLocation();
        }

        // Set up an empty filter
        $filter = new ProductFilter();
        $filter->setLatitude($currentLocation->getLatitude());
        $filter->setLongitude($currentLocation->getLongitude());
        $filter->setRange(100);

        $products = $this->getRepo('Product')
            ->findForSearchFilter($filter, $this->getCurrentCart())
        ;

        return $this->render('HarvestCloudCoreBundle:Buyer/Default:index.html.twig', array(
          'products' => $products,
        ));
    }
165315
private function retrieveExchangeRateFor(Currency $currency): void
    {
        $conversion = sprintf('%s_%s', $this->baseCurrency->getCode(), $currency->getCode());

        $response = $this->client->request('GET', self::EXCHANGE_RATE_API_URL . '/api/v6/convert', [
            'query' => ['q' => $conversion]
        ]);

        $data = json_decode($response->getBody(), true);

        if (! array_key_exists($conversion, $data['results'])) {
            throw CurrencyConverterApiException::currencyNotFound($currency->getCode());
        }

        $this->exchangeRates[$currency->getCode()] = (float) $data['results'][$conversion]['val'];
    }
1323333
public function _handleItemAfterSync($item, $result)
    {
        $curlError = $this->_checkCurlError($item);

        if (!$curlError) {
            if (isset($result->message) && !isset($result->id)) {
                $item->setImportStatus(\Dotdigitalgroup\Email\Model\Importer::FAILED)
                    ->setMessage($result->message);

                $this->importerResource->save($item);
            } elseif (isset($result->id) && !isset($result->message)) {
                $item->setImportStatus(\Dotdigitalgroup\Email\Model\Importer::IMPORTING)
                    ->setImportId($result->id)
                    ->setImportStarted(time())
                    ->setMessage('');
                $this->importerResource->save($item);
            } else {
                $message = (isset($result->message)) ? $result->message : 'Error unknown';
                $item->setImportStatus(\Dotdigitalgroup\Email\Model\Importer::FAILED)
                    ->setMessage($message);

                //If result id
                if (isset($result->id)) {
                    $item->setImportId($result->id);
                }

                $this->importerResource->save($item);
            }
        }
    }
817652
public function send(\BearFramework\Emails\Email $email): void
    {
        $app = App::get();
        $email = clone($email);

        if ($this->hasEventListeners('beforeSendEmail')) {
            $eventDetails = new \BearFramework\Emails\BeforeSendEmailEventDetails($email);
            $this->dispatchEvent('beforeSendEmail', $eventDetails);
            if ($eventDetails->preventDefault) {
                return;
            }
        }

        if (empty($this->senders)) {
            throw new \Exception('No email senders added.');
        }

        foreach ($this->senders as $sender) {
            if (is_callable($sender)) {
                $sender = call_user_func($sender);
            }
            if (is_string($sender)) {
                $sender = new $sender();
            }
            if ($sender instanceof \BearFramework\Emails\ISender) {
                if ($sender->send($email)) {
                    if ($this->hasEventListeners('sendEmail')) {
                        $eventDetails = new \BearFramework\Emails\SendEmailEventDetails($email);
                        $this->dispatchEvent('sendEmail', $eventDetails);
                    }
                    return;
                }
            }
        }
        throw new \Exception('No email sender is capable of sending the email provided.');
    }
460583
@Override
    public void handleRequest(final HttpServerExchange exchange) throws Exception {
        if(exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }
        SecurityContext context = exchange.getSecurityContext();
        if (context.authenticate()) {
            if(!exchange.isComplete()) {
               next.handleRequest(exchange);
            }
        } else {
            if(exchange.getStatusCode() >= StatusCodes.BAD_REQUEST && !exchange.isComplete()) {
                ServletRequestContext src = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY);
                src.getOriginalResponse().sendError(exchange.getStatusCode());
            } else {
                exchange.endExchange();
            }
        }
    }
1102725
public function setLineItem(\HarvestCloud\CoreBundle\Entity\OrderLineItem $lineItem)
    {
        $this->lineItem = $lineItem;
        $lineItem->setStockTransaction($this);
    }
265706
public function binding($vhost, $exchange, $queue)
    {
        return $this->client->send(sprintf('/api/bindings/%s/e/%s/q/%s', urlencode($vhost), urlencode($exchange), urlencode($queue)));
    }