use the resource manager
355069
public static void useResource(String host, int port, String user, String password, Authentication authType)
    throws ResourceNotFoundException, ForbiddenUserException, FailedRequestException
  {
    // create the client
    DatabaseClient client = DatabaseClientFactory.newClient(host, port, user, password, authType);

    setUpExample(client);

    // create the batch manager
    BatchManager batchMgr = new BatchManager(client);

    // collect the request items
    BatchManager.BatchRequest request = batchMgr.newBatchRequest();
    request.withRead("/batch/read1.xml", "application/xml");
    request.withRead("/batch/read2.xml", Metadata.COLLECTIONS, "application/xml");
    request.withDelete("/batch/delete1.xml");
    request.withWrite("/batch/write1.xml",
      new StringHandle().withFormat(Format.XML).with("<write1/>"));
    DocumentMetadataHandle meta2 = new DocumentMetadataHandle();
    meta2.getCollections().add("/batch/collection2");
    request.withWrite("/batch/write2.xml",
      meta2,
      new StringHandle().withFormat(Format.XML).with("<write2/>"));

    // apply the request
    BatchManager.BatchResponse response = batchMgr.apply(request);

    System.out.println("Applied the batch request with " +
      (response.getSuccess() ? "success" : "failure")+":");

    // iterate over the response items
    while (response.hasNext()){
      BatchManager.OutputItem item = response.next();
      BatchManager.OperationType itemType = item.getOperationType();
      String itemUri = item.getUri();
      if (item.getSuccess()) {
        System.out.println(itemType.name().toLowerCase()+" on "+itemUri);

        // inspect the response for a document read request
        if (itemType == BatchManager.OperationType.READ) {
          BatchManager.ReadOutput readItem = (BatchManager.ReadOutput) item;

          // show the document metadata read from the database
          if (readItem.hasMetadata()) {
            StringHandle metadataHandle = readItem.getMetadata(new StringHandle());
            System.out.println("with metadata:\n"+metadataHandle.get());
          }
          // show the document content read from the database
          if (readItem.hasContent()) {
            StringHandle contentHandle = readItem.getContent(new StringHandle());
            System.out.println("with content:\n"+contentHandle.get());
          }
        }
      } else {
        System.out.println(itemType.name().toLowerCase()+" failed on "+itemUri);
        if (item.hasException()) {
          StringHandle exceptionHandle = item.getException(new StringHandle());
          System.out.println("with exception:\n"+exceptionHandle.get());
        }
      }
    }

    // release the client
    client.release();
  }
413128
def get_resources(self):
        
        json_resources = self.rest_client.make_request(self.resource_url)['resources']
        return [RestResource(resource, self.rest_client) for resource in json_resources]
74321
def help(self):
        

        print('Resources:')
        print('')
        for name in sorted(self._resources.keys()):
            methods = sorted(self._resources[name]._methods.keys())
            print('{}: {}'.format(bold(name), ', '.join(methods)))
185031
def _call_resource_method(self, cls, id, method_name, data):
        """"""

        if cls.api_root != "a":
            url_path = "/{name}/{id}/{method}".format(
                name=cls.collection_name, id=id, method=method_name
            )
        else:
            # Management method.
            url_path = "/a/{app_id}/{name}/{id}/{method}".format(
                app_id=self.app_id, name=cls.collection_name, id=id, method=method_name
            )

        url = URLObject(self.api_server).with_path(url_path)
        converted_data = convert_datetimes_to_timestamps(data, cls.datetime_attrs)

        session = self._get_http_session(cls.api_root)
        response = session.post(url, json=converted_data)

        result = _validate(response).json()
        return cls.create(self, **result)
581255
def _harvest_lost_resources(self):
        """"""
        with self._lock:
            for i in self._unavailable_range():
                rtracker = self._reference_queue[i]
                if rtracker is not None and rtracker.available():
                    self.put_resource(rtracker.resource)
64730
def RegisterResources(self, client_resources):
    """"""
    self.user_cpu_stats.RegisterValue(client_resources.cpu_usage.user_cpu_time)
    self.system_cpu_stats.RegisterValue(
        client_resources.cpu_usage.system_cpu_time)
    self.network_bytes_sent_stats.RegisterValue(
        client_resources.network_bytes_sent)

    self.worst_performers.Append(client_resources)
    new_worst_performers = sorted(
        self.worst_performers,
        key=lambda s: s.cpu_usage.user_cpu_time + s.cpu_usage.system_cpu_time,
        reverse=True)[:self.NUM_WORST_PERFORMERS]
    self.worst_performers = new_worst_performers
