============================================================================= /* Resource Protection Closures
11595
function NotLoggedIn(req, res) {
        req.session.redirectTo = req.originalUrl;
//debug("NotLoggedIn: %s -> %s", req.session.redirectTo, req.originalUrl)
        res.redirect(redirectOptions.failureRedirect);
    }
206754
protected function cleanup()
    {
        if ($this->resource) {
            proc_terminate($this->resource);
        }

        if (is_resource($this->handle)) {
            fclose($this->handle);
        }

        $this->handle   = null;
        $this->resource = null;
    }
940004
function onCollectionRetrievalFailure( serverResponse ) {
			self.logInterface.error( self.logPrefix + "Unable to retrieve the collection from the server.",
				serverResponse );
			self.__entityCacheRaw = null;

			self.scope.$emit( "absyncError", serverResponse );

			if( self.throwFailures ) {
				throw serverResponse;
			}
		}
681922
private void cleanUpDriverResources() {
    ctrlc.setComplete();
    try {
      Runtime.getRuntime().removeShutdownHook(ctrlc);
    }
    catch (IllegalStateException ignore) {
      // If "Shutdown in progress" exception would be thrown, just ignore and don't bother to remove the hook.
    }
    ctrlc = null;

    try {
      setShutdownRequested();
      driverCallbackSocket.close();
      driverCallbackSocket = null;
    }
    catch (Exception e) {
      System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)"));
      e.printStackTrace();
    }

    try {
      if (! job.isComplete()) {
        System.out.println("ERROR: Job not complete after cleanUpDriverResources()");
      }
    }
    catch (Exception e) {
      System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)"));
      e.printStackTrace();
    }

    // At this point, resources are released.
    // The hadoop job has completed (job.isComplete() is true),
    // so the cluster memory and cpus are freed.
    // The driverCallbackSocket has been closed so a new one can be made.

    // The callbackManager itself may or may not have finished, but it doesn't
    // matter since the server socket has been closed.
  }
944648
function _failHandler(e){
        $spin.hide()

        if(e.status === 400) alert(e.responseText || 'Bad request.')
        if(e.status === 401) alert(e.responseText || 'Unauthorized request.')
        if(e.status === 402) alert(e.responseText || 'Forbidden request.')
        if(e.status === 403) alert(e.responseText || 'Forbidden request.')
        if(e.status === 404) alert(e.responseText || 'Images were not found.')
        if(e.status === 405) alert(e.responseText || 'That method is not allowed.')
        if(e.status === 408) alert(e.responseText || 'The request timed out. Try again.')
        if(e.status === 500) alert(e.responseText || 'Something went really wrong.')
        
        postData = postUrl = ''
        
        cb & cb()

      }
442981
public void releaseResource(int resourceId) {
    synchronized (lockObject) {
      ResourceRequest req = requestedResources.get(resourceId);
      removeRequestUnprotected(req);
    }
  }
1307341
public void onResourceReleased(final ResourceReleaseEvent resourceReleaseEvent) {
    String id = resourceReleaseEvent.getIdentifier();
    LOG.log(Level.FINEST, "Got ResourceReleasedEvent for Id: {0} in AzureBatchResourceManager", id);

    ResourceRequestEvent removedEvent = this.containerRequests.remove(id);
    if (removedEvent == null) {
      LOG.log(Level.WARNING,
          "Ignoring attempt to remove non-existent containerRequest for Id: {0} in AzureBatchResourceManager", id);
    } else {
      int currentContainerCount = this.containerCount.decrementAndGet();
      if (currentContainerCount <= 0) {
        this.azureBatchTaskStatusAlarmHandler.disableAlarm();
      }
    }

    this.evaluatorShimManager.onResourceReleased(resourceReleaseEvent);
  }
242108
function purgeResource(resource, archive) {
        if (!resource.purge) { return true; }

        var criteria = resource.purge();
        var deferred = Q.defer();

        archive.bind(resource.name);
        archive[resource.name].remove(criteria, function (err, results) {
            err ? deferred.reject(err) : deferred.resolve(results);
        });
        return deferred.promise;
    }
1220278
@EventHandler(field = "_resourceContext", eventSet = ResourceContext.ResourceEvents.class, eventName = "onRelease")
    public void onRelease() {

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Enter: onRelease()");
        }

        for (PreparedStatement ps : getResources()) {
            try {
                ps.close();
            } catch (SQLException sqe) {
            }
        }
        getResources().clear();

        if (_connection != null) {
            try {
                _connection.close();
            } catch (SQLException e) {
                throw new ControlException("SQL Exception while attempting to close database connection.", e);
            }
        }

        _connection = null;
        _connectionDataSource = null;
        _connectionDriver = null;
    }
468673
public function handleClose()
    {
        if ($this->autoClose === true && is_resource($this->resource))
        {
            fclose($this->resource);
        }
    }
390267
void onResourceReleaseRequest(final ResourceReleaseEvent releaseRequest) {
    synchronized (this.theContainers) {
      LOG.log(Level.FINEST, "Release container: {0}", releaseRequest.getIdentifier());
      this.theContainers.release(releaseRequest.getIdentifier());
      this.checkRequestQueue();
    }
  }
113031
public void close(ScopeWrapper<S> scope)
      throws IOException {
    List<Throwable> exceptionsList = Lists.newArrayList();
    List<Service> awaitShutdown = Lists.newArrayList();

    for (Map.Entry<RawJobBrokerKey, Object> entry : Maps.filterKeys(this.sharedResourceCache.asMap(),
        new ScopeIsAncestorFilter(scope)).entrySet()) {

      this.sharedResourceCache.invalidate(entry.getKey());

      if (entry.getValue() instanceof ResourceInstance) {
        Object obj = ((ResourceInstance) entry.getValue()).getResource();
        // Catch unchecked exception while closing resources, make sure all resources managed by cache are closed.
        try {
          SharedResourcesBrokerUtils.shutdownObject(obj, log);
        } catch (Throwable t) {
          exceptionsList.add(t);
        }
        if (obj instanceof Service) {
          awaitShutdown.add((Service) obj);
        }
      }
    }

    for (Service service : awaitShutdown) {
      try {
        service.awaitTerminated(10, TimeUnit.SECONDS);
      } catch (TimeoutException te) {
        log.error("Failed to shutdown {}.", service);
      }
    }

    // log exceptions while closing resources up.
    if (exceptionsList.size() > 0) {
      log.error(exceptionsList.stream()
          .map(Throwables::getStackTraceAsString).collect(Collectors.joining("\n")));
    }
  }
1149356
int claimResource(ZooKeeper zookeeper, String poolNode, int poolSize)
            throws KeeperException, InterruptedException {

        logger.debug("Trying to claim a resource.");
        List<String> claimedResources = zookeeper.getChildren(poolNode, false);
        if (claimedResources.size() >= poolSize) {
            logger.debug("No resources available at the moment (pool size: {}), waiting.", poolSize);
            // No resources available. Wait for a resource to become available.
            final CountDownLatch latch = new CountDownLatch(1);
            zookeeper.getChildren(poolNode, event -> latch.countDown());
            latch.await();
            return claimResource(zookeeper, poolNode, poolSize);
        }

        // Try to claim an available resource.
        for (int i = 0; i < poolSize; i++) {
            String resourcePath = Integer.toString(i);
            if (!claimedResources.contains(resourcePath)) {
                String node;
                try {
                    logger.debug("Trying to claim seemingly available resource {}.", resourcePath);
                    node = zookeeper.create(
                            poolNode + "/" + resourcePath,
                            new byte[0],
                            ZooDefs.Ids.OPEN_ACL_UNSAFE,
                            CreateMode.EPHEMERAL
                    );
                } catch (KeeperException e) {
                    if (e.code() == KeeperException.Code.NODEEXISTS) {
                        // Failed to claim this resource for some reason.
                        continue;
                    } else {
                        // Unexpected failure.
                        throw e;
                    }
                }

                zookeeper.exists(node, event -> {
                    if (event.getType() == EventType.NodeDeleted) {
                        // Invalidate our claim when the node is deleted by some other process.
                        logger.debug("Resource-claim node unexpectedly deleted ({})", resource);
                        close(true);
                    }
                });

                logger.debug("Successfully claimed resource {}.", resourcePath);
                return i;
            }
        }

        return claimResource(zookeeper, poolNode, poolSize);
    }
608675
function handleResource( $tpl, &$resourceData, $method, &$extraParameters )
    {
        return $this->handleResourceData( $tpl, $this, $resourceData, $method, $extraParameters );
    }
234258
public static function shutdownHandler()
    {
        if ($err = error_get_last()) {
            switch ($err['type']) {
                case E_ERROR:
                case E_PARSE:
                case E_COMPILE_ERROR:
                case E_CORE_ERROR:
                    $service = self::$psrLogger
                        ->getMetadataProvider()
                        ->serviceId();
                    $version = self::$psrLogger
                        ->getMetadataProvider()
                        ->versionId();
                    $message = sprintf(
                        '%s: %s in %s on line %d',
                        self::getErrorPrefix($err['type']),
                        $err['message'],
                        $err['file'],
                        $err['line']
                    );
                    $context = [
                        'context' => [
                            'reportLocation' => [
                                'filePath' => $err['file'],
                                'lineNumber' => $err['line'],
                                'functionName' =>
                                    self::getFunctionNameForReport(),
                            ]
                        ],
                        'serviceContext' => [
                            'service' => $service,
                            'version' => $version
                        ]
                    ];
                    if (self::$psrLogger) {
                        self::$psrLogger->log(
                            self::getErrorLevelString($err['type']),
                            $message,
                            $context
                        );
                    }
                    break;
            }
        }
    }
310141
def http_error_handler(f):
    

    def hrefs_to_resources(hrefs):
        for href in hrefs.replace(',', '').split():
            type, uuid = href.split('/')[-2:]
            yield Resource(type, uuid=uuid)

    def hrefs_list_to_resources(hrefs_list):
        for href in eval(hrefs_list):
            type, uuid = href.split('/')[-2:]
            yield Resource(type, uuid=uuid)

    @wraps(f)
    def wrapper(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except HttpError as e:
            if e.http_status == 404:
                # remove previously created resource
                # from the cache
                self.emit('deleted', self)
                if isinstance(self, Resource):
                    raise ResourceNotFound(resource=self)
                elif isinstance(self, Collection):
                    raise CollectionNotFound(collection=self)
            elif e.http_status == 409:
                # contrail 3.2
                matches = re.match(r'^Delete when children still present: (\[[^]]*\])', e.message)
                if matches:
                    raise ChildrenExists(
                        resources=list(hrefs_list_to_resources(matches.group(1))))
                matches = re.match(r'^Delete when resource still referred: (\[[^]]*\])', e.message)
                if matches:
                    raise BackRefsExists(
                        resources=list(hrefs_list_to_resources(matches.group(1))))
                # contrail 2.21
                matches = re.match(r'^Children (.*) still exist$', e.message)
                if matches:
                    raise ChildrenExists(
                        resources=list(hrefs_to_resources(matches.group(1))))
                matches = re.match(r'^Back-References from (.*) still exist$', e.message)
                if matches:
                    raise BackRefsExists(
                        resources=list(hrefs_to_resources(matches.group(1))))
            raise
    return wrapper
707028
function exitIfEACCES(err) {
  if (err && err.syscall === 'bind' && err.code === 'EACCES') {
    this.logError("Unable to bind to port, exiting! Hopefully we will be restarted with privileges to bind the port.");
    process.exit(1);
  }
}