Finish the delivery execution

@throws common_exception_Error
@throws common_exception_NotFound
555613
public function finishDeliveryExecution() {
	    $deliveryExecution = $this->getCurrentDeliveryExecution();
	    if ($deliveryExecution->getUserIdentifier() == common_session_SessionManager::getSession()->getUserUri()) {
            $stateService = $this->getServiceManager()->get(StateServiceInterface::SERVICE_ID);
	        $stateService->finish($deliveryExecution);
	    } else {
	        common_Logger::w('Non owner '.common_session_SessionManager::getSession()->getUserUri().' tried to finish deliveryExecution '.$deliveryExecution->getIdentifier());
	    }
	    $this->redirect($this->getReturnUrl());
	}
478688
public function delete()
    {
        if (!$this->isXmlHttpRequest()) {
            throw new common_exception_BadRequest('wrong request mode');
        }
        $deliveryExecutionUri = tao_helpers_Uri::decode($this->getRequestParameter('uri'));
        $de = $this->getServiceProxy()->getDeliveryExecution($deliveryExecutionUri);

        try {
            $this->getResultStorage($de->getDelivery());

            $deleted = $this->getResultsService()->deleteResult($deliveryExecutionUri);

            $this->returnJson(array('deleted' => $deleted));
        } catch (\common_exception_Error $e) {
            $this->returnJson(array('error' => $e->getMessage()));
        }
    }
405669
final void postComplete() {
        /*
         * On each step, variable f holds current dependents to pop
         * and run.  It is extended along only one path at a time,
         * pushing others to avoid unbounded recursion.
         */
        CompletableFuture<?> f = this; Completion h;
        while ((h = f.stack) != null ||
               (f != this && (h = (f = this).stack) != null)) {
            CompletableFuture<?> d; Completion t;
            if (f.casStack(h, t = h.next)) {
                if (t != null) {
                    if (f != this) {
                        pushStack(h);
                        continue;
                    }
                    h.next = null;    // detach
                }
                f = (d = h.tryFire(NESTED)) == null ? this : d;
            }
        }
    }
928151
public function generate()
    {
        try {
            if (!$this->hasRequestParameter(self::REST_DELIVERY_TEST_ID)) {
                throw new \common_exception_MissingParameter(self::REST_DELIVERY_TEST_ID, $this->getRequestURI());
            }

            $test = $this->getResource($this->getRequestParameter(self::REST_DELIVERY_TEST_ID));
            if (!$test->exists()) {
                throw new \common_exception_NotFound('Unable to find a test associated to the given uri.');
            }

            $label = 'Delivery of ' . $test->getLabel();
            $deliveryClass = $this->getDeliveryClassByParameters();

            $deliveryFactory = $this->getServiceManager()->get(DeliveryFactory::SERVICE_ID);
            /** @var \common_report_Report $report */
            $report = $deliveryFactory->create($deliveryClass, $test, $label);

            if ($report->getType() == \common_report_Report::TYPE_ERROR) {
                $this->logInfo('Unable to generate delivery execution ' .
                    'into taoDeliveryRdf::RestDelivery for test uri ' . $test->getUri());
                throw new \common_Exception('Unable to generate delivery execution.');
            }
            $delivery = $report->getData();

            /** @var DeliveryFactory $deliveryFactoryService */
            $deliveryFactoryService = $this->getServiceManager()->get(DeliveryFactory::SERVICE_ID);
            $initialProperties = $deliveryFactoryService->getInitialPropertiesFromRequest($this->getRequest());
            $delivery = $deliveryFactoryService->setInitialProperties($initialProperties, $delivery);
            $this->returnSuccess(array('delivery' => $delivery->getUri()));
        } catch (\Exception $e) {
            $this->returnFailure($e);
        }
    }
1324069
public function end() {
        ob_start();
        if ($this->matched && count($this->routeCallback)) {
            count($this->before) && $this->emit($this->before);
            foreach ($this->routeCallback as $call) {
                $this->callback($call, $this->req->args);
            }
            count($this->after) && $this->emit($this->after);
        } else if($this->req->method != 'OPTIONS'){
            http_response_code(404);
            print('<h1>404 Not Found</h1>');
        }

        if (ob_get_length()) {
            ob_end_flush();
        }

        exit;
    }
