text:
from django.db import models

import re
import unicodedata
import json

def getSlug(s):
    slug = unicodedata.normalize('NFKD', s)
    slug = slug.encode('ascii', 'ignore').lower()
    slug = re.sub(r'[^a-z0-9]+', '', slug).strip('-')
    slug = re.sub(r'[-]+', '', slug)
    return slug

VECTOR_LAYERS_TYPES = (
    ('kml', 'KML layer'),
    #('wfs', 'wfs layer'),
)

RASTER_LAYERS_TYPES = (
    ('OSM', 'OSM layer'),
    ('GOOGLE-STREET', 'Google street'),
    ('GOOGLE-SATELLITE', 'Google satellite'),
    ('GOOGLE-TERRAIN', 'Google terrain'),
    ('GOOGLE-HYBRID', 'Google hybrid'),

)

JS_BOOL_CHOICES = (
    ('true', 'True'),
    ('false', 'False'),
)

class _Layer(models.Model):

    name = models.CharField(null=False, blank=False, unique=True, max_length=200)
    description = models.TextField(null=True, blank=True)
    options = models.TextField(null=True, blank=True)

    class Meta:
        abstract = True

    def __unicode__(self):
        return u'%s' % (self.name)

class RasterLayer(_Layer):

    #maps = models.ManyToManyField(Map, related_name='raster_layers', null=True, blank=True)
    type = models.CharField(max_length=300, choices = RASTER_LAYERS_TYPES)

class VectorLayer(_Layer):

    #maps = models.ManyToManyField(Map, related_name='vector_layers', null=True, blank=True)
    type = models.CharField(max_length=300, choices = VECTOR_LAYERS_TYPES)
    layer_uri =  models.CharField(null=True, blank=True, max_length=300)

    #layer options
    extract_styles = models.CharField(choices = JS_BOOL_CHOICES, default="true", max_length=10);
    extract_attributes = models.CharField(choices = JS_BOOL_CHOICES, default="true", max_length=10);

    #popup_handler = models.BooleanField(default=False)

class Map(models.Model):

    name = models.CharField(null=False, blank=False, unique=True, max_length=200)
    description = models.TextField(null=True, blank=True)

    raster_layers = models.ManyToManyField(RasterLayer, through='MapsRasterLayers')
    vector_layers = models.ManyToManyField(VectorLayer, through='MapsVectorLayers')

    navigation_control = models.BooleanField(default=True)
    layer_switcher_control = models.BooleanField(default=False)
    scale_line_control = models.BooleanField(default=False)
    pan_zoom_bar_control = models.BooleanField(default=False)

    @property
    def ordered_raster_layers(self):
        return self.raster_layers.order_by('mapsrasterlayers__order')

    @property
    def ordered_vector_layers(self):
        return self.vector_layers.order_by('mapsvectorlayers__order')

    def getDivId(self):
        return getSlug(self.name)

    #this is an alternate approach for generating js.
    #still thinking about using it.
    def getJsonOptions(self):
        map_name = "map-"+str(map.id)
        map_options = {}
        map_controls = []
        if self.navigation_control:
            map_controls.append("new OpenLayers.Control.Navigation()")
        if self.pan_zoom_bar_control:
            map_controls.append("new OpenLayers.Control.PanZoomBar()")
        if self.layer_switcher_control:
            map_controls.append("new OpenLayers.Control.LayerSwitcher()")
        if self.scale_line_control:
            map_controls.append("new OpenLayers.Control.ScaleLine()")

        map_options['controls'] = map_controls
        out = [map_name, map_options]

        return json.dumps(out);

class MapsRasterLayers(models.Model):

    map = models.ForeignKey(Map)
    layer = models.ForeignKey(RasterLayer)
    order = models.IntegerField(blank=True, null=True)

    class Meta:
        ordering = ('order',)

class MapsVectorLayers(models.Model):

    map = models.ForeignKey(Map)
    layer = models.ForeignKey(VectorLayer)
    order = models.IntegerField(blank=True, null=True)

    class Meta:
        ordering = ('order',)

class UploadedFile(models.Model):
    file = models.FileField(upload_to='openlayers')
    description = models.TextField(null=True, blank=True)

try:
    import cms
    from cms_models import *
except:
    pass


text:
#include "stdafx.h"
#include "MipFieldParser.h"

#include <vector>
#include "MipDataPacket.h"

namespace mscl
{
    //forces the linker to include the Parser files
    //by using a global variable defined in their files
    bool run_once_forceLibraryToIncludeCompilationUnit()
    {
        //add the following 2 lines for each parser's file
        extern bool _forceLibraryToIncludeCompilationUnit_AHRS;
        _forceLibraryToIncludeCompilationUnit_AHRS = true;

        extern bool _forceLibraryToIncludeCompilationUnit_GNSS;
        _forceLibraryToIncludeCompilationUnit_GNSS = true;

        extern bool _forceLibraryToIncludeCompilationUnit_NAV;
        _forceLibraryToIncludeCompilationUnit_NAV = true;

        extern bool _forceLibraryToIncludeCompilationUnit_Shared;
        _forceLibraryToIncludeCompilationUnit_Shared = true;

        extern bool _forceLibraryToIncludeCompilationUnit_Displacement;
        _forceLibraryToIncludeCompilationUnit_Displacement = true;

        extern bool _forceLibraryToIncludeCompilationUnit_System;
        _forceLibraryToIncludeCompilationUnit_System = true;

        return true;
    }

    ParserMap& MipFieldParser::getParserMap()
    {
        //force the linker to include all the parser files
        static bool unused = run_once_forceLibraryToIncludeCompilationUnit();

        //create a static ParserMap (1st time only) and return it
        static ParserMap p;
        return p;
    }

    bool MipFieldParser::registerParser(MipTypes::ChannelField field, const MipFieldParser* parser)
    {
        ParserMap& map = getParserMap();

        //verify it doesn't already exist in the map
        if(map.find(field) != map.end())
        {
            assert(false);    //this should never happen
            return false;
        }

        //store the parser in the map of parsers
        getParserMap()[field] = parser;

        return true;
    }

    void MipFieldParser::parseField(const MipDataField& field, MipDataPoints& result)
    {
        //get the static parser map
        ParserMap& parsers = getParserMap();

        MipTypes::ChannelField chField = static_cast<MipTypes::ChannelField>(field.fieldId());

        //try to find a parser in our map that can parse this field type
        std::map<MipTypes::ChannelField, const MipFieldParser*>::const_iterator itr = parsers.find(chField);

        //if we can find a parser for this field type
        if(itr != parsers.end())
        {
            //parse the field for data
            itr->second->parse(field, result);
        }
        //if we failed to find a parser for this field type
        else
        {
            //just add a data point of this whole field as bytes
            result.push_back(MipDataPoint(chField, MipTypes::CH_UNKNOWN, valueType_Bytes, anyType(field.fieldData().data()), true));
        }
    }

