Java 2 security APIs for deleteOnExit
3941
public static void delete(final File f) {
        if (f != null && f.exists()) {
            // Why do we have to specify a return type for the run method and paramatize
            // PrivilegedExceptionAction to it, this method should have a void return type ideally.
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    if (!f.delete()) {
                        logger.log(Level.INFO, Messages.INSTALL_KERNEL_MESSAGES.getLogMessage("LOG_CANNOT_DELETE_FILE",
                                                                                              f.getAbsolutePath()));
                        f.deleteOnExit();
                    }

                    return null;
                }
            });
        }
    }
367105
public void deleteCache(DeleteCacheAopProxyChain jp, CacheDelete cacheDelete, Object retVal) throws Throwable {
        Object[] arguments = jp.getArgs();
        CacheDeleteKey[] keys = cacheDelete.value();
        if (null == keys || keys.length == 0) {
            return;
        }
        Object target = jp.getTarget();
        String methodName = jp.getMethod().getName();
        try {
            boolean isOnTransactional = CacheHelper.isOnTransactional();
            Set<CacheKeyTO> keySet = null;
            if (!isOnTransactional) {
                keySet = new HashSet<>(keys.length);
            }
            for (int i = 0; i < keys.length; i++) {
                CacheDeleteKey keyConfig = keys[i];
                String[] tempKeys = keyConfig.value();
                String tempHfield = keyConfig.hfield();
                if (!scriptParser.isCanDelete(keyConfig, arguments, retVal)) {
                    continue;
                }
                for (String tempKey : tempKeys) {
                    CacheKeyTO key = getCacheKey(target, methodName, arguments, tempKey, tempHfield, retVal, true);
                    if (null == key) {
                        continue;
                    }
                    if (isOnTransactional) {
                        CacheHelper.addDeleteCacheKey(key);
                    } else {
                        keySet.add(key);
                    }
                    this.getAutoLoadHandler().resetAutoLoadLastLoadTime(key);
                }
            }
            this.delete(keySet);
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            throw e;
        }
    }
106705
private <TResponse> void callDeleteApi(
            BasicCredentials credentials, String path,
            Map<String, String> queryParams) throws AuthleteApiException
    {
        callApi(HttpMethod.DELETE, credentials, path, queryParams, (Object)null, (Class<TResponse>)null);
    }
1259121
def deleteAllActivationKeys(server):
    '''
    
    '''

    try:
        client, key = _get_session(server)
    except Exception as exc:
        err_msg = 'Exception raised when connecting to spacewalk server ({0}): {1}'.format(server, exc)
        log.error(err_msg)
        return {'Error': err_msg}

    activation_keys = client.activationkey.listActivationKeys(key)

    deleted_keys = []
    failed_keys = []

    for aKey in activation_keys:
        if client.activationkey.delete(key, aKey['key']) == 1:
            deleted_keys.append(aKey['key'])
        else:
            failed_keys.append(aKey['key'])

    ret = {'deleted': deleted_keys}
    if failed_keys:
        ret['failed'] = failed_keys
    return ret
543464
public static snmp_trap delete(nitro_service client, snmp_trap resource) throws Exception
	{
		resource.validate("delete");
		return ((snmp_trap[]) resource.delete_resource(client))[0];
	}
1301633
def _api_delete(path, data, server=None):
    '''
    
    '''
    server = _get_server(server)
    response = requests.delete(
            url=_get_url(server['ssl'], server['url'], server['port'], path),
            auth=_get_auth(server['user'], server['password']),
            headers=_get_headers(),
            params=data,
            verify=False
    )
    return _api_response(response)
23677
def endpoint_delete(auth=None, **kwargs):
    '''
    
    '''
    cloud = get_operator_cloud(auth)
    kwargs = _clean_kwargs(**kwargs)
    return cloud.delete_endpoint(**kwargs)
