Register a honeycomb service.

    :param package_folder: Path to folder with service to load
    :returns: Validated service object
    :rtype: :func:`honeycomb.utils.defs.ServiceType`
351948
def register_service(package_folder):
    
    logger.debug("registering service %s", package_folder)
    package_folder = os.path.realpath(package_folder)
    if not os.path.exists(package_folder):
        raise ServiceNotFound(os.path.basename(package_folder))

    json_config_path = os.path.join(package_folder, CONFIG_FILE_NAME)
    if not os.path.exists(json_config_path):
        raise ConfigFileNotFound(json_config_path)

    with open(json_config_path, "r") as f:
        config_json = json.load(f)

    # Validate service and alert config
    config_utils.validate_config(config_json, defs.SERVICE_ALERT_VALIDATE_FIELDS)

    config_utils.validate_config(config_json.get(defs.SERVICE_CONFIG_SECTION_KEY, {}),
                                 defs.SERVICE_CONFIG_VALIDATE_FIELDS)
    _validate_supported_platform(config_json)
    _validate_alert_configs(config_json)
    config_utils.validate_config_parameters(config_json,
                                            defs.SERVICE_ALLOWED_PARAMTER_KEYS,
                                            defs.SERVICE_ALLOWED_PARAMTER_TYPES)

    service_type = _create_service_object(config_json)
    service_type.alert_types = _create_alert_types(config_json, service_type)

    return service_type
1047635
def registerSds(self, sdsObj, **kwargs):
        
        # Register existing SDS running SDS binary (need to be installed manually but not added to MDM)
        # 
        self.conn.connection._check_login()    

        response = self.conn.connection._do_post("{}/{}".format(self.conn.connection._api_url, "types/Sds/instances"), json=sdsObj.__to_dict__())
        return response
1073076
def _setup_packages(self, sc):
        
        packages = self.py_packages
        if not packages:
            return
        for package in packages:
            mod = importlib.import_module(package)
            try:
                mod_path = mod.__path__[0]
            except AttributeError:
                mod_path = mod.__file__
            tar_path = os.path.join(self.run_path, package + '.tar.gz')
            tar = tarfile.open(tar_path, "w:gz")
            tar.add(mod_path, os.path.basename(mod_path))
            tar.close()
            sc.addPyFile(tar_path)
907556
def requires_package(pkg, msg, error_type=ImportError):
    
    def _requires_package(func):
        def wrapper(*args, **kwargs):
            if pkg is None:
                raise error_type(msg)
            return func(*args, **kwargs)
        return wrapper
    return _requires_package
1102642
def register(self, model_alias, code='general', name=None, order=None, display_filter=None):
        
        model_alias = self.get_model_alias(model_alias)

        def wrapper(create_layout):
            item = TabItem(
                code=code,
                create_layout=create_layout,
                name=name,
                order=order,
                display_filter=display_filter
            )

            if item in self.tabs[model_alias]:
                raise Exception("Tab {} already registered for model {}".format(code, model_alias))

            self.tabs[model_alias].append(item)
            self.tabs[model_alias] = sorted(self.tabs[model_alias], key=lambda item: item.order if item.order else 999)

            return create_layout
        return wrapper
1109827
def _register_file_server(self, app):
        
        if isinstance(self.driver, local.LocalStorageDriver) \
                and self.config["serve_files"]:
            server_url = self.config["serve_files_url"].strip("/").strip()
            if server_url:
                url = "/%s/<path:object_name>" % server_url

                @app.route(url, endpoint=SERVER_ENDPOINT)
                def files_server(object_name):
                    obj = self.get(object_name)
                    if obj is not None:
                        dl = flask_request.args.get("dl")
                        name = flask_request.args.get("name", obj.name)

                        if get_file_extension(name) != obj.extension:
                            name += ".%s" % obj.extension

                        _url = obj.get_cdn_url()
                        return send_file(_url,
                                         as_attachment=True if dl else False,
                                         attachment_filename=name,
                                         conditional=True)
                    else:
                        abort(404)
            else:
                warnings.warn("Flask-Cloudy can't serve files. 'STORAGE_SERVER_FILES_URL' is not set")