768527
public function byDeliveryExecution()
    {
        try
        {
            $this->checkMethod();

            $this->validateParams(array(self::DELIVERY_EXECUTION));

            $deliveryExecution = $this->getQtiResultService()->getDeliveryExecutionById(
                $this->getRequestParameter(self::DELIVERY_EXECUTION)
            );

            $this->returnValidXml($this->getQtiResultService()->getDeliveryExecutionXml($deliveryExecution));
        } catch (Exception $e) {
            $this->returnFailure($e);
        }
    }
947589
public function finish()
    {

        foreach ($this->drivers as $name => $class) {
            $handler = $class->getHandler();
            if (isset($handler->terminatable) && $handler->terminatable == false) {
                unset($this->drivers[$name]);
                continue;
            }

            if ($class->get('terminate') !== true) {
                $class->finish();
            }
            unset($this->drivers[$name]);
        }
        $this->drivers = [];
    }
808420
public void finish() throws IOException 
    {
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
            logger.logp(Level.FINE, CLASS_NAME,"finish", "finish");
        } 
        // PM18453 start
        WebContainerRequestState requestState = WebContainerRequestState.getInstance(false);
        if (requestState != null && (Boolean.valueOf((String)requestState.getAttribute("InputStreamEarlyReadCompleted"))).booleanValue()) {
            if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  //306998.15
                logger.logp(Level.FINE, CLASS_NAME,"finish", "Skip read because data has already been read and destroyed.");
            } 
            total=limit;
        }
        // PM18453 End
        else if (!SRTServletResponse.isSkipInputStreamRead() &&  length != -1 )        {
            // if content length set then skip remaining bytes in message body
            long remaining = limit - total;   // PK79219
            while ( remaining > 0 )
            {
                long n = skip(remaining);   // PM03146
                if ( n == 0 )
                {
                    // begin 280584.3    6021: Cleanup of  defect 280584.2    WAS.webcontainer
                    //logger.logp(Level.SEVERE, CLASS_NAME,"finish", nls.getString("Invalid.Content.Length"));
                    // end 280584.3    6021: Cleanup of  defect 280584.2    WAS.webcontainer
                    throw new IOException(nls.getString("Invalid.Content.Length","Invalid content length"));
                }
                remaining -= n;
            }
        }
    }
558374
public static void endDoing() {
    long elapsed = System.currentTimeMillis() - startTime;
    System.err.println("done [" + nf.format(((double) elapsed) / 1000) + 
                       " sec].");
  }
1065772
protected void finish() {
        Reporter reporter = this.reporterThreadLocal.get();
        assertEquals("Detailed results found at: " + reporter.getFileName(), "0 errors",
                Integer.toString(reporter.getFails()) + ERRORS_CHECK);
    }
294767
@Override
    @FFDCIgnore(IOException.class)
    public void complete(VirtualConnection vc) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "complete",  vc);
        }
        synchronized( this.in.getCompleteLockObj()){
            
            SRTServletRequestThreadData.getInstance().init(_requestDataAsyncReadCallbackThread);
            
            //Push the original thread's context onto the current thread, also save off the current thread's context
            this.threadContextManager.pushContextData();

            //Call into the user's ReadListener to indicate there is data available
            try{
                if (!in.isFinished()) {
                    this.in.getReadListener().onDataAvailable();
                }   
            } catch (Throwable onDataAvailableException){
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Exception occurred during ReadListener.onDataAvailable : " + onDataAvailableException + ", " + this.in.getReadListener());
                }
                this.threadContextManager.popContextData();
                error(vc, onDataAvailableException);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                    Tr.exit(tc, "complete");
                }
                return;
            }

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                 Tr.debug(tc, "Message is fully read, calling ReadListener onAllDataRead : " + this.in.getReadListener());
            }
            
            if(this.in.getReadListener() != null){
                // if all the data has been read we are done.
                if (in.isFinished()) {
                    try{
                        this.in.getReadListener().onAllDataRead();
                    } catch (Throwable onAllDataReadException){
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Exception occurred during ReadListener.onAllDataRead : " + onAllDataReadException + ", " + this.in.getReadListener());
                        }
                        this.threadContextManager.popContextData();
                        error(vc, onAllDataReadException);
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                            Tr.exit(tc, "complete");
                        }
                        return;
                    }
                } else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "onDataAavailabe returned without reading all data. Read Listener will no be called again : "  + this.in.getReadListener());
                }
                else{
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "ReadListener is not set , stream must be closed, cannot call onAllDataRead()");
                    }
                }
            }
            
            //Revert back to the thread's current context
            this.threadContextManager.popContextData();

        }
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "complete");
        }
    }
