Clean up native win32 resources after completion or failure of SSPI authentication. This
SSPIClient instance becomes unusable after disposal.
979949
@Override
  public void dispose() {
    if (sspiContext != null) {
      sspiContext.dispose();
      sspiContext = null;
    }
    if (clientCredentials != null) {
      clientCredentials.dispose();
      clientCredentials = null;
    }
  }
14010
private void cleanup() {
        final String methodName = "cleanup(): ";
        try {
            final Bundle b = bundle.getAndSet(null);
            if (b != null) {
                if (tc.isDebugEnabled()) {
                    Tr.debug(tc, methodName + "Uninstalling bundle location: " + b.getLocation() + ", bundle id: " + b.getBundleId());
                }
                SecurityManager sm = System.getSecurityManager();
                if (sm != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Void>() {
                        @Override
                        public Void run() {
                            try {
                                b.uninstall();
                                return null;
                            } catch (BundleException ignored) {
                                return null;
                            }
                        }
                    });
                } else {
                    b.uninstall();
                }
            }
        } catch (BundleException ignored) {
        } catch (IllegalStateException ignored) {

        }
    }
729519
private void tearDownShiro()
  {
    try
    {
      SecurityManager securityManager = SecurityUtils.getSecurityManager();

      LifecycleUtils.destroy(securityManager);
      ThreadContext.unbindSecurityManager();
      ThreadContext.unbindSubject();
      ThreadContext.remove();
    }
    catch (UnavailableSecurityManagerException e)
    {

      // we don't care about this when cleaning up the test environment
      // (for example, maybe the subclass is a unit test and it didn't
      // need a SecurityManager instance because it was using only mock Subject instances)
    }

    SecurityUtils.setSecurityManager(null);
  }
326726
def stop(self):
        """"""
        stopped = []
        for interface_id, proxy in self.proxies.items():
            if interface_id in self.failed_inits:
                LOG.warning("ServerThread.stop: Not performing de-init for %s" % interface_id)
                continue
            if proxy._callbackip and proxy._callbackport:
                callbackip = proxy._callbackip
                callbackport = proxy._callbackport
            else:
                callbackip = proxy._localip
                callbackport = self._localport
            remote = "http://%s:%i" % (callbackip, callbackport)
            LOG.debug("ServerThread.stop: init('%s')" % remote)
            if not callbackip in stopped:
                try:
                    proxy.init(remote)
                    stopped.append(callbackip)
                    LOG.info("Proxy de-initialized: %s" % remote)
                except Exception as err:
                    LOG.debug("proxyInit: Exception: %s" % str(err))
                    LOG.warning("Failed to de-initialize proxy")
        self.proxies.clear()
        LOG.info("Shutting down server")
        self.server.shutdown()
        LOG.debug("ServerThread.stop: Stopping ServerThread")
        self.server.server_close()
        LOG.info("Server stopped")
1201840
def close(self):
        
        if self.ipmi_session:
            self.ipmi_session.unregister_keepalive(self.keepaliveid)
        if self.activated:
            try:
                self.ipmi_session.raw_command(netfn=6, command=0x49,
                                              data=(1, 1, 0, 0, 0, 0))
            except exc.IpmiException:
                # if underlying ipmi session is not working, then
                # run with the implicit success
                pass
948323
def cleanup_state
      # intentionally not deleting entire temp dir to preserve localized
      # executable directories between tests on Windows. see how we reference
      # RS_RIGHT_RUN_EXE below.
      delete_if_exists(state_file_path)
      delete_if_exists(chef_file_path)
      delete_if_exists(past_scripts_path)
      delete_if_exists(log_path)
      delete_if_exists(cook_state_file_path)
    end
252655
def _cleanup(self):
        """"""
        self._expkg = None
        self._extmp = None
        self._flag_e = True
        self._ifile.close()