1044698
function getStuffAndDeleteSecret(opts, someArgument) {
  // We depend on "stuffs" repository.
  const stuffs = opts.stuffs

  // We may now carry on.
  return stuffs.getStuff(someArgument).then(stuff => {
    // Modify return value. Just to prove this is testable.
    delete stuff.secret
    return stuff
  })
}
1189442
def cli(env, securitygroup_id):
    """"""
    mgr = SoftLayer.NetworkManager(env.client)
    if not mgr.delete_securitygroup(securitygroup_id):
        raise exceptions.CLIAbort("Failed to delete security group")
979200
private Response delete(ChaincodeStub stub, List<String> args) {
		if (args.size() != 1) {
			return newErrorResponse("Incorrect number of arguments. Expecting 1");
		}
		String key = args.get(0);
		// Delete the key from the state in ledger
		stub.delState(key);
		return newSuccessResponse();
	}
151457
function performRemove() {
        UserService.remove(vm.user)
          .then(deleteUserSuccess)
          .catch(deleteUserCatch);

        function deleteUserSuccess() {
          Toast.show({type: 'success', text: 'User ' + vm.displayName + ' deleted'});
          vm.showList();
        }

        function deleteUserCatch(err) {
          Toast.show({
            type: 'warn',
            text: 'Error while deleting user ' + vm.displayName,
            link: {state: $state.$current, params: $stateParams}
          });

          if (form && err) {
            form.setResponseErrors(err, vm.errors);
          }
        }
      }
997530
public static base_responses delete(nitro_service client, String Dnssuffix[]) throws Exception {
		base_responses result = null;
		if (Dnssuffix != null && Dnssuffix.length > 0) {
			dnssuffix deleteresources[] = new dnssuffix[Dnssuffix.length];
			for (int i=0;i<Dnssuffix.length;i++){
				deleteresources[i] = new dnssuffix();
				deleteresources[i].Dnssuffix = Dnssuffix[i];
			}
			result = delete_bulk_request(client, deleteresources);
		}
		return result;
	}
157400
@Override
	public DeleteMethodOutcome deleteByUrl(String theUrl, List<DeleteConflict> deleteConflicts, RequestDetails theRequest) {
		StopWatch w = new StopWatch();

		Set<Long> resourceIds = myMatchResourceUrlService.processMatchUrl(theUrl, myResourceType);
		if (resourceIds.size() > 1) {
			if (myDaoConfig.isAllowMultipleDelete() == false) {
				throw new PreconditionFailedException(getContext().getLocalizer().getMessage(BaseHapiFhirDao.class, "transactionOperationWithMultipleMatchFailure", "DELETE", theUrl, resourceIds.size()));
			}
		}

		List<ResourceTable> deletedResources = new ArrayList<>();
		for (Long pid : resourceIds) {
			ResourceTable entity = myEntityManager.find(ResourceTable.class, pid);
			deletedResources.add(entity);

			T resourceToDelete = toResource(myResourceType, entity, null, false);

			// Notify IServerOperationInterceptors about pre-action call
			HookParams hooks = new HookParams()
				.add(IBaseResource.class, resourceToDelete)
				.add(RequestDetails.class, theRequest)
				.addIfMatchesType(ServletRequestDetails.class, theRequest);
			myInterceptorBroadcaster.callHooks(Pointcut.STORAGE_PRESTORAGE_RESOURCE_DELETED, hooks);

			validateOkToDelete(deleteConflicts, entity, false);

			// Notify interceptors
			IdDt idToDelete = entity.getIdDt();
			if (theRequest != null) {
				ActionRequestDetails requestDetails = new ActionRequestDetails(theRequest, idToDelete.getResourceType(), idToDelete);
				notifyInterceptors(RestOperationTypeEnum.DELETE, requestDetails);
			}

			// Perform delete

			updateEntityForDelete(theRequest, entity);
			resourceToDelete.setId(entity.getIdDt());

			// Notify JPA interceptors
			TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
				@Override
				public void beforeCommit(boolean readOnly) {
					HookParams hookParams = new HookParams()
						.add(IBaseResource.class, resourceToDelete)
						.add(RequestDetails.class, theRequest)
						.addIfMatchesType(ServletRequestDetails.class, theRequest);
					myInterceptorBroadcaster.callHooks(Pointcut.STORAGE_PRECOMMIT_RESOURCE_DELETED, hookParams);
				}
			});
		}

		IBaseOperationOutcome oo;
		if (deletedResources.isEmpty()) {
			oo = OperationOutcomeUtil.newInstance(getContext());
			String message = getContext().getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "unableToDeleteNotFound", theUrl);
			String severity = "warning";
			String code = "not-found";
			OperationOutcomeUtil.addIssue(getContext(), oo, severity, message, null, code);
		} else {
			oo = OperationOutcomeUtil.newInstance(getContext());
			String message = getContext().getLocalizer().getMessage(BaseHapiFhirResourceDao.class, "successfulDeletes", deletedResources.size(), w.getMillis());
			String severity = "information";
			String code = "informational";
			OperationOutcomeUtil.addIssue(getContext(), oo, severity, message, null, code);
		}

		ourLog.debug("Processed delete on {} (matched {} resource(s)) in {}ms", theUrl, deletedResources.size(), w.getMillis());

		DeleteMethodOutcome retVal = new DeleteMethodOutcome();
		retVal.setDeletedEntities(deletedResources);
		retVal.setOperationOutcome(oo);
		return retVal;
	}