403962
private void loadDynamicJavaRegisteredServices() {
        Map<Package,Map<String,String>> packagedJava = new HashMap<>();
        try {
            for (Asset javaAsset : AssetCache.getAssets(Asset.JAVA)) {
                // process RegisteredService-annotated classes
                if (javaAsset.getStringContent().indexOf("@RegisteredService") > 0 ||
                        javaAsset.getStringContent().indexOf("@Monitor") > 0 ||
                        javaAsset.getStringContent().indexOf("@Path") > 0 ||
                        javaAsset.getStringContent().indexOf("@Api") > 0 ||
                        javaAsset.getStringContent().indexOf("@ScheduledJob") > 0) {
                    String className = JavaNaming.getValidClassName(javaAsset.getName());
                    Package javaAssetPackage = PackageCache.getAssetPackage(javaAsset.getId());
                    if (javaAssetPackage == null) {
                        logger.severe("Omitting unpackaged Registered Service from compilation: " + javaAsset.getLabel());
                    }
                    else {
                        String qName = JavaNaming.getValidPackageName(javaAssetPackage.getName()) + "." + className;
                        Map<String,String> javaSources = packagedJava.get(javaAssetPackage);
                        if (javaSources == null) {
                            javaSources = new HashMap<>();
                            packagedJava.put(javaAssetPackage, javaSources);
                        }
                        javaSources.put(qName, javaAsset.getStringContent());
                    }
                }
            }
        }
        catch (Exception ex) {
            logger.severeException(ex.getMessage(), ex);
        }

        if (!packagedJava.isEmpty()) {
            for (Package pkg : packagedJava.keySet()) {
                try {
                    List<Class<?>> classes = CompiledJavaCache.compileClasses(getClass().getClassLoader(), pkg, packagedJava.get(pkg), true);
                    for (Class<?> clazz : classes) {
                        RegisteredService registeredService = clazz.getAnnotation(RegisteredService.class);
                        if (registeredService == null) {
                            // jax-rs services, and swagger Apis
                            Path pathAnnotation = clazz.getAnnotation(Path.class);
                            if (pathAnnotation != null) {
                                String resourcePath = pathAnnotation.value() == null ? clazz.getPackage().getName() + "/" + clazz.getSimpleName() : pathAnnotation.value();
                                if (JsonService.class.isAssignableFrom(clazz)) {
                                    logger.info("JAX-RS JSON Service: " + resourcePath + " --> '" + clazz + "'");
                                    DynamicJavaServiceRegistry.addRegisteredService(JsonService.class.getName(), clazz.getName(), resourcePath);
                                }
                                if (XmlService.class.isAssignableFrom(clazz)) {
                                    logger.info("JAX-RS XML Service: " + resourcePath + " --> '" + clazz + "'");
                                    DynamicJavaServiceRegistry.addRegisteredService(XmlService.class.getName(), clazz.getName(), resourcePath);
                                }
                            }
                            // Monitor annotation
                            Monitor monitorAnnotation = clazz.getAnnotation(Monitor.class);
                            if (monitorAnnotation != null) {
                                logger.info("Monitor Service: " + monitorAnnotation.value() + " --> '" + clazz + "'");
                                String monitorCategory = monitorAnnotation.category().getName();
                                MonitorRegistry.getInstance().addDynamicService(monitorCategory, clazz.getName());
                            }
                            // ScheduledJob annotation
                            ScheduledJob scheduledJobAnnotation = clazz.getAnnotation(ScheduledJob.class);
                            if (scheduledJobAnnotation != null) {
                                logger.info("Scheduled Job: " + scheduledJobAnnotation.value() + " --> '" + clazz + "'");
                                DynamicJavaServiceRegistry.addRegisteredService(com.centurylink.mdw.model.monitor.ScheduledJob.class.getName(), clazz.getName());
                            }
                        }
                        else {
                            for (int i = 0; i < registeredService.value().length; i++) {
                                String serviceName = registeredService.value()[i].getName();
                                logger.info("@RegisteredService: " + serviceName + " Class: " + clazz);
                                DynamicJavaServiceRegistry.addRegisteredService(serviceName, clazz.getName());
                            }
                        }
                    }
                }
                catch (Exception ex) {
                  // let other packages continue to process
                  logger.severeException("Failed to process Dynamic Java services in package " + pkg.getLabel() + ": " + ex.getMessage(), ex);
                }
            }
        }
    }