395579
public void tlsCleanup() throws ResourceException {

        final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled();

        if (isTracingEnabled && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "tlsCleanup");
        }

        this.initialRequestStackTrace = null;
        this.clearHandleList();

        // ease state checks for error cleanup code.    if ((state != STATE_ACTIVE_INUSE) && (state != STATE_ACTIVE_FREE)) {
        if ((state == STATE_NEW) || (state == STATE_INACTIVE)) {
            IllegalStateException e = new IllegalStateException("cleanup: illegal state exception. State = " + getStateString() + " MCW = " + mcWrapperObject_hexString);
            Object[] parms = new Object[] { "cleanup", e };
            Tr.error(tc, "ILLEGAL_STATE_EXCEPTION_J2CA0079", parms);
            throw e;
        }

        try {
            /*
             * DissociateConnection needs to be called before cleanup.
             *
             * Under the original implementation for smart handles, no
             * dissociateConnection was needed because it was cleaned up
             * during the cleanup call on the mc. Now with the new implementation
             * cleanup will not do the dissociateConnection. If a resource
             * adapter is a instanceof DissociatableManagedConnection, we
             * need to call the dissociateConnection
             *
             * Lazy Connection Association Optimization is the new name
             * for smart handles.
             */
            if (isTracingEnabled && tc.isDebugEnabled())
                Tr.debug(this, tc,
                         "InstanceOf DissociatableManagedConnection is " + gConfigProps.isInstanceOfDissociatableManagedConnection() + " In ConnectionManager " + this.toString());

            if (gConfigProps.isInstanceOfDissociatableManagedConnection()) {
                if (isTracingEnabled && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Calling mc.dissociateConnections()");
                ((DissociatableManagedConnection) mc).dissociateConnections();
                if (isTracingEnabled && tc.isDebugEnabled())
                    Tr.debug(this, tc, "Returned from mc.dissociateConnections()");
            }
            if (mc != null && !aborted) {
                mc.cleanup();
            } else if (tc.isDebugEnabled()) {
                Tr.debug(this, tc, "mc is null, or mc is aborted, mc.cleanup() not called.", (mc == null));
            }
        } catch (ResourceException e) {

            String localMessage = e.getLocalizedMessage();
            if ((localMessage != null) && localMessage.equals("Skip logging for this failing connection")) {
                /*
                 * If the resource adapter throws a resource exception with the skip logging text,
                 * log this path only when debug is enabled.
                 *
                 * The resource apdater does not want normal logging of this failed managed connection.
                 */
                if (tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "Connection failed, resource adapter requested skipping failure logging");
                }
                throw e;
            } else {
                com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ejs.j2c.MCWrapper.cleanup", "706", this);
                /*
                 * We are here means there is an error occured during MC cleanup.
                 * Lets not log a error message, when we clearly know we are attempting to
                 * cleanup a bad connection. At this stage the error message could be misleading.
                 */
                if (!stale && !do_not_reuse_mcw) {
                    Object[] parms = new Object[] { "cleanup", "cleanup", mc, e, gConfigProps.cfName };
                    Tr.error(tc, "MCERROR_J2CA0081", parms);
                } else {
                    if (isTracingEnabled && tc.isDebugEnabled())
                        Tr.debug(this, tc, "got a SCE when doing cleanup on the mc, { mc, e, pmiName}; is:", new Object[] { mc, e, gConfigProps.cfName });
                }
                throw e;
            }

        } catch (Exception e) {

            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ejs.j2c.MCWrapper.cleanup", "712", this);
            ResourceException re = null;
            if (!stale && !do_not_reuse_mcw) {
                Object[] parms = new Object[] { "cleanup", "cleanup", mc, e, gConfigProps.cfName };
                Tr.error(tc, "MCERROR_J2CA0081", parms);
            } else {
                if (isTracingEnabled && tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "got a SCE when doing cleanup on the mc, { mc, e, pmiName}; is:", new Object[] { mc, e, gConfigProps.cfName });
                }
            }
            re = new ResourceException("cleanup: Exception caught");
            re.initCause(e);
            throw re;

        } finally {
            if (mcConnectionCount != 0) {
                for (int i = mcConnectionCount; i > 0; i--) { //couldn't this just be while(mcConnectionCount > 0)
                    decrementHandleCount();
                }
            }

            // reset to STATE_ACTIVE state.
            //  remove  if(pm.unusedTimeoutEnabled){ //we only need to set the
            // unusedTimeStamp if unused timeout
            // is enabled.
            // we must unconditionally reset unusedTimeStamp here.

            unusedTimeStamp = java.lang.System.currentTimeMillis();
            switch (tranWrapperInUse) {
                /*
                 * Cleanup on the tran wrapper. This is not cleanup for
                 * the mc.
                 */
                case XATXWRAPPER:
                    xaTranWrapper.cleanup();
                    break;

                case LOCALTXWRAPPER:
                    localTranWrapper.cleanup();
                    break;

                case NOTXWRAPPER:
                    noTranWrapper.cleanup();
                    break;

                case RRSGLOBALTXWRAPPER:
                    rrsGlobalTranWrapper.cleanup();
                    break;

                case RRSLOCALTXWRAPPER:
                    rrsLocalTranWrapper.cleanup();
                    break;

                default:
                    break;

            }

            mcConnectionCount = 0;
            cm = null;

            boolean isAlreadyFreeActive = false;
            if (state == STATE_ACTIVE_FREE) {
                isAlreadyFreeActive = true;
            }

            state = STATE_ACTIVE_FREE;
            tranWrapperInUse = NONE;
            uowCoord = null;
            holdTimeStart = 0;
            holdStartTimeSet = false;
            // threadId = null; //  keep the thead info for tls connections
            // threadName = null; //  keep the thread name info for tls connections
            totalUseTime = 0;
            currentUseStartTime = 0;
            useStartTimeSet = false;
            totalHoldTime = 0;
            if (!isAlreadyFreeActive) {
                isNotAlreadyFreeActive();
            }
        }

        if (isTracingEnabled && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "tlsCleanup");
        }

    }