706134
public void complete() {
        long seqNo = this.operation.getSequenceNumber();
        Preconditions.checkState(seqNo >= 0, "About to complete a CompletableOperation that has no sequence number.");

        this.done = true;
        if (this.successHandler != null) {
            Callbacks.invokeSafely(this.successHandler, null, cex -> log.error("Success Callback invocation failure.", cex));
        }
    }
883137
private void finishRequest()
    throws IOException
  {
    try {
      cleanup();
    } catch (Exception e) {
      log.log(Level.WARNING, e.toString(), e);
    } finally {
      //_requestFacade = null;
    }
  }
795305
public function terminate()
    {
        //Cleanup and flush output to client
        if (!function_exists('fastcgi_finish_request'))
        {
            if (PHP_SAPI !== 'cli')
            {
                for ($i = 0; $i < ob_get_level(); $i++) {
                    ob_end_flush();
                }

                flush();
            }
        }
        else fastcgi_finish_request();

        //Set the exit status based on the status code.
        $status = 0;
        if(!$this->isSuccess()) {
            $status = (int) $this->getStatusCode();
        }

        exit($status);
    }
1143327
public function update()
    {
        try {
            if ($this->getRequestMethod() !== \Request::HTTP_POST) {
                throw new \common_exception_NotImplemented('Only post method is accepted to updating delivery');
            }

            if (! $this->hasRequestParameter(self::REST_DELIVERY_SEARCH_PARAMS)) {
                throw new \common_exception_MissingParameter(self::REST_DELIVERY_SEARCH_PARAMS, $this->getRequestURI());
            }

            $where = json_decode(html_entity_decode($this->getRequestParameter(self::REST_DELIVERY_SEARCH_PARAMS)), true);
            $propertyValues = $this->getRequestParameters();
            unset($propertyValues[self::REST_DELIVERY_SEARCH_PARAMS]);

            $deliveryModelClass = $this->getDeliveryRootClass();
            $deliveries = $deliveryModelClass->searchInstances($where, ['like' => false, 'recursive' => true]);

            $response = [];

            /** @var \core_kernel_classes_Resource $delivery */
            foreach ($deliveries as $key => $delivery) {
                foreach ($propertyValues as $rdfKey => $rdfValue) {
                    $rdfKey = \tao_helpers_Uri::decode($rdfKey);
                    $property = $this->getProperty($rdfKey);
                    $delivery->editPropertyValues($property, $rdfValue);
                }
                $response[] = ['delivery' => $delivery->getUri()];
            }
            $this->returnSuccess($response);
        }catch (\Exception $e) {
                $this->returnFailure($e);
            }
    }
673760
public function finish()
    {
        if (!empty($this->queue)) {
            // empty queue to avoid duplicates
            $queue = $this->queue;
            $this->queue = array();
            $this->sendChunk($queue);
        }
    }
723421
protected function run()
    {
        $report = common_report_Report::createInfo('Deleting Failing deliveries');

        /** @var ComplexSearchService $search */
        $search = $this->getModel()->getSearchInterface();
        $deliveryAssemblyService = DeliveryAssemblyService::singleton();

        $queryBuilder = $search->query();
        $query = $search->searchType($queryBuilder, $deliveryAssemblyService->getRootClass()->getUri(),true);
        $queryBuilder->setCriteria($query);
        $searchResult = $search->getGateway()->search($queryBuilder);

        $failedDeliveries = [];
        /** @var \core_kernel_classes_Resource $instance */
        foreach ($searchResult as $instance) {
            try {
                $value = DeliveryAssemblyService::singleton()->getRuntime($instance);
                if (is_null($value)) {
                    $failedDeliveries[] = $instance;
                }
            } catch (\common_Exception $e) {
                $failedDeliveries[] = $instance;
            }
        }

        /** @var \core_kernel_classes_Resource $failedDelivery */
        foreach ($failedDeliveries as $failedDelivery) {
            $failedDelivery->delete(true);
            $report->add(common_report_Report::createSuccess('Delivery deleted:'. $failedDelivery->getUri()));
        }

        return $report;
    }