Discovers data services.
777182
private function discoverDataServices()
    {
        $path = $this->rootDir.'/'.$this->directory;
        $finder = new Finder();
        $finder->files()->in($path);

        /** @var SplFileInfo $file */
        foreach ($finder as $file) {
            $class = $this->classForFile($file);
            /* @var \Lullabot\Mpx\DataService\Annotation\DataService $annotation */
            $annotation = $this->annotationReader->getClassAnnotation(new \ReflectionClass($class), 'Lullabot\Mpx\DataService\Annotation\DataService');
            if (!$annotation) {
                continue;
            }

            // Now that we have a new data service, we need to attach any
            // custom field implementations.
            $customFields = $this->getCustomFields($annotation);
            $this->dataServices[$annotation->getService()][$annotation->getObjectType()][$annotation->getSchemaVersion()] = new DiscoveredDataService($class, $annotation, $customFields);
        }
    }
429554
async def discover_master(self, service, timeout):
        """"""
        # TODO: get lock
        idle_timeout = timeout
        # FIXME: single timeout used 4 times;
        #   meaning discovery can take up to:
        #   3 * timeout * (sentinels count)
        #
        #   having one global timeout also can leed to
        #   a problem when not all sentinels are checked.

        # use a copy, cause pools can change
        pools = self._pools[:]
        for sentinel in pools:
            try:
                with async_timeout(timeout, loop=self._loop):
                    address = await self._get_masters_address(
                        sentinel, service)

                pool = self._masters[service]
                with async_timeout(timeout, loop=self._loop), \
                        contextlib.ExitStack() as stack:
                    conn = await pool._create_new_connection(address)
                    stack.callback(conn.close)
                    await self._verify_service_role(conn, 'master')
                    stack.pop_all()

                return conn
            except asyncio.CancelledError:
                # we must correctly handle CancelledError(s):
                #   application may be stopped or function can be cancelled
                #   by outer timeout, so we must stop the look up.
                raise
            except asyncio.TimeoutError:
                continue
            except DiscoverError as err:
                sentinel_logger.debug("DiscoverError(%r, %s): %r",
                                      sentinel, service, err)
                await asyncio.sleep(idle_timeout, loop=self._loop)
                continue
            except RedisError as err:
                raise MasterReplyError("Service {} error".format(service), err)
            except Exception:
                # TODO: clear (drop) connections to schedule reconnect
                await asyncio.sleep(idle_timeout, loop=self._loop)
                continue
        else:
            raise MasterNotFoundError("No master found for {}".format(service))
225221
def ossos_discoveries(directory=parameters.REAL_KBO_AST_DIR,
                      suffix='ast',
                      no_nt_and_u=False,
                      single_object=None,
                      all_objects=True,
                      data_release=None,
                      ):
    
    retval = []
    # working_context = context.get_context(directory)
    # files = working_context.get_listing(suffix)
    files = [f for f in os.listdir(directory) if (f.endswith('mpc') or f.endswith('ast') or f.endswith('DONE'))]

    if single_object is not None:
        files = filter(lambda name: name.startswith(single_object), files)
    elif all_objects and data_release is not None:
        # only return the objects corresponding to a particular Data Release
        data_release = ossos_release_parser(table=True, data_release=data_release)
        objects = data_release['object']
        files = filter(lambda name: name.partition(suffix)[0].rstrip('.') in objects, files)

    for filename in files:
        # keep out the not-tracked and uncharacteried.
        if no_nt_and_u and (filename.__contains__('nt') or filename.startswith('u')):
            continue
        # observations = mpc.MPCReader(directory + filename)
        mpc_filename = directory + filename
        abg_filename = os.path.abspath(directory + '/../abg/') + "/" + os.path.splitext(filename)[0] + ".abg"
        obj = TNO(None, ast_filename=mpc_filename, abg_filename=abg_filename)
        retval.append(obj)

    return retval
1213738
def system_find_data_objects(input_params={}, always_retry=True, **kwargs):
    
    return DXHTTPRequest('/system/findDataObjects', input_params, always_retry=always_retry, **kwargs)