762945
def _cleanup(self, kill, verbose):
        
        if kill:
            removed_indices = self.g.prune()

            self.nout -= len(removed_indices)

            if verbose and removed_indices:
                print('Removing %s' % removed_indices)

            for j in removed_indices:
                self.inv_map.pop(j[0])
933014
def cleanup_interfaces(self):
        
        debug("Cleaning up interfaces...")
        for gpio_id in self._gpio_kernel_interfaces_created:
            # Close the value-file and remove interrupt bindings
            self.del_interrupt_callback(gpio_id)

            # Remove the kernel GPIO interface
            debug("- unexporting GPIO %s" % gpio_id)
            with open(_SYS_GPIO_ROOT + "unexport", "w") as f:
                f.write("%s" % gpio_id)

        # Reset list of created interfaces
        self._gpio_kernel_interfaces_created = []
1150998
def _clean_up(self):
        ''''''
        self.logger.info('Beginning Clean Up Process')
        try:
            if self.origin_path:
                self.logger.info('Removing Origin Directory - %s', self.origin_path)
                shutil.rmtree(self.origin_path)
            self.logger.info('Removing Working Directory - %s', self.dir_path)
            shutil.rmtree(self.dir_path)
            self.logger.info('Clean Up Process Complete')
        except Exception as e:    #pragma: no cover
            self.logger.exception(e)
1190174
private void onUncleanExit(final String processId, final int exitCode) {
    this.onResourceStatus(
        ResourceStatusEventImpl.newBuilder()
            .setIdentifier(processId)
            .setState(State.FAILED)
            .setExitCode(exitCode)
            .build()
    );
  }
1357250
static void cleanup() {
        String tempFolder = getTempDir().getAbsolutePath();
        File dir = new File(tempFolder);

        File[] nativeLibFiles = dir.listFiles(new FilenameFilter() {
            private final String searchPattern = "secp256k1-";
            public boolean accept(File dir, String name) {
                return name.startsWith(searchPattern) && !name.endsWith(".lck");
            }
        });
        if(nativeLibFiles != null) {
            for(File nativeLibFile : nativeLibFiles) {
                File lckFile = new File(nativeLibFile.getAbsolutePath() + ".lck");
                if(!lckFile.exists()) {
                    try {
                        nativeLibFile.delete();
                    }
                    catch(SecurityException e) {
                        System.err.println("Failed to delete old native lib" + e.getMessage());
                    }
                }
            }
        }
    }
650017
def cleanup(test_data, udfs, tmp_data, tmp_db):
    """"""
    con = make_ibis_client(ENV)

    if udfs:
        # this comes before test_data bc the latter clobbers this too
        con.hdfs.rmdir(os.path.join(ENV.test_data_dir, 'udf'))

    if test_data:
        con.drop_database(ENV.test_data_db, force=True)
        con.hdfs.rmdir(ENV.test_data_dir)

    if tmp_data:
        con.hdfs.rmdir(ENV.tmp_dir)

    if tmp_db:
        con.drop_database(ENV.tmp_db, force=True)
977247
private void cleanupSession(){
        eventThread.queueClientEvent(new ClientSessionEvent(SessionEvent.CLOSED));
        watcherManager.cleanup();
        session.id = "";
        session.password = null;
        session.serverId = -1;
        onSessionClose();
    }
277435
def terminate():
    

    for callback_repository in _callback_repositories:
        for window_addr in list(callback_repository.keys()):
            del callback_repository[window_addr]
    for window_addr in list(_window_user_data_repository.keys()):
        del _window_user_data_repository[window_addr]
    _glfw.glfwTerminate()
439192
def cleanup
      # Provisioning should have set the host 'instance' values.
      kill_instances(@hosts.map{ |h| h['instance'] }.select{ |x| !x.nil? })
      delete_key_pair_all_regions()
      nil
    end