544747
def get_resources(cls):
        """"""
        my_plurals = resource_helper.build_plural_mappings(
            {}, RESOURCE_ATTRIBUTE_MAP)
        attributes.PLURALS.update(my_plurals)
        attr_map = RESOURCE_ATTRIBUTE_MAP
        resources = resource_helper.build_resource_info(my_plurals,
                                                        attr_map,
                                                        constants.A10_DEVICE_INSTANCE)

        return resources
702477
def load_resources(bucket, prefix, region, account_config, accounts,
                   assume, start, end, resources, store, db, verbose, debug):
    """"""
    logging.basicConfig(level=(verbose and logging.DEBUG or logging.INFO))
    logging.getLogger('botocore').setLevel(logging.WARNING)
    logging.getLogger('s3transfer').setLevel(logging.WARNING)
    start = date_parse(start)
    end = date_parse(end)

    if not resources:
        resources = ['NetworkInterface', 'Instance', 'LoadBalancer']

    account_map = {}
    data = yaml.safe_load(account_config.read())
    for a in data.get('accounts', ()):
        if accounts and (a['name'] in accounts or a['account_id'] in accounts):
            account_map[a['account_id']] = a
        elif not accounts:
            account_map[a['account_id']] = a
    account_ids = list(account_map)

    executor = ProcessPoolExecutor
    if debug:
        from c7n.executor import MainThreadExecutor
        MainThreadExecutor.c7n_async = False
        executor = MainThreadExecutor

    stats = Counter()
    t = time.time()
    with executor(max_workers=multiprocessing.cpu_count()) as w:
        futures = {}
        for a in account_ids:
            for r in resources:
                futures[w.submit(
                    process_account_resources, a, bucket, prefix,
                    region, store, start, end, r)] = (a, r)

        indexer = RESOURCE_FILE_INDEXERS[r]
        for f in as_completed(futures):
            a, r = futures[f]
            if f.exception():
                log.error("account:%s error:%s", a, f.exception())
                continue
            files, dl_stats = f.result()
            idx_stats = indexer(db, resource_config_iter(files))
            log.info(
                "loaded account:%s files:%d bytes:%s events:%d resources:%d idx-time:%d dl-time:%d",
                account_map[a]['name'], len(files),
                human_size(dl_stats['DownloadSize'] + dl_stats['CacheSize']),
                idx_stats['Records'],
                idx_stats['RowCount'],
                idx_stats['IndexTime'],
                dl_stats['FetchTime'])
            stats.update(dl_stats)
            stats.update(idx_stats)
    log.info("Loaded %d resources across %d accounts in %0.2f",
             stats['RowCount'], len(account_ids), time.time() - t)
1068620
def resource(self, *resources):
        
        resources = tuple(self.resources) + resources
        return Resource(self.client, resources)
745522
def update_resource(self, resource):
        ''''''
        index = self.resources.index(resource)
        data = {
            'resources__{index}'.format(index=index): resource
        }
        self.update(**data)
        self.reload()
        post_save.send(self.__class__, document=self)
391417
def get_resources(connection):
    
    resp = connection.describe(verbose=False).split('\r\n')
    resources = [x.replace('a=control:','') for x in resp if (x.find('control:') != -1 and x[-1] != '*' )]
    return resources
346235
private Resource getResource(
      final JobSubmissionEvent jobSubmissionEvent) {

    return new Resource()
        .setMemory(jobSubmissionEvent.getDriverMemory().get())
        .setvCores(jobSubmissionEvent.getDriverCPUCores().get());
  }
1339618
def get_resources(name, config):
    
    return tz.get_in(["resources", name], config,
                     tz.get_in(["resources", "default"], config, {}))
726291
def handle_resourcelist(ltext, **kwargs):
    '''
    
    '''
    base=kwargs.get('base', VERSA_BASEIRI)
    model=kwargs.get('model')
    iris = ltext.strip().split()
    newlist = model.generate_resource()
    for i in iris:
        model.add(newlist, VERSA_BASEIRI + 'item', I(iri.absolutize(i, base)))
    return newlist
1119733
def register_resources(klass, registry, resource_class):
        
        for rtype, resource_manager in registry.items():
            if not resource_manager.has_arn():
                continue
            if 'post-finding' in resource_manager.action_registry:
                continue
            resource_class.filter_registry.register('finding', klass)
516271
def run(self, resources):
        

        hwman = resources['connection']

        updater = hwman.hwman.app(name='device_updater')
        updater.run_script(self._script, no_reboot=self._no_reboot)
279914
def _load_resource(self, source_r, abs_path=False):
        

        r = self.doc.resource(source_r.name)

        r.url = self.resource_root.join(r.url).inner