    bool MipFieldParser::pointIsValid(uint16 allFlags, uint16 flagPos)
    {
        //check the flag position against the allFlags value
        return ((allFlags & flagPos) > 0);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
import classNames from 'classnames'
import { FormattedMessage } from 'react-intl'
import { fetchUsers, toggleUser } from './actions'
import { SearchBox, Pagination } from '../base/components'
import { UserItemList } from './components'

import './styles.sass'

class ListContainer extends Component {
  componentDidMount() {
    this.fetchData(1)
  }
  fetchData(page, search = undefined) {
    search = search != undefined ? search : this.props.search
    this.props.fetchUsers({ page: page, search: search })
  }
  render() {
    return (

          <SearchBox
            intl={this.props.intl}
            search={this.props.search}
            onSearch={this.fetchData.bind(this, 1)}
            />

          {this.props.list.data.map((item) => {
            return <UserItemList
              key={item._id}
              {...item}
              sending={this.props.sending}
              toggleUser={this.props.toggleUser}
              />
          })}

        <Pagination
          paging={this.props.list.paging}
          intl={this.props.intl}
          fetchData={this.fetchData.bind(this)}
          />

    )
  }
}

const mapStateToProps = (state) => {
  return {
    ...state.user,
    intl: state.intl
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    fetchUsers: (options) => {
      dispatch(fetchUsers(options))
    },
    toggleUser: (id, active) => {
      dispatch(toggleUser(id, active))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(ListContainer)


text:
module.exports = function ping() {
	return Promise.resolve({})
}


text:
using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Beyova;
using Beyova.Api;
using Beyova.ApiTracking;
using Beyova.ExceptionSystem;
using Beyova.RestApi;

namespace Beyova.Web
{
    /// <summary>
    /// Class RestApiContextConsistenceAttribute.
    /// This attribute is used in MVC to ensure following things are kept as same as REST API framework in Beyova.Common.
    /// <list type="number">
    /// <item><c>Token</c>, <c>User-Agent</c> and <c>IP address</c> would be initialized in <see cref="ContextHelper"/></item>
    /// <item><c>Exception</c>, <c>API Event</c> and <c>API Trace</c> would be handled.</item>
    /// </list>
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    public class RestApiContextConsistenceAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// Gets or sets the API tracking.
        /// </summary>
        /// <value>The API tracking.</value>
        public IApiTracking ApiTracking { get; protected set; }

        /// <summary>
        /// Gets or sets a value indicating whether [log API event].
        /// </summary>
        /// <value><c>true</c> if [log API event]; otherwise, <c>false</c>.</value>
        public bool LogApiEvent { get; set; }

        /// <summary>
        /// The settings
        /// </summary>
        private RestApiSettings settings;

        /// <summary>
        /// The API event
        /// </summary>
        [ThreadStatic]
        internal static ApiEventLog ApiEvent;

        /// <summary>
        /// The depth
        /// </summary>
        [ThreadStatic]
        internal static int Depth = 0;

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="RestApiContextConsistenceAttribute"/> class.
        /// </summary>
        /// <param name="restApiSetting">The rest API settings.</param>
        public RestApiContextConsistenceAttribute(RestApiSettings restApiSetting) : base()
        {
            this.settings = restApiSetting;
            ApiTracking = restApiSetting?.ApiTracking;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="RestApiContextConsistenceAttribute"/> class.
        /// </summary>
        /// <param name="settingName">Name of the setting.</param>
        public RestApiContextConsistenceAttribute(string settingName = null)
            : this(ApiHandlerBase.GetRestApiSettingByName(settingName, false))
        {
        }

        #endregion

        /// <summary>
        /// Called when [result executed].
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);

            // If using BeyovaBaseController, exception should be logger there, and in this method, no exception should appear.
            var baseException = filterContext.Exception?.Handle(new ExceptionScene
            {
                MethodName = string.Format("{0}: {1}", filterContext.HttpContext.Request.HttpMethod, filterContext.HttpContext.Request.RawUrl)
            }, data: (filterContext.Exception as BaseException)?.ReferenceData);

            if (baseException != null)
            {
                filterContext.Exception = baseException;
            }

            if (Depth < 2)
            {
                if (ApiTracking != null)
                {
                    DateTime exitStamp = DateTime.UtcNow;

                    // API EXCEPTION
                    if (baseException != null)
                    {
                        try
                        {
                            ApiTracking.LogException(baseException.ToExceptionInfo());
                        }
                        catch { }
                    }

                    // API EVENT
                    if (ApiEvent != null)
                    {
                        try
                        {
                            ApiEvent.ExitStamp = exitStamp;
                            ApiEvent.ExceptionKey = baseException?.Key;

                            ApiTracking.LogApiEvent(ApiEvent);
                        }
                        catch { }
                    }

                    // API TRACE
                    try
                    {
                        ApiTraceContext.Exit((ApiEvent?.ExceptionKey) ?? (baseException?.Key), exitStamp);
                        var traceLog = ApiTraceContext.GetCurrentTraceLog(true);

                        if (traceLog != null)
                        {
                            ApiTracking.LogApiTraceLog(traceLog);
                        }
                    }
                    catch { }
                }

                ThreadExtension.Clear();
            }

            Depth--;
        }

        /// <summary>
        /// Called by the ASP.NET MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);

            if (Depth < 1)
            {
                Depth = 0;

                DateTime entryStamp = DateTime.UtcNow;
                var request = filterContext.HttpContext.Request;

                var traceId = request.TryGetHeader(HttpConstants.HttpHeader.TRACEID);
                var traceSequence = request.TryGetHeader(HttpConstants.HttpHeader.TRACESEQUENCE).ObjectToNullableInt32();
                var methodInfo = (filterContext.ActionDescriptor as ReflectedActionDescriptor)?.MethodInfo;

                ContextHelper.ConsistContext(request, this.settings?.Name);

                if (!string.IsNullOrWhiteSpace(traceId))
                {
                    ApiTraceContext.Initialize(traceId, traceSequence, entryStamp);
                }

                if (settings != null && settings.TrackingEvent)
                {
                    var context = filterContext.HttpContext;
                    ApiEvent = new ApiEventLog
                    {
                        ApiFullName = methodInfo?.GetFullName(),
                        RawUrl = context.Request.RawUrl,
                        EntryStamp = entryStamp,
                        UserAgent = context.Request.UserAgent,
                        TraceId = traceId,
                        // If request came from ApiTransport or other proxy ways, ORIGINAL stands for the IP ADDRESS from original requester.
                        IpAddress = context.Request.TryGetHeader(settings?.OriginalIpAddressHeaderKey.SafeToString(HttpConstants.HttpHeader.ORIGINAL)).SafeToString(context.Request.UserHostAddress),
                        CultureCode = ContextHelper.ApiContext.CultureCode,
                        ContentLength = context.Request.ContentLength,
                        OperatorCredential = ContextHelper.CurrentCredential as BaseCredential,
                        Protocol = context.Request.Url.Scheme,
                        ReferrerUrl = context.Request.UrlReferrer?.ToString(),
                        ServerIdentifier = EnvironmentCore.ServerName,
                        ServiceIdentifier = EnvironmentCore.ProductName
                    };
                }

                var controllerType = methodInfo?.DeclaringType;

                var tokenRequiredAttribute = methodInfo?.GetCustomAttribute<TokenRequiredAttribute>(true) ?? controllerType?.GetCustomAttribute<TokenRequiredAttribute>(true);
                var permissionAttributes = controllerType?.GetCustomAttributes<ApiPermissionAttribute>(true).ToDictionary();
                permissionAttributes.Merge(methodInfo?.GetCustomAttributes<ApiPermissionAttribute>(true).ToDictionary(), true);

                var tokenRequired = tokenRequiredAttribute != null && tokenRequiredAttribute.TokenRequired;

                if (tokenRequired)
                {
                    if (!ContextHelper.IsUser)
                    {
                        var baseException = (new UnauthorizedTokenException(ContextHelper.Token)).Handle(
                       filterContext.HttpContext.Request.ToExceptionScene(filterContext.RouteData?.GetControllerName()), data: new { filterContext.HttpContext.Request.RawUrl });

                        HandleUnauthorizedAction(filterContext, baseException);
                    }
                    else if (permissionAttributes.HasItem())
                    {
                        var baseException = ContextHelper.CurrentUserInfo?.Permissions.ValidateApiPermission(permissionAttributes, ContextHelper.Token, methodInfo?.GetFullName());

                        if (baseException != null)
                        {
                            HandleUnauthorizedAction(filterContext, baseException);
                        }
                    }
                }

                ApiTraceContext.Enter(methodInfo.GetFullName(), setNameAsMajor: true);
            }

            Depth++;
        }

        /// <summary>
        /// Handles the unauthorized action.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        /// <param name="baseException">The base exception.</param>
        protected virtual void HandleUnauthorizedAction(ActionExecutingContext filterContext, BaseException baseException)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                ApiHandlerBase.PackageResponse(filterContext.HttpContext.Response, null, null, baseException, settings: settings);
                filterContext.Result = null;
            }
            else
            {
                filterContext.Result = new RedirectToRouteResult(routeValues: new RouteValueDictionary
                {
                    {"controller", "Error"},
                    {"action", "Index"},
                    {"code", 401},
                    {"minor", baseException.Code.Minor},
                    {"message", baseException.Message}
                });
            }
        }
    }
}


text:
<?php

namespace Hubzero\Content\Migration\Macros;

use Hubzero\Content\Migration\Macro;

/**
 * Migration macro to delete a template entry
 **/
class DeleteTemplateEntry extends Macro
{
	/**
	 * Remove template entires from the appropriate tables
	 *
	 * @param   string  $name    Template element name
	 * @param   int     $client  Client id
	 * @return  bool
	 **/
	public function __invoke($element, $client=1)
	{
		if ($this->db->tableExists('#__extensions'))
		{
			$query = $this->db->getQuery()
				->delete('#__extensions')
				->whereEquals('type', 'template')
				->whereEquals('element', $element)
				->whereEquals('client_id', $client)
				->toString();
			$this->db->setQuery($query);
			$this->db->query();

			$this->log(sprintf('Removed extension entry for template "%s"', $element));

			if ($this->db->tableExists('#__template_styles'))
			{
				$query = $this->db->getQuery()
					->delete('#__template_styles')
					->whereEquals('template', $element)
					->whereEquals('client_id', $client)
					->toString();
				$this->db->setQuery($query);
				$this->db->query();

				$this->log(sprintf('Removed style entry for template "%s"', $element));

				// Now make sure we have an enabled template (don't really care which one it is)
				$query = $this->db->getQuery()
					->select('id')
					->from('#__template_styles')
					->whereEquals('home', 1)
					->whereEquals('client_id', $client)
					->toString();
				$this->db->setQuery($query);
				if (!$this->db->loadResult())
				{
					$query = $this->db->getQuery()
						->select('id')
						->from('#__template_styles')
						->whereEquals('client_id', $client)
						->order('id', 'desc')
						->limit(1)
						->toString();
					$this->db->setQuery($query);
					if ($id = $this->db->loadResult())
					{
						$query = $this->db->getQuery()
							->update('#__template_styles')
							->set(array(
								'home' => 1
							))
							->whereEquals('id', $id)
							->toString();
						$this->db->setQuery($query);
						$this->db->query();

						$this->log(sprintf('Setting "home" for template style "%s"', $id));
					}
				}
			}

			return true;
		}

		return false;
	}
}


text:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
import { hasMany } from 'ember-data/relationships';
import { memberAction } from 'ember-api-actions';
import { filterBy } from '@ember/object/computed';

import Validator from './../mixins/model-validator';

// Constants
const STATUSES = ['draft', 'active', 'inactive'];

const SurveyTemplate = Model.extend(Validator, {
  // Attributes
  name: attr('string'),
  status: attr('string', { defaultValue: 'draft' }),
  surveyType: attr('string'),
  fullyEditable: attr('boolean'),
  duplicatorLabel: attr('string'),
  namePlusVersion: attr('string'),
  // Wildnote specific data
  lock: attr('boolean'),
  version: attr('string'),
  description: attr('string'),
  // Custom hack for Wildnote
  organizationId: attr('number'),
  surveyTemplateExportTypeId: attr('number'),

  // Relations
  questions: hasMany('question'),
  // Computed
  questionsNotNew: filterBy('questions', 'isNew', false),
  questionsNotDeleted: filterBy('questionsNotNew', 'isDeleted', false),
  filteredQuestions: filterBy('questionsNotDeleted', 'ancestryCollapsed', false),

  // Custom actions
  duplicate: memberAction({ path: 'duplicate', type: 'post' }),
  resortQuestions: memberAction({ path: 'resort_questions', type: 'patch' }),
  checkTemplate: memberAction({ path: 'check_template', type: 'get' }),

  // Validations
  validations: {
    name: {
      presence: true
    },
    status: {
      inclusion: {
        in: STATUSES
      }
    }
  }
});

SurveyTemplate.reopenClass({
  STATUSES
});

export default SurveyTemplate;


text:
from __future__ import (absolute_import, division, print_function)

__metaclass__ = type

DOCUMENTATION = '''
    name: openshift
    plugin_type: inventory
    author:
      - Chris Houseknecht <@chouseknecht>

    short_description: OpenShift inventory source

    description:
      - Fetch containers, services and routes for one or more clusters
      - Groups by cluster name, namespace, namespace_services, namespace_pods, namespace_routes, and labels
      - Uses openshift.(yml|yaml) YAML configuration file to set parameter values.

    options:
      plugin:
        description: token that ensures this is a source file for the 'openshift' plugin.
        required: True
        choices: ['openshift']
      connections:
          description:
          - Optional list of cluster connection settings. If no connections are provided, the default
            I(~/.kube/config) and active context will be used, and objects will be returned for all namespaces
            the active user is authorized to access.
          name:
              description:
              - Optional name to assign to the cluster. If not provided, a name is constructed from the server
                and port.
          kubeconfig:
              description:
              - Path to an existing Kubernetes config file. If not provided, and no other connection
                options are provided, the OpenShift client will attempt to load the default
                configuration file from I(~/.kube/config.json). Can also be specified via K8S_AUTH_KUBECONFIG
                environment variable.
          context:
              description:
              - The name of a context found in the config file. Can also be specified via K8S_AUTH_CONTEXT environment
                variable.
          host:
              description:
              - Provide a URL for accessing the API. Can also be specified via K8S_AUTH_HOST environment variable.
          api_key:
              description:
              - Token used to authenticate with the API. Can also be specified via K8S_AUTH_API_KEY environment
                variable.
          username:
              description:
              - Provide a username for authenticating with the API. Can also be specified via K8S_AUTH_USERNAME
                environment variable.
          password:
              description:
              - Provide a password for authenticating with the API. Can also be specified via K8S_AUTH_PASSWORD
                environment variable.
          client_cert:
              description:
              - Path to a certificate used to authenticate with the API. Can also be specified via K8S_AUTH_CERT_FILE
                environment variable.
              aliases: [ cert_file ]
          client_key:
              description:
              - Path to a key file used to authenticate with the API. Can also be specified via K8S_AUTH_KEY_FILE
                environment variable.
              aliases: [ key_file ]
          ca_cert:
              description:
              - Path to a CA certificate used to authenticate with the API. Can also be specified via
                K8S_AUTH_SSL_CA_CERT environment variable.
              aliases: [ ssl_ca_cert ]
          validate_certs:
              description:
              - "Whether or not to verify the API server's SSL certificates. Can also be specified via
                K8S_AUTH_VERIFY_SSL environment variable."
              type: bool
              aliases: [ verify_ssl ]
          namespaces:
              description:
              - List of namespaces. If not specified, will fetch all containers for all namespaces user is authorized
                to access.

    requirements:
    - "python >= 2.7"
    - "openshift >= 0.6"
    - "PyYAML >= 3.11"
'''

EXAMPLES = '''
# File must be named openshift.yaml or openshift.yml

# Authenticate with token, and return all pods and services for all namespaces
plugin: openshift
connections:
  - host: https://192.168.64.4:8443
    api_key: xxxxxxxxxxxxxxxx
    verify_ssl: false

# Use default config (~/.kube/config) file and active context, and return objects for a specific namespace
plugin: openshift
connections:
  - namespaces:
    - testing

# Use a custom config file, and a specific context.
plugin: openshift
connections:
  - kubeconfig: /path/to/config
    context: 'awx/192-168-64-4:8443/developer'
'''

from ansible.plugins.inventory.k8s import K8sInventoryException, InventoryModule as K8sInventoryModule, format_dynamic_api_exc

try:
    from openshift.dynamic.exceptions import DynamicApiError
except ImportError:
    pass

class InventoryModule(K8sInventoryModule):
    NAME = 'openshift'

    transport = 'oc'

    def fetch_objects(self, connections):
        super(InventoryModule, self).fetch_objects(connections)

        if connections:
            if not isinstance(connections, list):
                raise K8sInventoryException("Expecting connections to be a list.")

            for connection in connections:
                client = self.get_api_client(**connection)
                name = connection.get('name', self.get_default_host_name(client.configuration.host))
                if connection.get('namespaces'):
                    namespaces = connection['namespaces']
                else:
                    namespaces = self.get_available_namespaces(client)
                for namespace in namespaces:
                    self.get_routes_for_namespace(client, name, namespace)
        else:
            client = self.get_api_client()
            name = self.get_default_host_name(client.configuration.host)
            namespaces = self.get_available_namespaces(client)
            for namespace in namespaces:
                self.get_routes_for_namespace(client, name, namespace)

    def get_routes_for_namespace(self, client, name, namespace):
        v1_route = client.resources.get(api_version='v1', kind='Route')
        try:
            obj = v1_route.get(namespace=namespace)
        except DynamicApiError as exc:
            self.display.debug(exc)
            raise K8sInventoryException('Error fetching Routes list: %s' % format_dynamic_api_exc(exc))

        namespace_group = 'namespace_{0}'.format(namespace)
        namespace_routes_group = '{0}_routes'.format(namespace_group)

        self.inventory.add_group(name)
        self.inventory.add_group(namespace_group)
        self.inventory.add_child(name, namespace_group)
        self.inventory.add_group(namespace_routes_group)
        self.inventory.add_child(namespace_group, namespace_routes_group)
        for route in obj.items:
            route_name = route.metadata.name
            route_annotations = {} if not route.metadata.annotations else dict(route.metadata.annotations)

            self.inventory.add_host(route_name)

            if route.metadata.labels:
                # create a group for each label_value
                for key, value in route.metadata.labels:
                    group_name = 'label_{0}_{1}'.format(key, value)
                    self.inventory.add_group(group_name)
                    self.inventory.add_child(group_name, route_name)
                route_labels = dict(route.metadata.labels)
            else:
                route_labels = {}

            self.inventory.add_child(namespace_routes_group, route_name)

            # add hostvars
            self.inventory.set_variable(route_name, 'labels', route_labels)
            self.inventory.set_variable(route_name, 'annotations', route_annotations)
            self.inventory.set_variable(route_name, 'cluster_name', route.metadata.clusterName)
            self.inventory.set_variable(route_name, 'object_type', 'route')
            self.inventory.set_variable(route_name, 'self_link', route.metadata.selfLink)
            self.inventory.set_variable(route_name, 'resource_version', route.metadata.resourceVersion)
            self.inventory.set_variable(route_name, 'uid', route.metadata.uid)

            if route.spec.host:
                self.inventory.set_variable(route_name, 'host', route.spec.host)

            if route.spec.path:
                self.inventory.set_variable(route_name, 'path', route.spec.path)

            if hasattr(route.spec.port, 'targetPort') and route.spec.port.targetPort:
                self.inventory.set_variable(route_name, 'port', dict(route.spec.port))


text:
package org.apache.ambari.server.controller;