427651
function DiscoveryDecorator(AkeraConnector) {

  function getDatabasesMeta(conn, cb) {
    conn.getMetaData(function(err, meta) {
      if (err !== null)
        cb(err);
      else {
        meta.allDatabases().then(function(dbs) {
          cb(null, dbs);
        }, cb);
      }
    });
  }

  function getTableMeta(conn, schema, table, cb) {
    getDatabasesMeta(conn,
        function(err, dbs) {
          if (err !== null)
            cb(err);
          else {
            var callback = function(err) {
              if (err !== null)
                cb(err);

              for ( var t in tables) {
                if (table === tables[t].getName()) {
                  cb(null, tables[t]);
                  return;
                }
              }

              cb(new Error('Table not found in database: ' + schema + '.'
                  + table));
            };

            // select first database as default if not specified
            if (!schema)
              schema = dbs[0].getLname();

            for ( var d in dbs) {
              if (schema === dbs[d].getLname()) {
                var tables = [];
                var info = {
                  idx : d,
                  schema : schema
                };

                fetchSchemaTables(dbs, info, tables, callback);

                return;
              }
            }
            cb(new Error('Database not connected: ' + schema));
          }
        });
  }

  var dataTypeConversion = {
    DATE : 'Date',
    DATETIME : 'Date',
    'DATETIME-TZ' : 'Date',
    LOGICAL : 'Boolean',
    DECIMAL : 'Number',
    INTEGER : 'Number',
    INT64 : 'Number',
    CHARACTER : 'String',
    CLOB : 'String',
    BLOB : 'Buffer'
  };

  function getTableModel(tblMeta, cb) {
    tblMeta.getAllFields().then(function(fields) {
      var result = [];

      for ( var f in fields) {
        var field = fields[f];

        result.push({
          owner : tblMeta.getDatabase(),
          tableName : tblMeta.getName(),
          columnName : field.name,
          dataType : field.type,
          nullable : field.mandatory ? 'N' : 'Y',
          type : dataTypeConversion[field.type.toUpperCase()]
        });
      }

      cb(null, result);
    }, cb);
  }

  function getTablePrimaryKeys(tblMeta, cb) {
    tblMeta.getPk().then(function(pk) {
      var result = [];

      for ( var f in pk.fields) {
        var field = pk.fields[f];

        result.push({
          owner : tblMeta.getDatabase(),
          tableName : tblMeta.getName(),
          columnName : field.name,
          keySeq : field.fld_pos,
          pkName : field.idx_name
        });
      }

      cb(null, result);
    }, cb);
  }

  function getDatabaseSchemas(dbs, options) {
    var offset = 0;
    var limit = dbs.length;
    var result = [];

    if (options !== null && typeof options === 'object') {
      if (typeof options.offset === 'number')
        offset = options.offset;
      if (typeof options.skip === 'number')
        offset += options.skip;
      if (typeof options.limit === 'number')
        limit = options.limit;
    }

    for (var i = offset; i < limit; i++) {
      result.push({
        catalog : dbs[i].getLname(),
        schema : dbs[i].getLname()
      });
    }

    return result;
  }

  function getModelDefinitions(tblsMeta) {
    var result = [];

    for ( var t in tblsMeta) {
      result.push({
        type : 'table',
        name : tblsMeta[t].getName(),
        owner : tblsMeta[t].getDatabase()
      });
    }

    return result;
  }

  function getDatabaseTables(dbMeta, cb) {
    dbMeta.allTables().then(function(tables) {
      cb(null, tables);
    }, cb);
  }

  function fetchSchemaTables(dbs, info, tables, cb) {
    getDatabaseTables(dbs[info.idx], function(err, tbls) {
      if (err !== null)
        cb(err);
      else {
        for ( var t in tbls) {
          tables.push(tbls[t]);
        }
        // reach the end of databases or found the one we're looking for
        if ((info.schema && info.schema === dbs[info.idx].getLname())
            || ++info.idx === dbs.length)
          cb(null, tables);
        else
          fetchSchemaTables(dbs, info, tables, cb);
      }
    });
  }

  AkeraConnector.prototype.discoverDatabaseSchemas = function(options, cb) {
    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    getDatabasesMeta(this, function(err, dbs) {
      if (err !== null)
        cb(err);
      else {
        cb(null, getDatabaseSchemas(dbs, options));
      }
    });
  };

  /**
   * Discover model definitions
   * 
   * @param {Object}
   *         options Options for discovery
   * @param {Function}
   *         [cb] The callback function
   */
  AkeraConnector.prototype.discoverModelDefinitions = function(options, cb) {
    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    var schema = null;
    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    getDatabasesMeta(this, function(err, dbs) {
      if (err !== null)
        cb(err);
      else {
        var tables = [];
        var info = {
          idx : 0,
          schema : schema
        };

        fetchSchemaTables(dbs, info, tables, function(err) {
          if (err !== null)
            cb(err);

          cb(null, getModelDefinitions(tables));
        });
      }
    });

  };

  /**
   * Discover model properties from a table
   * 
   * @param {String}
   *         table The table name
   * @param {Object}
   *         options The options for discovery (schema/owner)
   * @param {Function}
   *         [cb] The callback function
   * 
   */
  AkeraConnector.prototype.discoverModelProperties = function(table, options,
      cb) {
    var schema = null;

    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    if (table === null && typeof table !== 'string') {
      cb(new Error('Table name is mandatory for model properties discovery.'));
      return;
    }

    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    if (!schema) {
      schema = this.getDefaultSchema();
    }

    getTableMeta(this, schema, table, function(err, tblMeta) {
      if (err) {
        cb(err);
      } else {
        getTableModel(tblMeta, cb);
      }
    });
  };

  /**
   * Discover model primary keys from a table
   * 
   * @param {String}
   *         table The table name
   * @param {Object}
   *         options The options for discovery (schema/owner)
   * @param {Function}
   *         [cb] The callback function
   * 
   */
  AkeraConnector.prototype.discoverPrimaryKeys = function(table, options, cb) {
    var schema = null;

    if (!cb && typeof options === 'function') {
      cb = options;
      options = null;
    }

    if (table === null && typeof table !== 'string') {
      cb(new Error('Table name is mandatory for model primary keys discovery.'));
      return;
    }

    if (options !== null && typeof options === 'object') {
      schema = options.owner || options.schema;
    }

    if (!schema) {
      schema = this.getDefaultSchema();
    }

    getTableMeta(this, schema, table, function(err, tblMeta) {
      if (err) {
        cb(err);
      } else {
        getTablePrimaryKeys(tblMeta, cb);
      }
    });
  };

  AkeraConnector.prototype.getDefaultSchema = function() {
    if (this.dataSource && this.dataSource.settings
        && this.dataSource.settings.database) {
      return this.dataSource.settings.database;
    }
    return undefined;
  };
}
1162005
public void discoverConnnectionProperties() {
    Connection connection = null;
    try {
      connection = getConnection();
      if (connection == null) {
        getLogger().warn("Could not get a conneciton");
        return;
      }
      DatabaseMetaData meta = connection.getMetaData();
      Util util = new Util();
      util.setLoggerRepository(repository);
      if (overriddenSupportsGetGeneratedKeys != null) {
        supportsGetGeneratedKeys = overriddenSupportsGetGeneratedKeys
            .booleanValue();
      } else {
        supportsGetGeneratedKeys = util.supportsGetGeneratedKeys(meta);
      }
      supportsBatchUpdates = util.supportsBatchUpdates(meta);
      dialectCode = Util.discoverSQLDialect(meta);
    } catch (SQLException se) {
      getLogger().warn("Could not discover the dialect to use.", se);
    } finally {
      DBHelper.closeConnection(connection);
    }
  }
