Include any custom class views on the Sanic JWT Blueprint
18032
def __add_class_views(self):
        
        config = self.config
        if "class_views" in self.kwargs:
            class_views = self.kwargs.pop("class_views")

            for route, view in class_views:
                if issubclass(view, endpoints.BaseEndpoint) and isinstance(
                    route, str
                ):
                    self.bp.add_route(
                        view.as_view(
                            self.responses,
                            config=self.config,
                            instance=self.instance,
                        ),
                        route,
                        strict_slashes=config.strict_slashes(),
                    )
                else:
                    raise exceptions.InvalidClassViewsFormat()
1313459
void init() throws MpJwtProcessingException {
        String methodName = "init";
        if (tc.isDebugEnabled()) {
            Tr.entry(tc, methodName);
        }
        setUpJsseHelper();
        if (this.jsseHelper == null) {
            if (tc.isDebugEnabled()) {
                Tr.exit(tc, methodName);
            }
            return;
        }
        Properties sslProps = null;
        try {
            sslProps = getSslPropertiesFromJsseHelper();
        } catch (Exception e) {
            String msg = Tr.formatMessage(tc, "ERROR_LOADING_SSL_PROPS", new Object[] { e.getLocalizedMessage() });
            Tr.error(tc, msg);
            throw new MpJwtProcessingException(msg, e);
        }
        setKeystoreAndTruststoreNames(sslProps);
        if (tc.isDebugEnabled()) {
            Tr.exit(tc, methodName);
        }
    }
1326815
def render_as_json(func):
    
    if inspect.isclass(func):
        setattr(func, "_renderer", json_renderer)
        return func
    else:
        @functools.wraps(func)
        def decorated_view(*args, **kwargs):
            data = func(*args, **kwargs)
            return _build_response(data, jsonify)
        return decorated_view
106005
def register_view(self, view_class, *args, **kwargs):
        
        protected_view_class = self.view_class_factory(view_class)
        if 'endpoint' not in kwargs:
            kwargs['endpoint'] = view_class(*args, **kwargs).endpoint
        self.admin.add_view(protected_view_class(*args, **kwargs))
1143003
public function injectViewClasses()
    {
        $controller = $this->_controller();
        foreach ($this->getConfig('viewClasses') as $type => $class) {
            $controller->RequestHandler->setConfig('viewClassMap', [$type => $class]);
        }
    }
457551
def bind_blueprint(pale_api_module, flask_blueprint):
    """"""

    if not isinstance(flask_blueprint, Blueprint):
        raise TypeError(("pale.flask_adapter.bind_blueprint expected the "
                         "passed in flask_blueprint to be an instance of "
                         "Blueprint, but it was an instance of %s instead.")
                        % (type(flask_blueprint),))

    if not pale.is_pale_module(pale_api_module):
        raise TypeError(("pale.flask_adapter.bind_blueprint expected the "
                         "passed in pale_api_module to be a module, and to "
                         "have a _module_type defined to equal "
                         "pale.ImplementationModule, but it was an instance of "
                         "%s instead.")
                        % (type(pale_api_module),))

    endpoints = pale.extract_endpoints(pale_api_module)

    for endpoint in endpoints:
        endpoint._set_response_class(RESPONSE_CLASS)
        method = [endpoint._http_method]
        name = endpoint._route_name
        handler = endpoint._execute

        flask_blueprint.add_url_rule(
                endpoint._uri,
                name,
                view_func=ContextualizedHandler(handler),
                methods=method)
639067
def __check_deprecated(self):
        
        # Depracation notices
        if "SANIC_JWT_HANDLER_PAYLOAD_SCOPES" in self.app.config:
            raise exceptions.InvalidConfiguration(
                "SANIC_JWT_HANDLER_PAYLOAD_SCOPES has been deprecated. "
                "Instead, pass your handler method (not an import path) as "
                "initialize(add_scopes_to_payload=my_scope_extender)"
            )

        if "SANIC_JWT_PAYLOAD_HANDLER" in self.app.config:
            raise exceptions.InvalidConfiguration(
                "SANIC_JWT_PAYLOAD_HANDLER has been deprecated. "
                "Instead, you will need to subclass Authentication. "
            )

        if "SANIC_JWT_HANDLER_PAYLOAD_EXTEND" in self.app.config:
            raise exceptions.InvalidConfiguration(
                "SANIC_JWT_HANDLER_PAYLOAD_EXTEND has been deprecated. "
                "Instead, you will need to subclass Authentication. "
                "Check out the documentation for more information."
            )
1045377
def init_app(self, app, decorators=None):
        
        self.decorators = decorators or self.decorators
        self.app = app

        self.load_config(app)
        # self.load_apispec(app)
        if self.template_file is not None:
            self.template = self.load_swagger_file(self.template_file)
        self.register_views(app)
        self.add_headers(app)

        if self.parse:
            if RequestParser is None:
                raise RuntimeError('Please install flask_restful')
            self.parsers = {}
            self.schemas = {}
            self.format_checker = jsonschema.FormatChecker()
            self.parse_request(app)

        self._configured = True
        app.swag = self
753263
def render_view(parser, token):
    
    bits = token.split_contents()

    n = len(bits)
    if n < 2:
        raise TemplateSyntaxError("'%s' takes at least one view as argument")

    viewname = bits[1]

    kwargs = {}
    if n > 2:
        for bit in bits[2:]:
            match = kwarg_re.match(bit)
            if not match:
                raise TemplateSyntaxError("Malformed arguments to render_view tag")
            name, value = match.groups()
            if name:
                kwargs[name] = parser.compile_filter(value)

    return StringNode(viewname, kwargs)