import static com.google.inject.matcher.Matchers.annotatedWith;
import static com.google.inject.matcher.Matchers.any;
import static org.eclipse.persistence.config.PersistenceUnitProperties.CREATE_JDBC_DDL_FILE;
import static org.eclipse.persistence.config.PersistenceUnitProperties.CREATE_ONLY;
import static org.eclipse.persistence.config.PersistenceUnitProperties.CREATE_OR_EXTEND;
import static org.eclipse.persistence.config.PersistenceUnitProperties.DDL_BOTH_GENERATION;
import static org.eclipse.persistence.config.PersistenceUnitProperties.DDL_GENERATION;
import static org.eclipse.persistence.config.PersistenceUnitProperties.DDL_GENERATION_MODE;
import static org.eclipse.persistence.config.PersistenceUnitProperties.DROP_AND_CREATE;
import static org.eclipse.persistence.config.PersistenceUnitProperties.DROP_JDBC_DDL_FILE;
import static org.eclipse.persistence.config.PersistenceUnitProperties.JDBC_DRIVER;
import static org.eclipse.persistence.config.PersistenceUnitProperties.JDBC_PASSWORD;
import static org.eclipse.persistence.config.PersistenceUnitProperties.JDBC_URL;
import static org.eclipse.persistence.config.PersistenceUnitProperties.JDBC_USER;
import static org.eclipse.persistence.config.PersistenceUnitProperties.NON_JTA_DATASOURCE;
import static org.eclipse.persistence.config.PersistenceUnitProperties.THROW_EXCEPTIONS;

import java.beans.PropertyVetoException;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.ambari.server.AmbariService;
import org.apache.ambari.server.EagerSingleton;
import org.apache.ambari.server.StaticallyInject;
import org.apache.ambari.server.actionmanager.ActionDBAccessor;
import org.apache.ambari.server.actionmanager.ActionDBAccessorImpl;
import org.apache.ambari.server.actionmanager.ExecutionCommandWrapperFactory;
import org.apache.ambari.server.actionmanager.HostRoleCommandFactory;
import org.apache.ambari.server.actionmanager.HostRoleCommandFactoryImpl;
import org.apache.ambari.server.actionmanager.RequestFactory;
import org.apache.ambari.server.actionmanager.StageFactory;
import org.apache.ambari.server.actionmanager.StageFactoryImpl;
import org.apache.ambari.server.checks.DatabaseConsistencyCheckHelper;
import org.apache.ambari.server.checks.UpgradeCheckRegistry;
import org.apache.ambari.server.checks.UpgradeCheckRegistryProvider;
import org.apache.ambari.server.cleanup.ClasspathScannerUtils;
import org.apache.ambari.server.configuration.AmbariServerConfiguration;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.configuration.Configuration.ConnectionPoolType;
import org.apache.ambari.server.configuration.Configuration.DatabaseType;
import org.apache.ambari.server.controller.internal.AlertTargetResourceProvider;
import org.apache.ambari.server.controller.internal.ClusterStackVersionResourceProvider;
import org.apache.ambari.server.controller.internal.ComponentResourceProvider;
import org.apache.ambari.server.controller.internal.CredentialResourceProvider;
import org.apache.ambari.server.controller.internal.HostComponentResourceProvider;
import org.apache.ambari.server.controller.internal.HostKerberosIdentityResourceProvider;
import org.apache.ambari.server.controller.internal.HostResourceProvider;
import org.apache.ambari.server.controller.internal.KerberosDescriptorResourceProvider;
import org.apache.ambari.server.controller.internal.MemberResourceProvider;
import org.apache.ambari.server.controller.internal.RepositoryVersionResourceProvider;
import org.apache.ambari.server.controller.internal.RootServiceComponentConfigurationResourceProvider;
import org.apache.ambari.server.controller.internal.ServiceResourceProvider;
import org.apache.ambari.server.controller.internal.UpgradeResourceProvider;
import org.apache.ambari.server.controller.internal.UserAuthenticationSourceResourceProvider;
import org.apache.ambari.server.controller.internal.UserResourceProvider;
import org.apache.ambari.server.controller.internal.ViewInstanceResourceProvider;
import org.apache.ambari.server.controller.logging.LoggingRequestHelperFactory;
import org.apache.ambari.server.controller.logging.LoggingRequestHelperFactoryImpl;
import org.apache.ambari.server.controller.metrics.MetricPropertyProviderFactory;
import org.apache.ambari.server.controller.metrics.timeline.cache.TimelineMetricCacheEntryFactory;
import org.apache.ambari.server.controller.metrics.timeline.cache.TimelineMetricCacheProvider;
import org.apache.ambari.server.controller.spi.ResourceProvider;
import org.apache.ambari.server.controller.utilities.KerberosChecker;
import org.apache.ambari.server.events.AgentConfigsUpdateEvent;
import org.apache.ambari.server.events.AmbariEvent;
import org.apache.ambari.server.hooks.AmbariEventFactory;
import org.apache.ambari.server.hooks.HookContext;
import org.apache.ambari.server.hooks.HookContextFactory;
import org.apache.ambari.server.hooks.HookService;
import org.apache.ambari.server.hooks.users.PostUserCreationHookContext;
import org.apache.ambari.server.hooks.users.UserCreatedEvent;
import org.apache.ambari.server.hooks.users.UserHookService;
import org.apache.ambari.server.metadata.CachedRoleCommandOrderProvider;
import org.apache.ambari.server.metadata.RoleCommandOrderProvider;
import org.apache.ambari.server.metrics.system.MetricsService;
import org.apache.ambari.server.metrics.system.impl.MetricsServiceImpl;
import org.apache.ambari.server.mpack.MpackManagerFactory;
import org.apache.ambari.server.notifications.DispatchFactory;
import org.apache.ambari.server.notifications.NotificationDispatcher;
import org.apache.ambari.server.notifications.dispatchers.AlertScriptDispatcher;
import org.apache.ambari.server.notifications.dispatchers.AmbariSNMPDispatcher;
import org.apache.ambari.server.notifications.dispatchers.SNMPDispatcher;
import org.apache.ambari.server.orm.DBAccessor;
import org.apache.ambari.server.orm.DBAccessorImpl;
import org.apache.ambari.server.orm.PersistenceType;
import org.apache.ambari.server.orm.dao.HostRoleCommandDAO;
import org.apache.ambari.server.scheduler.ExecutionScheduler;
import org.apache.ambari.server.scheduler.ExecutionSchedulerImpl;
import org.apache.ambari.server.security.SecurityHelper;
import org.apache.ambari.server.security.SecurityHelperImpl;
import org.apache.ambari.server.security.authorization.AuthorizationHelper;
import org.apache.ambari.server.security.authorization.internal.InternalAuthenticationInterceptor;
import org.apache.ambari.server.security.authorization.internal.RunWithInternalSecurityContext;
import org.apache.ambari.server.security.encryption.AESEncryptionService;
import org.apache.ambari.server.security.encryption.AgentConfigUpdateEncryptor;
import org.apache.ambari.server.security.encryption.AmbariServerConfigurationEncryptor;
import org.apache.ambari.server.security.encryption.ConfigPropertiesEncryptor;
import org.apache.ambari.server.security.encryption.CredentialStoreService;
import org.apache.ambari.server.security.encryption.CredentialStoreServiceImpl;
import org.apache.ambari.server.security.encryption.EncryptionService;
import org.apache.ambari.server.security.encryption.Encryptor;
import org.apache.ambari.server.serveraction.kerberos.KerberosOperationHandlerFactory;
import org.apache.ambari.server.serveraction.users.CollectionPersisterService;
import org.apache.ambari.server.serveraction.users.CollectionPersisterServiceFactory;
import org.apache.ambari.server.serveraction.users.CsvFilePersisterService;
import org.apache.ambari.server.stack.StackManagerFactory;
import org.apache.ambari.server.stack.upgrade.orchestrate.UpgradeContextFactory;
import org.apache.ambari.server.stageplanner.RoleGraphFactory;
import org.apache.ambari.server.state.Cluster;
import org.apache.ambari.server.state.Clusters;
import org.apache.ambari.server.state.Config;
import org.apache.ambari.server.state.ConfigFactory;
import org.apache.ambari.server.state.ConfigImpl;
import org.apache.ambari.server.state.Host;
import org.apache.ambari.server.state.Service;
import org.apache.ambari.server.state.ServiceComponent;
import org.apache.ambari.server.state.ServiceComponentFactory;
import org.apache.ambari.server.state.ServiceComponentHost;
import org.apache.ambari.server.state.ServiceComponentHostFactory;
import org.apache.ambari.server.state.ServiceComponentImpl;
import org.apache.ambari.server.state.ServiceFactory;
import org.apache.ambari.server.state.ServiceImpl;
import org.apache.ambari.server.state.cluster.ClusterFactory;
import org.apache.ambari.server.state.cluster.ClusterImpl;
import org.apache.ambari.server.state.cluster.ClustersImpl;
import org.apache.ambari.server.state.configgroup.ConfigGroup;
import org.apache.ambari.server.state.configgroup.ConfigGroupFactory;
import org.apache.ambari.server.state.configgroup.ConfigGroupImpl;
import org.apache.ambari.server.state.host.HostFactory;
import org.apache.ambari.server.state.host.HostImpl;
import org.apache.ambari.server.state.kerberos.KerberosDescriptorFactory;
import org.apache.ambari.server.state.kerberos.KerberosServiceDescriptorFactory;
import org.apache.ambari.server.state.scheduler.RequestExecution;
import org.apache.ambari.server.state.scheduler.RequestExecutionFactory;
import org.apache.ambari.server.state.scheduler.RequestExecutionImpl;
import org.apache.ambari.server.state.stack.OsFamily;
import org.apache.ambari.server.state.svccomphost.ServiceComponentHostImpl;
import org.apache.ambari.server.topology.BlueprintFactory;
import org.apache.ambari.server.topology.PersistedState;
import org.apache.ambari.server.topology.PersistedStateImpl;
import org.apache.ambari.server.topology.SecurityConfigurationFactory;
import org.apache.ambari.server.topology.tasks.ConfigureClusterTaskFactory;
import org.apache.ambari.server.utils.PasswordUtils;
import org.apache.ambari.server.view.ViewInstanceHandlerList;
import org.eclipse.jetty.server.session.SessionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.util.ClassUtils;
import org.springframework.web.filter.DelegatingFilterProxy;