227728
Object getDataService(T session, Class cls) throws DataServiceException {
		String dataServiceClassName = cls.getName();
		logger.debug("Looking for dataservice : {}", dataServiceClassName);
		if (cls.isAnnotationPresent(DataService.class)) {
			return _getDataService(session, cls);
		} else {
			throw new DataServiceException(dataServiceClassName + " is not annotated with @" + DataService.class.getSimpleName());
		}
	}
691538
def _verifyDiscoveredServices(self, claimed_id, services,
                                  to_match_endpoints):
        """"""

        # Search the services resulting from discovery to find one
        # that matches the information from the assertion
        failure_messages = []
        for endpoint in services:
            for to_match_endpoint in to_match_endpoints:
                try:
                    self._verifyDiscoverySingle(endpoint, to_match_endpoint)
                except ProtocolError as why:
                    failure_messages.append(str(why))
                else:
                    # It matches, so discover verification has
                    # succeeded. Return this endpoint.
                    return endpoint
        else:
            logging.error('Discovery verification failure for %s' %
                          (claimed_id, ))
            for failure_message in failure_messages:
                logging.error(' * Endpoint mismatch: ' + failure_message)

            raise DiscoveryFailure(
                'No matching endpoint found after discovering %s' %
                (claimed_id, ), None)