1331542
public void register(Context context) {
        if (mRegisteredContext != null) {
            throw new IllegalStateException("Already registered");
        }

        mRegisteredContext = context;
        context.registerReceiver(this, mPackageFilter);
    }
881825
def create(self, resource):
        
        schema = PackageSchema(exclude=('id', 'created', 'updated', 'test_count', 'agent_id', 'result_id'))
        json = self.service.encode(schema, resource)

        schema = PackageSchema()
        resp = self.service.create(self.base, json)
        return self.service.decode(schema, resp)
697488
def from_href(cls, href, **kw):
    
    package = cls._HREF_TO_PACKAGE_CACHE.get(href)
    if package is not None:
      return package
    link_href = Link.wrap(href)
    for package_type in cls._REGISTRY:
      try:
        package = package_type(link_href.url, **kw)
        break
      except package_type.InvalidPackage:
        continue
    if package is not None:
      cls._HREF_TO_PACKAGE_CACHE.store(href, package)
    return package
733596
def register_msgpack():
    """"""
    try:
        import msgpack
        registry.register('msgpack', msgpack.packs, msgpack.unpacks,
                content_type='application/x-msgpack',
                content_encoding='binary')
    except ImportError:

        def not_available(*args, **kwargs):
            """In case a client receives a msgpack message, but yaml
            isn't installed."""
            raise SerializerNotInstalled(
                    "No decoder installed for msgpack. "
                    "Install the msgpack library")
        registry.register('msgpack', None, not_available,
                          'application/x-msgpack')
1257415
def register_app(self, app):
        
        app.route(self.uri, methods=self.methods)(self.callable_obj)

        return self
509392
def load(cls, partname, content_type, blob, package):
        
        return cls(partname, content_type, blob)
266349
def register_backend(cls: Type[StorageBackend]):
    """"""
    if not issubclass(cls, StorageBackend):
        raise TypeError("cls must be a subclass of StorageBackend")
    __registry__[cls.NAME] = cls
    return cls
259460
private function registerPackageMakeCommand()
    {
        $this->app->bindShared('command.make.package', function ($app)
        {
            return new PackageMakeCommand($app['files'], $app['packages']);
        });

        $this->commands('command.make.package');
    }
985498
def register_mappings(self, alias, package_name):
        
        # For backwards compatibility, we also allow for ES2 mappings to be
        # placed at the root level of the specified package path, and not in
        # the `<package-path>/v2` directory.
        if ES_VERSION[0] == 2:
            try:
                resource_listdir(package_name, 'v2')
                package_name += '.v2'
            except (OSError, IOError) as ex:
                if getattr(ex, 'errno', 0) != errno.ENOENT:
                    raise
                warnings.warn(
                    "Having mappings in a path which doesn't specify the "
                    "Elasticsearch version is deprecated. Please move your "
                    "mappings to a subfolder named according to the "
                    "Elasticsearch version which your mappings are intended "
                    "for. (e.g. '{}/v2/{}')".format(
                        package_name, alias),
                    PendingDeprecationWarning)
        else:
            package_name = '{}.v{}'.format(package_name, ES_VERSION[0])

        def _walk_dir(aliases, *parts):
            root_name = build_index_name(self.app, *parts)
            resource_name = os.path.join(*parts)

            if root_name not in aliases:
                self.number_of_indexes += 1

            data = aliases.get(root_name, {})

            for filename in resource_listdir(package_name, resource_name):
                index_name = build_index_name(
                    self.app,
                    *(parts + (filename, ))
                )
                file_path = os.path.join(resource_name, filename)

                if resource_isdir(package_name, file_path):
                    _walk_dir(data, *(parts + (filename, )))
                    continue

                ext = os.path.splitext(filename)[1]
                if ext not in {'.json', }:
                    continue

                assert index_name not in data, 'Duplicate index'
                data[index_name] = self.mappings[index_name] = \
                    resource_filename(
                        package_name, os.path.join(resource_name, filename))
                self.number_of_indexes += 1

            aliases[root_name] = data

        # Start the recursion here:
        _walk_dir(self.aliases, alias)
1358017
def map_req(self, requirement):
        
        if isinstance(self._packages_map, dict):
            local_name = self._packages_map.get(requirement, requirement.name)
        else:
            local_name = self._packages_map(requirement)
        return local_name