import com.google.common.reflect.ClassPath;
import com.google.common.util.concurrent.ServiceManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.inject.AbstractModule;
import com.google.inject.Scopes;
import com.google.inject.Singleton;
import com.google.inject.TypeLiteral;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import com.google.inject.name.Names;
import com.google.inject.persist.PersistModule;
import com.google.inject.persist.jpa.AmbariJpaPersistModule;
import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * Used for injection purposes.
 */
public class ControllerModule extends AbstractModule {
  private static final Logger LOG = LoggerFactory.getLogger(ControllerModule.class);
  private static final String AMBARI_PACKAGE = "org.apache.ambari.server";

  private final Configuration configuration;
  private final OsFamily os_family;
  private final HostsMap hostsMap;
  private boolean dbInitNeeded;
  private final Gson prettyGson = new GsonBuilder().serializeNulls().setPrettyPrinting().create();

  // ----- Constructors ------------------------------------------------------

  public ControllerModule() throws Exception {
    configuration = new Configuration();
    hostsMap = new HostsMap(configuration);
    os_family = new OsFamily(configuration);
  }

  public ControllerModule(Properties properties) throws Exception {
    configuration = new Configuration(properties);
    hostsMap = new HostsMap(configuration);
    os_family = new OsFamily(configuration);
  }

  // ----- ControllerModule --------------------------------------------------

  /**
   * Get the common persistence related configuration properties.
   *
   * @return the configuration properties
   */
  public static Properties getPersistenceProperties(Configuration configuration) {
    Properties properties = new Properties();

    // log what database type has been calculated
    DatabaseType databaseType = configuration.getDatabaseType();
    LOG.info("Detected {} as the database type from the JDBC URL", databaseType);

    switch (configuration.getPersistenceType()) {
      case IN_MEMORY:
        properties.setProperty(JDBC_URL, Configuration.JDBC_IN_MEMORY_URL);
        properties.setProperty(JDBC_DRIVER, Configuration.JDBC_IN_MEMORY_DRIVER);
        properties.setProperty(JDBC_USER, Configuration.JDBC_IN_MEMORY_USER);
        properties.setProperty(JDBC_PASSWORD, Configuration.JDBC_IN_MEMORY_PASSWORD);
        properties.setProperty(DDL_GENERATION, CREATE_ONLY);
        properties.setProperty(THROW_EXCEPTIONS, "true");
        break;
      case REMOTE:
        properties.setProperty(JDBC_URL, configuration.getDatabaseUrl());
        properties.setProperty(JDBC_DRIVER, configuration.getDatabaseDriver());
        break;
      case LOCAL:
        properties.setProperty(JDBC_URL, configuration.getLocalDatabaseUrl());
        properties.setProperty(JDBC_DRIVER, Configuration.SERVER_JDBC_DRIVER.getDefaultValue());
        break;
    }

    //allow to override values above
    // custom jdbc driver properties
    Properties customDatabaseDriverProperties = configuration.getDatabaseCustomProperties();
    properties.putAll(customDatabaseDriverProperties);

    // custom persistence properties
    Properties customPersistenceProperties = configuration.getPersistenceCustomProperties();
    properties.putAll(customPersistenceProperties);

    // determine the type of pool to use
    boolean isConnectionPoolingExternal = false;
    ConnectionPoolType connectionPoolType = configuration.getConnectionPoolType();
    if (connectionPoolType == ConnectionPoolType.C3P0) {
      isConnectionPoolingExternal = true;
    }

    // force the use of c3p0 with MySQL
    if (databaseType == DatabaseType.MYSQL) {
      isConnectionPoolingExternal = true;
    }

    // use c3p0
    if (isConnectionPoolingExternal) {
      LOG.info("Using c3p0 {} as the EclipsLink DataSource",
          ComboPooledDataSource.class.getSimpleName());

      // Oracle requires a different validity query
      String testQuery = "SELECT 1";
      if (databaseType == DatabaseType.ORACLE) {
        testQuery = "SELECT 1 FROM DUAL";
      }

      ComboPooledDataSource dataSource = new ComboPooledDataSource();

      // attempt to load the driver; if this fails, warn and move on
      try {
        dataSource.setDriverClass(configuration.getDatabaseDriver());
      } catch (PropertyVetoException pve) {
        LOG.warn("Unable to initialize c3p0", pve);
        return properties;
      }

      // basic configuration stuff
      dataSource.setJdbcUrl(configuration.getDatabaseUrl());
      dataSource.setUser(configuration.getDatabaseUser());
      dataSource.setPassword(configuration.getDatabasePassword());

      // pooling
      dataSource.setMinPoolSize(configuration.getConnectionPoolMinimumSize());
      dataSource.setInitialPoolSize(configuration.getConnectionPoolMinimumSize());
      dataSource.setMaxPoolSize(configuration.getConnectionPoolMaximumSize());
      dataSource.setAcquireIncrement(configuration.getConnectionPoolAcquisitionSize());
      dataSource.setAcquireRetryAttempts(configuration.getConnectionPoolAcquisitionRetryAttempts());
      dataSource.setAcquireRetryDelay(configuration.getConnectionPoolAcquisitionRetryDelay());

      // validity
      dataSource.setMaxConnectionAge(configuration.getConnectionPoolMaximumAge());
      dataSource.setMaxIdleTime(configuration.getConnectionPoolMaximumIdle());
      dataSource.setMaxIdleTimeExcessConnections(configuration.getConnectionPoolMaximumExcessIdle());
      dataSource.setPreferredTestQuery(testQuery);
      dataSource.setIdleConnectionTestPeriod(configuration.getConnectionPoolIdleTestInternval());

      properties.put(NON_JTA_DATASOURCE, dataSource);
    }

    return properties;
  }

  // ----- AbstractModule ----------------------------------------------------