915791
function buildViewAttribsFire( def, code ) {
    code.pm = true;
    const attribs = def[ "view.attribs" ];
    if ( typeof attribs !== 'object' ) return;
    try {
        for ( const attName of Object.keys( attribs ) ) {
            const camelCaseAttName = camelCase( attName );
            if ( !code.isAction( attName ) ) {
                buildViewAttribsInitFire( camelCaseAttName, code );
            }
        }
    } catch ( ex ) {
        bubble( ex, `...in buildViewAttribsFire - view.attribs: ${JSON.stringify(attribs, null, "  ")}` );
    }
}
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);
                }
            }
        }
    }
1320958
def community_responsify(schema_class, mimetype):
    
    def view(data, code=200, headers=None, links_item_factory=None,
             page=None, urlkwargs=None, links_pagination_factory=None):
        """Generate the response object."""
        if isinstance(data, Community):
            last_modified = data.updated
            response_data = schema_class(
                context=dict(item_links_factory=links_item_factory)
            ).dump(data).data
        else:
            last_modified = None
            response_data = schema_class(
                context=dict(
                    total=data.query.count(),
                    item_links_factory=links_item_factory,
                    page=page,
                    urlkwargs=urlkwargs,
                    pagination_links_factory=links_pagination_factory)
            ).dump(data.items, many=True).data

        response = current_app.response_class(
            json.dumps(response_data, **_format_args()),
            mimetype=mimetype)
        response.status_code = code

        if last_modified:
            response.last_modified = last_modified

        if headers is not None:
            response.headers.extend(headers)
        return response
    return view
620035
def generate_endpoint_classes(db, generate_pks=False):
    """"""
    seen_classes = set()
    for cls in current_app.class_references.values():
        seen_classes.add(cls.__tablename__)
    with app.app_context():
        db.metadata.reflect(bind=db.engine)
        for name, table in db.metadata.tables.items():
            if not name in seen_classes:
                seen_classes.add(name)
                if not table.primary_key and generate_pks:
                    cls = add_pk_if_required(db, table, name)
                else:
                    cls = type(
                        str(name),
                        (sandman_model, db.Model),
                        {'__tablename__': name})
                register(cls)
852254
def create_swagger_json_handler(app, **kwargs):
    

    spec = getattr(app, SWAGGER_ATTR_NAME, SwaggerSpec())
    _add_blueprint_specs(app, spec)
    spec_dict = spec.swagger_definition(**kwargs)
    encoded_spec = json.dumps(spec_dict).encode("UTF-8")

    def swagger():
        return Response(
            encoded_spec,
            # we allow CORS, so this can be requested at swagger.io
            headers={
                "Access-Control-Allow-Origin": "*"
            },
            content_type="application/json",
        )

    return swagger
573363
def register_service(cls, primary_key_type):
    
    view_func = cls.as_view(cls.__name__.lower())  # pylint: disable=no-member
    methods = set(cls.__model__.__methods__)  # pylint: disable=no-member

    if 'GET' in methods:  # pylint: disable=no-member
        current_app.add_url_rule(
            cls.__model__.__url__ + '/', defaults={'resource_id': None},
            view_func=view_func,
            methods=['GET'])
        current_app.add_url_rule(
            '{resource}/meta'.format(resource=cls.__model__.__url__),
            view_func=view_func,
            methods=['GET'])
    if 'POST' in methods:  # pylint: disable=no-member
        current_app.add_url_rule(
            cls.__model__.__url__ + '/', view_func=view_func, methods=['POST', ])
    current_app.add_url_rule(
        '{resource}/<{pk_type}:{pk}>'.format(
            resource=cls.__model__.__url__,
            pk='resource_id', pk_type=primary_key_type),
        view_func=view_func,
        methods=methods - {'POST'})
    current_app.classes.append(cls)
680318
@Override
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    protected View onCreateView(View parent, String name, AttributeSet attrs) throws ClassNotFoundException {
        return mCalligraphyFactory.onViewCreated(super.onCreateView(parent, name, attrs),
                getContext(), attrs);
    }
405650
def register_views(self, app):
        

        # Wrap the views in an arbitrary number of decorators.
        def wrap_view(view):
            if self.decorators:
                for decorator in self.decorators:
                    view = decorator(view)
            return view

        if self.config.get('swagger_ui', True):
            uiversion = self.config.get('uiversion', 3)
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__,
                url_prefix=self.config.get('url_prefix', None),
                subdomain=self.config.get('subdomain', None),
                template_folder=self.config.get(
                    'template_folder', 'ui{0}/templates'.format(uiversion)
                ),
                static_folder=self.config.get(
                    'static_folder', 'ui{0}/static'.format(uiversion)
                ),
                static_url_path=self.config.get('static_url_path', None)
            )

            blueprint.add_url_rule(
                self.config.get('specs_route', '/apidocs/'),
                'apidocs',
                view_func=wrap_view(APIDocsView().as_view(
                    'apidocs',
                    view_args=dict(config=self.config)
                ))
            )

            # backwards compatibility with old url style
            blueprint.add_url_rule(
                '/apidocs/index.html',
                view_func=lambda: redirect(url_for('flasgger.apidocs'))
            )
        else:
            blueprint = Blueprint(
                self.config.get('endpoint', 'flasgger'),
                __name__
            )

        for spec in self.config['specs']:
            self.endpoints.append(spec['endpoint'])
            blueprint.add_url_rule(
                spec['route'],
                spec['endpoint'],
                view_func=wrap_view(APISpecsView.as_view(
                    spec['endpoint'],
                    loader=partial(
                        self.get_apispecs, endpoint=spec['endpoint'])
                ))
            )

        app.register_blueprint(blueprint)