361695
def oauth_client_delete(self, id, **kwargs):
        ""
        api_path = "/api/v2/oauth/clients/{id}.json"
        api_path = api_path.format(id=id)
        return self.call(api_path, method="DELETE", **kwargs)
362025
protected void cleanupOnExit() {
        String threadName = "Shutdown Hook Deletion Thread for Temporary DB " + dataDir.toString();
        final DB db = this;
        Runtime.getRuntime().addShutdownHook(new Thread(threadName) {

            @Override
            public void run() {
                // ManagedProcess DestroyOnShutdown ProcessDestroyer does
                // something similar, but it shouldn't hurt to better be save
                // than sorry and do it again ourselves here as well.
                try {
                    // Shut up and don't log if it was already stop() before
                    if (mysqldProcess != null && mysqldProcess.isAlive()) {
                        logger.info("cleanupOnExit() ShutdownHook now stopping database");
                        db.stop();
                    }
                } catch (ManagedProcessException e) {
                    logger.warn("cleanupOnExit() ShutdownHook: An error occurred while stopping the database", e);
                }

                if (dataDir.exists() && (configuration.isDeletingTemporaryBaseAndDataDirsOnShutdown() && Util.isTemporaryDirectory(dataDir.getAbsolutePath()))) {
                    logger.info("cleanupOnExit() ShutdownHook quietly deleting temporary DB data directory: " + dataDir);
                    FileUtils.deleteQuietly(dataDir);
                }
                if (baseDir.exists() && (configuration.isDeletingTemporaryBaseAndDataDirsOnShutdown() && Util.isTemporaryDirectory(dataDir.getAbsolutePath()))) {
                    logger.info("cleanupOnExit() ShutdownHook quietly deleting temporary DB base directory: " + baseDir);
                    FileUtils.deleteQuietly(baseDir);
                }
            }
        });
    }
128052
function deleteSelf(callback) {
  var _this = this;

  _flowsync2["default"].series([function (done) {
    _this.beforeDelete(done);
  }, function (done) {
    if (_this.constructor.useSoftDelete !== undefined) {
      _this.softDestroy(done);
    } else {
      _this.destroy(done);
    }
  }, function (done) {
    _this.afterDelete(done);
  }], function (errors) {
    callback(errors);
  });
}
90286
public static ssl_key delete(nitro_service client, ssl_key resource) throws Exception
	{
		resource.validate("delete");
		return ((ssl_key[]) resource.delete_resource(client))[0];
	}