  @Override
  protected void configure() {
    installFactories();

    final SessionHandler sessionHandler = new SessionHandler();
    bind(SessionHandler.class).toInstance(sessionHandler);

    bind(KerberosOperationHandlerFactory.class);
    bind(KerberosDescriptorFactory.class);
    bind(KerberosServiceDescriptorFactory.class);
    bind(KerberosHelper.class).to(KerberosHelperImpl.class);

    bind(CredentialStoreService.class).to(CredentialStoreServiceImpl.class);
    bind(EncryptionService.class).to(AESEncryptionService.class);
    //to support different Encryptor implementation we have to annotate them by their name and use them as @Named injects
    if (configuration.shouldEncryptSensitiveData()) {
      bind(new TypeLiteral<Encryptor<Config>>() {}).annotatedWith(Names.named("ConfigPropertiesEncryptor")).to(ConfigPropertiesEncryptor.class);
      bind(new TypeLiteral<Encryptor<AgentConfigsUpdateEvent>>() {}).annotatedWith(Names.named("AgentConfigEncryptor")).to(AgentConfigUpdateEncryptor.class);
      bind(new TypeLiteral<Encryptor<AmbariServerConfiguration>>() {}).annotatedWith(Names.named("AmbariServerConfigurationEncryptor")).to(AmbariServerConfigurationEncryptor.class);
    } else {
      bind(new TypeLiteral<Encryptor<Config>>() {}).annotatedWith(Names.named("ConfigPropertiesEncryptor")).toInstance(Encryptor.NONE);
      bind(new TypeLiteral<Encryptor<AgentConfigsUpdateEvent>>() {}).annotatedWith(Names.named("AgentConfigEncryptor")).toInstance(Encryptor.NONE);
      bind(new TypeLiteral<Encryptor<AmbariServerConfiguration>>() {}).annotatedWith(Names.named("AmbariServerConfigurationEncryptor")).toInstance(Encryptor.NONE);
    }

    bind(Configuration.class).toInstance(configuration);
    bind(OsFamily.class).toInstance(os_family);
    bind(HostsMap.class).toInstance(hostsMap);
    bind(PasswordEncoder.class).toInstance(new StandardPasswordEncoder());
    bind(DelegatingFilterProxy.class).toInstance(new DelegatingFilterProxy() {
      {
        setTargetBeanName("springSecurityFilterChain");
      }
    });

    bind(Gson.class).annotatedWith(Names.named("prettyGson")).toInstance(prettyGson);

    install(buildJpaPersistModule());

    bind(Gson.class).in(Scopes.SINGLETON);
    bind(SecureRandom.class).in(Scopes.SINGLETON);

    bind(Clusters.class).to(ClustersImpl.class);
    bind(AmbariCustomCommandExecutionHelper.class);
    bind(ActionDBAccessor.class).to(ActionDBAccessorImpl.class);
    bindConstant().annotatedWith(Names.named("schedulerSleeptime")).to(
        configuration.getExecutionSchedulerWait());

    // This time is added to summary timeout time of all tasks in stage
    // So it's an "additional time", given to stage to finish execution before
    // it is considered as timed out
    bindConstant().annotatedWith(Names.named("actionTimeout")).to(600000L);
    bindConstant().annotatedWith(Names.named("alertServiceCorePoolSize")).to(configuration.getAlertServiceCorePoolSize());

    bindConstant().annotatedWith(Names.named("dbInitNeeded")).to(dbInitNeeded);
    bindConstant().annotatedWith(Names.named("statusCheckInterval")).to(5000L);

    //ExecutionCommands cache size

    bindConstant().annotatedWith(Names.named("executionCommandCacheSize")).
        to(configuration.getExecutionCommandsCacheSize());

    // Host role commands status summary max cache enable/disable
    bindConstant().annotatedWith(Names.named(HostRoleCommandDAO.HRC_STATUS_SUMMARY_CACHE_ENABLED)).
        to(configuration.getHostRoleCommandStatusSummaryCacheEnabled());

    // Host role commands status summary max cache size
    bindConstant().annotatedWith(Names.named(HostRoleCommandDAO.HRC_STATUS_SUMMARY_CACHE_SIZE)).
        to(configuration.getHostRoleCommandStatusSummaryCacheSize());
    // Host role command status summary cache expiry duration in minutes
    bindConstant().annotatedWith(Names.named(HostRoleCommandDAO.HRC_STATUS_SUMMARY_CACHE_EXPIRY_DURATION_MINUTES)).
        to(configuration.getHostRoleCommandStatusSummaryCacheExpiryDuration());

    bind(AmbariManagementController.class).to(
        AmbariManagementControllerImpl.class);
    bind(AbstractRootServiceResponseFactory.class).to(RootServiceResponseFactory.class);
    bind(ExecutionScheduler.class).to(ExecutionSchedulerImpl.class);
    bind(DBAccessor.class).to(DBAccessorImpl.class);
    bind(ViewInstanceHandlerList.class).to(AmbariHandlerList.class);
    bind(TimelineMetricCacheProvider.class);
    bind(TimelineMetricCacheEntryFactory.class);
    bind(SecurityConfigurationFactory.class).in(Scopes.SINGLETON);

    bind(PersistedState.class).to(PersistedStateImpl.class);

    // factory to create LoggingRequestHelper instances for LogSearch integration
    bind(LoggingRequestHelperFactory.class).to(LoggingRequestHelperFactoryImpl.class);

    bind(MetricsService.class).to(MetricsServiceImpl.class).in(Scopes.SINGLETON);

    requestStaticInjection(DatabaseConsistencyCheckHelper.class);
    requestStaticInjection(KerberosChecker.class);
    requestStaticInjection(AuthorizationHelper.class);
    requestStaticInjection(PasswordUtils.class);

    bindByAnnotation(null);
    bindNotificationDispatchers(null);

    bind(UpgradeCheckRegistry.class).toProvider(UpgradeCheckRegistryProvider.class).in(Singleton.class);
    bind(HookService.class).to(UserHookService.class);

    InternalAuthenticationInterceptor ambariAuthenticationInterceptor = new InternalAuthenticationInterceptor();
    requestInjection(ambariAuthenticationInterceptor);
    bindInterceptor(any(), annotatedWith(RunWithInternalSecurityContext.class), ambariAuthenticationInterceptor);
  }

  // ----- helper methods ----------------------------------------------------

  private PersistModule buildJpaPersistModule() {
    PersistenceType persistenceType = configuration.getPersistenceType();
    AmbariJpaPersistModule jpaPersistModule = new AmbariJpaPersistModule(Configuration.JDBC_UNIT_NAME);

    Properties persistenceProperties = ControllerModule.getPersistenceProperties(configuration);

    if (!persistenceType.equals(PersistenceType.IN_MEMORY)) {
      persistenceProperties.setProperty(JDBC_USER, configuration.getDatabaseUser());
      persistenceProperties.setProperty(JDBC_PASSWORD, configuration.getDatabasePassword());

      switch (configuration.getJPATableGenerationStrategy()) {
        case CREATE:
          persistenceProperties.setProperty(DDL_GENERATION, CREATE_ONLY);
          dbInitNeeded = true;
          break;
        case DROP_AND_CREATE:
          persistenceProperties.setProperty(DDL_GENERATION, DROP_AND_CREATE);
          dbInitNeeded = true;
          break;
        case CREATE_OR_EXTEND:
          persistenceProperties.setProperty(DDL_GENERATION, CREATE_OR_EXTEND);
          break;
        default:
          break;
      }

      persistenceProperties.setProperty(DDL_GENERATION_MODE, DDL_BOTH_GENERATION);
      persistenceProperties.setProperty(CREATE_JDBC_DDL_FILE, "DDL-create.jdbc");
      persistenceProperties.setProperty(DROP_JDBC_DDL_FILE, "DDL-drop.jdbc");
    }

    jpaPersistModule.properties(persistenceProperties);
    return jpaPersistModule;
  }

  /**
   * Bind classes to their Factories, which can be built on-the-fly.
   * Often, will also have to edit AgentResourceTest.java
   */
  private void installFactories() {
    install(new FactoryModuleBuilder().implement(
        Cluster.class, ClusterImpl.class).build(ClusterFactory.class));
    install(new FactoryModuleBuilder().implement(
        Host.class, HostImpl.class).build(HostFactory.class));
    install(new FactoryModuleBuilder().implement(
        Service.class, ServiceImpl.class).build(ServiceFactory.class));

    install(new FactoryModuleBuilder()
        .implement(ResourceProvider.class, Names.named("host"), HostResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("hostComponent"), HostComponentResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("service"), ServiceResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("component"), ComponentResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("member"), MemberResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("repositoryVersion"), RepositoryVersionResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("hostKerberosIdentity"), HostKerberosIdentityResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("user"), UserResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("userAuthenticationSource"), UserAuthenticationSourceResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("credential"), CredentialResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("kerberosDescriptor"), KerberosDescriptorResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("upgrade"), UpgradeResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("clusterStackVersion"), ClusterStackVersionResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("alertTarget"), AlertTargetResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("viewInstance"), ViewInstanceResourceProvider.class)
        .implement(ResourceProvider.class, Names.named("rootServiceHostComponentConfiguration"), RootServiceComponentConfigurationResourceProvider.class)
        .build(ResourceProviderFactory.class));

    install(new FactoryModuleBuilder().implement(
      ServiceComponent.class, ServiceComponentImpl.class).build(
      ServiceComponentFactory.class));
    install(new FactoryModuleBuilder().implement(
        ServiceComponentHost.class, ServiceComponentHostImpl.class).build(
        ServiceComponentHostFactory.class));
    install(new FactoryModuleBuilder().implement(
        Config.class, ConfigImpl.class).build(ConfigFactory.class));
    install(new FactoryModuleBuilder().implement(
        ConfigGroup.class, ConfigGroupImpl.class).build(ConfigGroupFactory.class));
    install(new FactoryModuleBuilder().implement(RequestExecution.class,
        RequestExecutionImpl.class).build(RequestExecutionFactory.class));

    bind(StageFactory.class).to(StageFactoryImpl.class);
    bind(RoleCommandOrderProvider.class).to(CachedRoleCommandOrderProvider.class);

    install(new FactoryModuleBuilder().build(RoleGraphFactory.class));

    install(new FactoryModuleBuilder().build(RequestFactory.class));
    install(new FactoryModuleBuilder().build(StackManagerFactory.class));
    install(new FactoryModuleBuilder().build(ExecutionCommandWrapperFactory.class));
    install(new FactoryModuleBuilder().build(MetricPropertyProviderFactory.class));
    install(new FactoryModuleBuilder().build(UpgradeContextFactory.class));
    install(new FactoryModuleBuilder().build(MpackManagerFactory.class));
    install(new FactoryModuleBuilder().build(org.apache.ambari.server.topology.addservice.RequestValidatorFactory.class));

    bind(HostRoleCommandFactory.class).to(HostRoleCommandFactoryImpl.class);
    bind(SecurityHelper.class).toInstance(SecurityHelperImpl.getInstance());
    bind(org.apache.ambari.server.topology.StackFactory.class).to(org.apache.ambari.server.topology.DefaultStackFactory.class);
    bind(BlueprintFactory.class);

    install(new FactoryModuleBuilder().implement(AmbariEvent.class, Names.named("userCreated"), UserCreatedEvent.class).build(AmbariEventFactory.class));
    install(new FactoryModuleBuilder().implement(HookContext.class, PostUserCreationHookContext.class).build(HookContextFactory.class));
    install(new FactoryModuleBuilder().implement(CollectionPersisterService.class, CsvFilePersisterService.class).build(CollectionPersisterServiceFactory.class));

    install(new FactoryModuleBuilder().build(ConfigureClusterTaskFactory.class));

  }