394018
private static Map<String, String> findServiceBeanDefinitions(ConfigurableListableBeanFactory beanFactory) {
		final Map<String, String> serviceBeanNames = new HashMap<>();
		for (String beanName : beanFactory.getBeanDefinitionNames()) {
			JsonRpcService jsonRpcPath = beanFactory.findAnnotationOnBean(beanName, JsonRpcService.class);
			if (hasServiceAnnotation(jsonRpcPath)) {
				String pathValue = jsonRpcPath.value();
				logger.debug("Found JSON-RPC path '{}' for bean [{}].", pathValue, beanName);
				if (isNotDuplicateService(serviceBeanNames, beanName, pathValue))
					serviceBeanNames.put(pathValue, beanName);
			}
		}
		collectFromParentBeans(beanFactory, serviceBeanNames);
		return serviceBeanNames;
	}
1319848
def service(ctx):
    """"""

    install_service(ctx.obj['instance'], ctx.obj['dbhost'], ctx.obj['dbname'], ctx.obj['port'])
446084
def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        frontend_ip_configurations = []
        for raw_content in properties.get("frontendIPConfigurations", []):
            resource = Resource.from_raw_data(raw_content)
            frontend_ip_configurations.append(resource)
        properties["frontendIPConfigurations"] = frontend_ip_configurations

        raw_content = properties.get("backendAddressPool", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["backendAddressPool"] = resource

        raw_content = properties.get("probe", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["probe"] = resource

        return super(LoadBalancingRules, cls).process_raw_data(raw_data)
751112
def reading(self, service):
        
        # counting the new data to store to display them in the log provider - the service that offer data
        provider_token = service.provider.token
        default_provider.load_services()
        service_provider = default_provider.get_service(str(service.provider.name.name))
        date_triggered = service.date_triggered if service.date_triggered else service.date_created

        # get the data from the provider service
        kwargs = {'token': provider_token, 'trigger_id': service.id, 'date_triggered': date_triggered}
        data = self.provider(service_provider, **kwargs)

        if len(data) > 0:
            logger.info("{} - {} new data".format(service, len(data)))
        elif data is False:
            # if data is False, something went wrong
            self.is_ceil_reached(service)
1089688
def show(self, id):
        """"""
        # url('DataStores', id=ID)
        datastore = meta.Session.query(DataStore).get(id)

        # do not raise RuntimeError from discover_datasources
        # if in "test" mode
        try:
            datasources = discover_datasources(datastore.ogrstring)
        except RuntimeError:
            if "test" in request.params:
                datasources = None
            else:
                raise

        result = datastore.to_json()
        result['datasources'] = datasources
        return result
350389
def discover(names=None, pattern=['*.py'], skip='efp', dry_run=False, blacklist=None, name_greps=None,
             manual_reset=False, delete_history=False, max_devices=0,
             continue_from=None, result_file='./result.json', auto_reboot=False, keep_explorer=False,
             add_all_devices=False):
    
    if not os.path.exists(settings.OUTPUT_PATH):
        os.mkdir(settings.OUTPUT_PATH)

    if delete_history:
        os.system('del history.json')

    if blacklist:
        try:
            excludes = [line.strip('\n') for line in open(blacklist, 'r').readlines()
                        if not line.startswith('#')]
        except:
            logger.exception('Failed to open test case black list file')
            raise
    else:
        excludes = []

    log = None
    if os.path.isfile(result_file):
        try:
            log = json.load(open(result_file, 'r'))
        except:
            logger.exception('Failed to open result file')

    if not log:
        log = {}
        json.dump(log, open(result_file, 'w'), indent=2)

    suite = unittest.TestSuite()
    discovered = unittest.defaultTestLoader.discover('cases', pattern)

    if names and continue_from:
        names = names[names.index(continue_from):]

    for s1 in discovered:
        for s2 in s1:
            for case in s2:
                if case.__class__ is HarnessCase:
                    continue
                case_name = unicode(case.__class__.__name__)

                # grep name
                if name_greps and not any(fnmatch.fnmatch(case_name, name_grep) for name_grep in name_greps):
                    logger.info('case[%s] skipped by name greps', case_name)
                    continue

                # whitelist
                if len(names) and case_name not in names:
                    logger.info('case[%s] skipped', case_name)
                    continue

                # skip cases
                if case_name in log.keys():
                    if (log[case_name]['passed'] and ('p' in skip)) \
                        or (log[case_name]['passed'] is False and ('f' in skip)) \
                        or (log[case_name]['passed'] is None and ('e' in skip)):
                        logger.warning('case[%s] skipped for its status[%s]', case_name, log[case_name]['passed'])
                        continue

                # continue from
                if continue_from:
                    if continue_from != case_name:
                        logger.warning('case[%s] skipped for continue from[%s]', case_name, continue_from)
                        continue
                    else:
                        continue_from = None

                # black list
                if case_name in excludes:
                    logger.warning('case[%s] skipped for blacklist', case_name)
                    continue

                # max devices
                if max_devices and case.golden_devices_required > max_devices:
                    logger.warning('case[%s] skipped for exceeding max golden devices allowed[%d]', case_name, max_devices)
                    continue

                suite.addTest(case)
                logger.info('case[%s] added', case_name)

    if auto_reboot:
        argv = []
        argv.append('"%s"' % os.sep.join([os.getcwd(), 'start.bat']))
        argv.extend(['-p', pattern])
        argv.extend(['-k', skip])
        argv.extend(['-o', result_file])
        argv.append('-a')

        if manual_reset:
            argv.append('-m')

        if delete_history:
            argv.append('-d')

        auto_reboot_args = argv + names
    else:
        auto_reboot_args = None
        os.system('del "%s"' % RESUME_SCRIPT_PATH)

    # manual reset
    if manual_reset:
        settings.PDU_CONTROLLER_TYPE = 'MANUAL_PDU_CONTROLLER'
        settings.PDU_CONTROLLER_OPEN_PARAMS = {}
        settings.PDU_CONTROLLER_REBOOT_PARAMS = {}

    result = SimpleTestResult(result_file, auto_reboot_args, keep_explorer, add_all_devices)
    for case in suite:
        logger.info(case.__class__.__name__)

    if dry_run:
        return

    suite.run(result)
    return result
566295
function discoverServicesAndCharacteristics(error) {
      if (error) { return reject(error); }
      peripheral.discoverSomeServicesAndCharacteristics(
        ALL_SERVICES,
        ALL_CHARACTERISTICS,
        setupEmitter
      );
    }
463244
private List<ServiceInformation> getServiceInformations(URI location, final Map<String, String> params)
            throws IOException {
        final ReadOnlyDiscoveryClient discoveryClient = getDiscoveryClient(params);

        final String serviceType = params.get("serviceType");

        final List<ServiceInformation> services;

        if (serviceType != null) {
            services = discoveryClient.findAllServiceInformation(location.getHost(), serviceType);
        } else {
            services = discoveryClient.findAllServiceInformation(location.getHost());
        }
        return services;
    }
1334354
def rebuild_data_service(config, data_service_auth_data):
        
        auth = DataServiceAuth(config)
        auth.set_auth_data(data_service_auth_data)
        return DataServiceApi(auth, config.url)