  /**
   * Initializes specially-marked interfaces that require injection.
   * <p/>
   * An example of where this is needed is with a singleton that is headless; in
   * other words, it doesn't have any injections but still needs to be part of
   * the Guice framework.
   * <p/>
   * A second example of where this is needed is when classes require static
   * members that are available via injection.
   * <p/>
   * Although Spring has a nicer API for performing this search, it's dreadfully
   * slow on annotation processing. This class will use
   * {@link ClasspathScannerUtils} which in turn uses {@link ClassPath} to
   * perform the scan.
   * <p/>
   * If {@code matchedClasses} is null this will scan
   * {@code org.apache.ambari.server} (currently) for any {@link EagerSingleton}
   * or {@link StaticallyInject} or {@link AmbariService} instances.
   *
   * @param matchedClasses
   *          the set of previously found classes, or {@code null} to invoke
   *          scanning.
   * @return the set of classes that was found.
   */
  @SuppressWarnings("unchecked")
  protected Set<Class<?>> bindByAnnotation(Set<Class<?>> matchedClasses) {
    // only search if necessary
    if (null == matchedClasses) {
      List<Class<?>> classes = new ArrayList<>();
      classes.add(EagerSingleton.class);
      classes.add(StaticallyInject.class);
      classes.add(AmbariService.class);

      LOG.info("Searching package {} for annotations matching {}", AMBARI_PACKAGE, classes);

      matchedClasses = ClasspathScannerUtils.findOnClassPath(AMBARI_PACKAGE, new ArrayList<>(), classes);

      if (null == matchedClasses || matchedClasses.size() == 0) {
        LOG.warn("No instances of {} found to register", classes);
        return matchedClasses;
      }
    }

    Set<com.google.common.util.concurrent.Service> services = new HashSet<>();

    for (Class<?> clazz : matchedClasses) {
      if (null != clazz.getAnnotation(EagerSingleton.class)) {
        bind(clazz).asEagerSingleton();
        LOG.debug("Eagerly binding singleton {}", clazz);
      }

      if (null != clazz.getAnnotation(StaticallyInject.class)) {
        requestStaticInjection(clazz);
        LOG.debug("Statically injecting {} ", clazz);
      }

      // Ambari services are registered with Guava
      if (null != clazz.getAnnotation(AmbariService.class)) {
        // safety check to ensure it's actually a Guava service
        if (!com.google.common.util.concurrent.Service.class.isAssignableFrom(clazz)) {
          String message = MessageFormat.format(
              "Unable to register service {0} because it is not a Service which can be scheduled",
              clazz);

          LOG.error(message);
          throw new RuntimeException(message);
        }

        // instantiate the service, register as singleton via toInstance()
        com.google.common.util.concurrent.Service service = null;
        try {
          service = (com.google.common.util.concurrent.Service) clazz.newInstance();
          bind((Class<com.google.common.util.concurrent.Service>) clazz).toInstance(service);
          services.add(service);
          LOG.info("Registering service {} ", clazz);
        } catch (Exception exception) {
          LOG.error("Unable to register {} as a service", clazz, exception);
          throw new RuntimeException(exception);
        }
      }
    }

    ServiceManager manager = new ServiceManager(services);
    bind(ServiceManager.class).toInstance(manager);

    return matchedClasses;
  }

  /**
   * Searches for all instances of {@link NotificationDispatcher} on the
   * classpath and registers each as a singleton with the
   * {@link DispatchFactory}.
   */
  @SuppressWarnings("unchecked")
  protected Set<BeanDefinition> bindNotificationDispatchers(Set<BeanDefinition> beanDefinitions) {

    // make the factory a singleton
    DispatchFactory dispatchFactory = DispatchFactory.getInstance();
    bind(DispatchFactory.class).toInstance(dispatchFactory);

    if (null == beanDefinitions || beanDefinitions.isEmpty()) {
      String packageName = AlertScriptDispatcher.class.getPackage().getName();
      LOG.info("Searching package {} for dispatchers matching {}", packageName,
          NotificationDispatcher.class);

      ClassPathScanningCandidateComponentProvider scanner =
          new ClassPathScanningCandidateComponentProvider(false);

      // match all implementations of the dispatcher interface
      AssignableTypeFilter filter = new AssignableTypeFilter(
          NotificationDispatcher.class);

      scanner.addIncludeFilter(filter);

      beanDefinitions = scanner.findCandidateComponents(packageName);
    }

    // no dispatchers is a problem
    if (null == beanDefinitions || beanDefinitions.size() == 0) {
      LOG.error("No instances of {} found to register", NotificationDispatcher.class);
      return null;
    }

    // for every discovered dispatcher, singleton-ize them and register with
    // the dispatch factory
    for (BeanDefinition beanDefinition : beanDefinitions) {
      String className = beanDefinition.getBeanClassName();
      if (className != null) {
        Class<?> clazz = ClassUtils.resolveClassName(className,
                ClassUtils.getDefaultClassLoader());
        try {
          NotificationDispatcher dispatcher;
          if (clazz.equals(AmbariSNMPDispatcher.class)) {
            dispatcher = (NotificationDispatcher) clazz.getConstructor(Integer.class)
                    .newInstance(configuration.getAmbariSNMPUdpBindPort());
          } else if (clazz.equals(SNMPDispatcher.class)) {
            dispatcher = (NotificationDispatcher) clazz.getConstructor(Integer.class)
                    .newInstance(configuration.getSNMPUdpBindPort());
          } else {
            dispatcher = (NotificationDispatcher) clazz.newInstance();
          }
          dispatchFactory.register(dispatcher.getType(), dispatcher);
          bind((Class<NotificationDispatcher>) clazz).toInstance(dispatcher);
          LOG.info("Binding and registering notification dispatcher {}", clazz);
        } catch (Exception exception) {
          LOG.error("Unable to bind and register notification dispatcher {}",
                  clazz, exception);
        }
      } else {
        LOG.error("Binding and registering notification dispatcher is not possible for" +
            " beanDefinition: {} in the absence of className", beanDefinition);
      }
    }

    return beanDefinitions;
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Skydaz | Minecraft Installers, Tools, Mods, Maps & Textures</title>
<meta name="description" content="Minecraft Installers, Tools, Mods, Maps & Textures" />

<link rel="pingback" href="https://www.skydaz.com/xmlrpc.php" />

<link rel="shortcut icon" href="https://www.skydaz.com/favicon.ico" />

<meta name="viewport" content="width=1000" />

<link rel='dns-prefetch' href='//ajax.googleapis.com' />
<link rel='dns-prefetch' href='//cdnjs.cloudflare.com' />
<link rel='dns-prefetch' href='//s.w.org' />
<link rel="alternate" type="application/rss+xml" title="Skydaz » Feed" href="https://www.skydaz.com/feed/" />
<link rel="alternate" type="application/rss+xml" title="Skydaz » Comments Feed" href="https://www.skydaz.com/comments/feed/" />
<link rel='stylesheet' id='tab-shortcode-css'  href='https://www.skydaz.com/wp-content/plugins/tabs-shortcode/tab.min.css?ver=4.8' type='text/css' media='all' />
<link rel='stylesheet' id='arras-layout-css'  href='https://www.skydaz.com/wp-content/themes/arras/css/layouts/2c-r-fixed.css?ver=2015-19-10' type='text/css' media='all' />
<link rel='stylesheet' id='arras-css'  href='https://www.skydaz.com/wp-content/themes/arras/css/styles/default.css?ver=2015-19-10' type='text/css' media='all' />
<link rel='stylesheet' id='arras-user-css'  href='https://www.skydaz.com/wp-content/themes/arras/user.css?ver=2015-19-10' type='text/css' media='all' />

<link rel='https://api.w.org/' href='https://www.skydaz.com/wp-json/' />

Skydaz

Minecraft Installers, Tools, Mods, Maps & Textures

	<form method="get" class="searchform clearfix" action="https://www.skydaz.com/">
	<input type="text" value="Search for mods, maps..." name="s" class="s" onfocus="if ( this.value == 'Search for mods, maps...' ) this.value = ''" onblur="if ( this.value == '' ) this.value = 'Search for mods, maps...'" />
	<input type="submit" class="searchsubmit" value="Search" title="Search Skydaz" />
</form>

Home

Skydaz Installers

1.12 Installers

1.11.2 Installers

1.11 Installers

1.10.2 Installers

1.9.4 Installers

1.9 Installers

1.8.9 Installers

1.8 Installers

1.7.10 Installers

1.7.2 Installers

1.6.4 Installers

Older Versions

1.6.2 Installers

Forge

ModLoader

ModLoader & Forge

1.5.2 Installers

Forge

ModLoader & Forge

ModLoader

1.7.5 Installers

1.7.4 Installers

1.5.1 Installers

Forge

ModLoader

ModLoader & Forge

1.4.7 Installers

Forge

ModLoader

ModLoader & Forge

1.4.6 Installers

Forge

ModLoader

1.4.5 Installers

Forge

ModLoader

ModLoader & Forge

1.4.2 Installers

1.3.2 Installers

1.3.1 Installers

1.2.5 Installers

Maps

Adventure

Survival

Mini-Game

Horror

Textures

Modpacks

1.6.4

Tools

Support

FAQ

Fixing Minecraft

Windows 8 Compatibility

Contact

Terms

Privacy

RSS Feed

Facebook

Twitter

YouTube

			Prev
			Next

				<img width="640" height="300" src="https://www.skydaz.com/wp-content/uploads/2016/10/baby-animals-mod-installer-minecraft.jpg" class="attachment-featured-slideshow-thumb size-featured-slideshow-thumb wp-post-image" alt="The Baby Animals mod replaces the vanilla baby models. Model Swapper does not have any of the functionality of the […]" title="Baby Animals Mod Installer for Minecraft 1.12" srcset="https://www.skydaz.com/wp-content/uploads/2016/10/baby-animals-mod-installer-minecraft.jpg 640w, https://www.skydaz.com/wp-content/uploads/2016/10/baby-animals-mod-installer-minecraft-300x141.jpg 300w" sizes="(max-width: 640px) 100vw, 640px" />

					Baby Animals Mod Installer for Minecraft 1.12

The Baby Animals mod replaces the vanilla baby models. Model Swapper does not have any of the functionality of the […]

				<img width="640" height="300" src="https://www.skydaz.com/wp-content/uploads/2016/03/chameleon-creepers-mod-installer-minecraft.jpg" class="attachment-featured-slideshow-thumb size-featured-slideshow-thumb wp-post-image" alt="The Chameleon Creepers mod adds in a little bit of fun by making the creepers change colors depending on their […]" title="Chameleon Creepers Mod Installer for Minecraft 1.12" srcset="https://www.skydaz.com/wp-content/uploads/2016/03/chameleon-creepers-mod-installer-minecraft.jpg 640w, https://www.skydaz.com/wp-content/uploads/2016/03/chameleon-creepers-mod-installer-minecraft-300x141.jpg 300w" sizes="(max-width: 640px) 100vw, 640px" />

					Chameleon Creepers Mod Installer for Minecraft 1.12

The Chameleon Creepers mod adds in a little bit of fun by making the creepers change colors depending on their […]

				<img width="640" height="300" src="https://www.skydaz.com/wp-content/uploads/2015/12/Enhanced-Visuals-Mod-installer-minecraft.png" class="attachment-featured-slideshow-thumb size-featured-slideshow-thumb wp-post-image" alt="The Enhanced Visuals a mod that aims to add several visual effects based on what is happening to your player, […]" title="Enhanced Visuals Mod Installer for Minecraft 1.11.2" srcset="https://www.skydaz.com/wp-content/uploads/2015/12/Enhanced-Visuals-Mod-installer-minecraft.png 640w, https://www.skydaz.com/wp-content/uploads/2015/12/Enhanced-Visuals-Mod-installer-minecraft-300x141.png 300w" sizes="(max-width: 640px) 100vw, 640px" />

					Enhanced Visuals Mod Installer for Minecraft 1.11.2

The Enhanced Visuals a mod that aims to add several visual effects based on what is happening to your player, […]

				<img width="640" height="300" src="https://www.skydaz.com/wp-content/uploads/2014/01/floocraft-mod-installer-minecraft-mods-craft.jpg" class="attachment-featured-slideshow-thumb size-featured-slideshow-thumb wp-post-image" alt="Fans of Harry Potter will know that Floo Powder is a special powder that, when thrown into a fire, turns […]" title="Floocraft Mod Installer for Minecraft 1.11.2" srcset="https://www.skydaz.com/wp-content/uploads/2014/01/floocraft-mod-installer-minecraft-mods-craft.jpg 640w, https://www.skydaz.com/wp-content/uploads/2014/01/floocraft-mod-installer-minecraft-mods-craft-300x140.jpg 300w" sizes="(max-width: 640px) 100vw, 640px" />

					Floocraft Mod Installer for Minecraft 1.11.2

Fans of Harry Potter will know that Floo Powder is a special powder that, when thrown into a fire, turns […]

Featured Installers

6May 31, 2017

Painted Biomes Mod Installer for Minecraft 1.7.10

The Painted Biomes mod allows you to use images to control how biomes are generated in your world. This mod […]

3May 31, 2017

FuturePack Mod Installer for Minecraft 1.11.2

The FuturePack mod brings you a futuristic environment, research and space travel, and new dimensions. It also allows you to […]

6May 30, 2017

Headcrumbs Mod Installer for Minecraft 1.10.2

The Headcrumbs mod is an awesome simple mod that adds wearable mob heads for you to wear! From Natura mobs […]

1May 30, 2017

DiseaseCraft Mod Installer for Minecraft 1.10.2

DiseaseCraft 2 is a complete rewrite of my original DiseaseCraft mod. This mod adds new diseases that alter the player’s […]

9May 24, 2017

Club Penguin Mod Installer for Minecraft 1.11.2

The Club Penguin mod is based after the famous Club Penguin online game! This mod adds the lovely penguins, cute […]

2May 22, 2017

Water Works Mod Installer for Minecraft 1.11.2

Waterworks is a mod for Minecraft that adds several water collecting mechanics. This mod is developed by Terpo, all credits to […]

9May 22, 2017

ToroQuest Mod Installer for Minecraft 1.11.2

The Toroquest is an adventure and RPG mod. This exciting mod adds civilizations, dungeons and new mobs among other interesting […]

4May 18, 2017

Coffee Spawner Mod Installer for Minecraft 1.11.2

Coffee Spawner adds a coffee machine to minecraft which spawns a drinkable coffee every morning! Whether you mined all night […]

7May 15, 2017

NuclearCraft Mod Installer for Minecraft 1.11.2

NuclearCraft is a fun mod that brings nuclear physics to your Minecraft world. It adds cool items such as a […]

6May 15, 2017

Immersive Craft Mod Installer for Minecraft 1.11.2

The Immersive Craft mod brings to Minecraft a three-dimensional feel to handling, crafting, and storing items. The mod is a […]

7May 15, 2017

Headcrumbs Mod Installer for Minecraft 1.11.2

The Headcrumbs mod is an awesome simple mod that adds wearable mob heads for you to wear! From Natura mobs […]

14May 12, 2017

Personal Cars Mod Installer for Minecraft 1.11.2

The Personal cars mod adds in vehicles that come with keys which means only the owner is able to open […]

Latest Installers for Minecraft

				1.11.2 Installers

Mowzies Mobs Mod Installer for Minecraft 1.11.2

			4 Comments

				1.10.2 Installers

Trail Mix Mod Installer for Minecraft 1.10.2

			1 Comment

				1.11.2 Installers

Cannibalism Mod Installer for Minecraft 1.11.2

			6 Comments

				1.10.2 Installers

Primitive Mobs Mod Installer for Minecraft 1.10.2

			4 Comments

				1.7.10 Installers

Spawner Craft Mod Installer for Minecraft 1.7.10

			11 Comments

				1.11.2 Installers

Ender Zoo Mod Installer for Minecraft 1.11.2

			4 Comments

				1.10.2 Installers

Advanced Chimneys Mod Installer for Minecraft 1.10.2

			5 Comments

				1.11.2 Installers

NeoTech Mod Installer for Minecraft 1.11.2

			4 Comments

				1.11.2 Installers

Pet Buddy Mod Installer for Minecraft 1.11.2

			11 Comments

				1.11.2 Installers

Decocraft Mod Installer for Minecraft 1.11.2

			16 Comments

Older Entries

    <form action="//www.skydaz.com/search-results/" id="cse-search-box">

        <input type="hidden" name="cx" value="partner-pub-9898963553052987:4683460165" />
        <input type="hidden" name="cof" value="FORID:10" />
        <input type="hidden" name="ie" value="UTF-8" />
        <input type="text" name="q" size="55" />
        <input type="submit" name="sa" value="Advanced Search" />

    </form>

    Custom Search

Skydaz | Terms of Use | Privacy Policy

Copyright Skydaz. All Rights Reserved. All creations copyright of the creators.
Minecraft is copyright Mojang AB and is not affiliated with this site.