text:
import Router       from "./core/router";
import Debug        from "./core/debug";
import res          from "./core/response";
import DB           from "./db/db";
import Store        from "./db/store";
import middlewares  from "./core/middlewares";
import innocent     from "./innocent/innocent";

class employee {

    constructor() {
        this.middlewares = [];
        this.render      = innocent;

        this.settings = {
            "version":      "1.0",
            "name":         "cache",
            "view engine":  "innocent",
            "timeout":      5000
        };

        this.attachEvents();
    }

    attachEvents() {
        self.addEventListener('install',  this.handleInstall.bind(this));
        self.addEventListener('activate', this.handleActivate.bind(this));
        self.addEventListener('fetch',    this.handleFetch.bind(this));
    }

    use(callback) {
        this.middlewares.push(callback);
    }

    set(key, value) {
        switch(key) {
            case "static":
                this.setStaticBehavior(value);
                break;

            case "views":
                if(!value.startsWith("/")) value = "/" + value;
                break;

            case "view engine":
                if(value != this.settings["view engine"]) this.render = self[value] || this.render;
                break;

            default:
                break;
        }

        this.settings[key] = value;
    }

    get(key) {
        return this.settings[key];
    }

    cacheName() {
        return this.get("version") + "::" + this.get("name");
    }

    server() {
        console.log(this);
    }

    setStaticBehavior(behavior) {
        employee.Router.get(/\.(js|css|png|jpg|jpeg|gif|webm|webp|svg|map|html|xml|json|ico|woff|woff2|eot|ttf|otf|pdf)/, behavior);
    }

    handleInstall(event) {
        event.waitUntil(
            caches
                .open(this.cacheName())
                .then((cache) => cache.addAll(this.get("cache")))
        );
    }

    handleActivate(event) {
        event.waitUntil(
            caches
                .keys()
                .then((keys) => {
                    return Promise.all(
                        keys
                            .filter(key => !key.startsWith(this.get("version")))
                            .map(key => caches.delete(key))
                    );
                })
                .then(function() {
                    console.log('WORKER: activate completed.');
                })
        );
    }

    handleFetch(event) {
        //base64 data
        if(event && event.request.url.startsWith("data:")) return;

        let request     = event.request.clone();
        let response    = new res(this, event);

        request.settings = this.settings;

        let stack = [];

        //Render when forced or when the user is offline
        if(this.get('force render') || !navigator.onLine) {
            stack = this.middlewares.concat(Router.match(request));
        }
        else {
            stack = [middlewares.NetworkFirst];
        }

        let index = 0;

        while(index < stack.length) {
            if(typeof stack[index] == "function") stack[index](request, response);
            index++;
        }
    }

}

employee.DB     = DB;
employee.Store  = Store;
employee.Router = Router;

for(var name in middlewares) employee[name] = middlewares[name];

self.employee   = employee;


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:cache="http://www.springframework.org/schema/cache"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
	http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.1.xsd">

	<description>Shiro安全配置</description>
    <!-- 支持Shiro对Controller的方法级AOP安全控制 -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>

    <!--
    <!– 会话验证调度器 –>
    <bean id="sessionValidationScheduler"
          class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
        <!–检测时间间距,默认是60分钟–>
        <property name="interval" value="${session.validate.timespan}"/>
        <property name="sessionManager" ref="sessionManager"/>
    </bean>

    <!– 会话Cookie模板 –>
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <!–cookie的name –>
        <constructor-arg value="v_v-s-gmy"/>
        <property name="httpOnly" value="true"/>
        <!–cookie的有效时间 –>
        <property name="maxAge" value="-1"/>
        <!– 配置存储Session Cookie的domain为 一级域名 –>
        <property name="domain" value=".guanmaoyun.com"/>
    </bean>

    <!– 会话ID生成器 –>
    <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/>

    <!– 会话DAO –>
    <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/>
        <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
    </bean>

    <!– Session Manager –>
    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!– 相隔多久检查一次session的有效性   –>
        <property name="sessionValidationInterval" value="1800000"/>
        <!– session 有效时间为半小时 (毫秒单位)–>
        <property name="globalSessionTimeout" value="1800000"/>
        <property name="sessionDAO" ref="sessionDAO"/>
        <!– session 监听,可以多个。 –>
        <!–
        <property name="sessionListeners">
            <list>
                <ref bean="customSessionListener"/>
            </list>
        </property>
        –>
        <!– 间隔多少时间检查,不配置是60分钟 –>
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
        <!– 是否开启 检测,默认开启 –>
        <property name="sessionValidationSchedulerEnabled" value="true"/>
        <!– 是否删除无效的,默认也是开启 –>
        <property name="deleteInvalidSessions" value="true"/>
        <!– 会话Cookie模板 –>
        <property name="sessionIdCookie" ref="sessionIdCookie"/>
    </bean>
    -->

    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">/unauthorized</prop>
            </props>
        </property>
    </bean>

    <!-- Shiro's main business-tier object for web-enabled applications  depends-on="userDao,groupDao" -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="sessionManager" ref="sessionManager" />
		<!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
		<property name="realm" ref="shiroDbRealm" />
		<property name="cacheManager" ref="shiroEhCacheManager" />
		<!--
		<property name="rememberMeManager.cookie.name" value="rememberMe"/>
    	<property name="rememberMeManager.cookie.maxAge" value="3*60"/>
    	-->
    </bean>

	<!-- 自定义的Realm -->
	<!-- Define the realm you want to use to connect to your back-end security datasource: -->
	<bean id="shiroDbRealm" class="net.cloudkit.enterprises.infrastructure.shiro.ShiroDbRealm">
		<!-- 用来实现用户名密码等相关验证数据的查询 -->
		<!-- <property name="accountManager" ref="accountManager" /> -->
		<!-- <property name="adminService" ref="adminServiceImpl" /> -->
		<!-- MD5加密 -->
		<!--
		<property name="credentialsMatcher">
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
			    <property name="hashAlgorithmName" value="MD5" />
			</bean>
		</property>
		-->
	</bean>

    <!--
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager"/>
        <!– 设定角色的登录链接,这里为cas登录页面的链接可配置回调地址  –>
        <property name="loginUrl" value="https://www.cas.com/login?service=http://www.example.com/shiro-cas"/>

        <property name="filters">
            <map>
                <!– 添加casFilter到shiroFilter –>
                <entry key="casFilter" value-ref="casFilter"/>
            </map>
        </property>
        <property name="filterChainDefinitions">
            <value>
                /shiro-cas = casFilter
                /admin/** = roles[ROLE_USER]
                /** = anon
            </value>
        </property>
    </bean>

    <bean id="casFilter" class="org.apache.shiro.cas.CasFilter">
        <!– 配置验证错误时的失败页面  –>
        <property name="failureUrl" value="/error.jsp"/>
    </bean>

    <bean id="casRealm" class="org.apache.shiro.cas.CasRealm">
        <property name="defaultRoles" value="ROLE_USER"/>
        <property name="casServerUrlPrefix" value="https://www.cas.com"/>
        <!– 客户端的回调地址设置,必须和下面的shiro-cas过滤器拦截的地址一致 –>
        <property name="casService" value="http://www.example.com/shiro-cas"/>
    </bean>
    <!– 如果要实现cas的remember me的功能,需要用到下面这个bean,并设置到securityManager的subjectFactory中 –>
    <bean id="casSubjectFactory" class="org.apache.shiro.cas.CasSubjectFactory"/>

    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="casRealm"/>
        <property name="subjectFactory" ref="casSubjectFactory"/>
    </bean>
    -->

    <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
		<property name="globalSessionTimeout" value="6000000"/>
		<property name="sessionDAO" ref="shiroRedisSessionDAO"/>
		<property name="sessionValidationScheduler" ref="sessionValidationScheduler"/>
		<property name="sessionValidationSchedulerEnabled" value="true"/>
		<property name="sessionIdCookie" ref="simpleCookie"/>
	</bean>
	<!--自定义session存储容器-->
	<bean id="shiroRedisSessionDAO" class="net.cloudkit.enterprises.infrastructure.shiro.ShiroRedisSessionDAO" />
	<!--
	定时清理僵尸session,Shiro会启用一个后台守护线程定时执行清理操作
	用户直接关闭浏览器造成的孤立会话
	-->
	<bean id="sessionValidationScheduler"
		  class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
		<property name="interval" value="6000000"/>
		<property name="sessionManager" ref="sessionManager"/>
	</bean>
	<!--
	指定本系统SESSIONID, 默认为: JSESSIONID
	问题: 与SERVLET容器名冲突, 如JETTY, TOMCAT 等默认JSESSIONID,
	当跳出SHIRO SERVLET时如ERROR-PAGE容器会为JSESSIONID重新分配值导致登录会话丢失!
	-->
	<bean id="simpleCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
		<constructor-arg name="name" value="WEB_SESSIONID"/>
	</bean>

	<!-- 用于单点登录的Realm -->
	<!--
	<bean id="shiroCasRealm" class="net.cloudkit.legendfire.interfaces.common.common.ShiroCasRealm" depends-on="userDao">
		<property name="accountService" ref="accountService"/>
		<property name="cacheManager" ref="shiroCacheManager"/>
	</bean>
	-->

	<!-- For simplest integration, so that all SecurityUtils.* methods work in all cases, -->
	<!-- make the securityManager bean a static singleton.  DO NOT do this in web         -->
	<!-- applications - see the 'Web Applications' section below instead.                 -->
	<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
	    <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager"/>
	    <property name="arguments" ref="securityManager"/>
	</bean>

	<!-- Shiro Filter -->
	<!--
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        # shiro 的核心安全接口
	    <property name="securityManager" ref="securityManager" />
	    # 要求登录时的链接
	    <property name="loginUrl" value="/login.jsp" />
	    # 登陆成功后要跳转的连接
	    <property name="successUrl" value="/index.jsp" />
	    # 未授权时要跳转的连接
	    <property name="unauthorizedUrl" value="/unauthorized.jsp" />
        # shiro 连接约束配置
        <property name="filterChainDefinitions">
            <value>
            	# some example chain definitions:
	            /admin/** = authc, roles[admin]
	            /docs/** = authc, perms[document:read]
	            /** = authc
	            # more URL-to-FilterChain definitions here

                /rollindex = anon
                /index.html = anon
                /login = authc
                /logout = logout
                /resources/** = anon
                /admin/** = user
                /account/** = user
            </value>
        </property>
    </bean>
    -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- shiro的核心安全接口 -->
	    <property name="securityManager" ref="securityManager" />
	    <!-- 要求登录时的链接 -->
	    <!-- override these for application-specific URLs if you like: -->
	    <!--<property name="loginUrl" value="/login" />-->
	    <property name="loginUrl" value="/signin" />
	    <!-- 登陆成功后要跳转的连接 -->
	    <property name="successUrl" value="/workbench" />
	    <!-- 未授权时要跳转的连接 -->
	    <property name="unauthorizedUrl" value="/unauthorized" />
	    <!-- shiro 连接约束配置 -->
	    <!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean  -->
	    <!-- defined will be automatically acquired and available via its beanName in chain        -->
	    <!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
	    <property name="filters">
	        <map>
	        	<entry key="authc" value-ref="formAuthenticationFilter"></entry>
                <entry key="perms" value-ref="permissionsAuthorizationExpandFilter"></entry>
				<!-- <entry key="cas" value-ref="casFilter"></entry> -->
	            <!-- <entry key="anAlias" value-ref="someFilter"/> -->
	        </map>
	    </property>

	    <!-- shiro连接约束配置,在这里使用自定义的动态获取资源类 -->
	    <property name="filterChainDefinitionMap" ref="chainDefinitionSectionMetaSource" />
	</bean>

	<!-- 基于表单认证过滤器 formAuthenticationFilter -->
	<bean id="formAuthenticationFilter" class="net.cloudkit.enterprises.infrastructure.shiro.FormAuthenticationExpandFilter"/>
    <bean id="permissionsAuthorizationExpandFilter" class="net.cloudkit.enterprises.infrastructure.shiro.PermissionsAuthorizationExpandFilter"/>

	<!--
		anon 表示匿名访问(不需要认证与授权)
		authc 表示需要认证
		/** = user
		perms[user:view] 表示用户需要提供值为"user:view"Permission 信息
		authc 和  perms[*] 表示为受保护资源
	-->
	<bean id="chainDefinitionSectionMetaSource"  class="net.cloudkit.enterprises.infrastructure.shiro.ChainDefinitionSectionMetaSource">
        <!--
        anon org.apache.shiro.web.filter.authc.AnonymousFilter
        authc org.apache.shiro.web.filter.authc.FormAuthenticationFilter
        authcBasic org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
        logout org.apache.shiro.web.filter.authc.LogoutFilter
        noSessionCreation org.apache.shiro.web.filter.session.NoSessionCreationFilter
        perms org.apache.shiro.web.filter.authz.PermissionAuthorizationFilter
        port org.apache.shiro.web.filter.authz.PortFilter
        rest org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
        roles org.apache.shiro.web.filter.authz.RolesAuthorizationFilter
        ssl org.apache.shiro.web.filter.authz.SslFilter
        user org.apache.shiro.web.filter.authz.UserFilter
        -->
        <!--
        anon,authc,authcBasic,user是第一组认证过滤器
        perms,port,rest,roles,ssl是第二组授权过滤器
        注意user和authc不同:当应用开启了rememberMe时,用户下次访问时可以是一个user,但绝不会是authc,因为authc是需要重新认证的
        user表示用户不一定已通过认证,只要曾被Shiro记住过登录状态的用户就可以正常发起请求,比如rememberMe
        以前的一个用户登录时开启了rememberMe,然后他关闭浏览器,下次再访问时他就是一个user,而不会authc

        /admin=authc,roles[admin] 表示用户必需已通过认证,并拥有admin角色才可以正常发起'/admin'请求
        /edit=authc,perms[admin:edit] 表示用户必需已通过认证,并拥有admin:edit权限才可以正常发起'/edit'请求
        /home=user 表示用户不一定需要已经通过认证,只需要曾经被Shiro记住过登录状态就可以正常发起'/home'请求

        /admins/**=anon 无参,表示可匿名使用,可以理解为匿名用户或游客
        /admins/user/**=authc 无参,表示需认证才能使用
        /admins/user/**=authcBasic 表示httpBasic认证
        /admins/user/**=user 无参,表示必须存在用户,当登入操作时不做检查
        /admins/user/**=ssl 无参,表示安全的URL请求,协议为https
        /admins/user/**=perms[user:add:*] 参数可写多个,多参时必须加上引号,且参数之间用逗号分割,如/admins/user/**=perms["user:add:*,user:modify:*"] 当有多个参数时必须每个参数都通过才算通过,相当于isPermitedAll()方法
		/admins/user/**=port[8081] 当请求的URL端口不是8081时,跳转到schemal://serverName:8081?queryString 其中schmal是协议http或https等,serverName是你访问的Host,8081是Port端口,queryString是你访问的URL里的?后面的参数
        /admins/user/**=rest[user] 根据请求的方法,相当于/admins/user/**=perms[user:method],其中method为post,get,delete等
        /admins/user/**=roles[admin] 参数可写多个,多个时必须加上引号,且参数之间用逗号分割,如/admins/user/**=roles["admin,guest"] 当有多个参数时必须每个参数都通过才算通过,相当于hasAllRoles()方法

        #/setting/** authc
        #/unauthorized/ = anon
        #/assets/** = anon
        # 权限配置示例
        #/security/account/view=authc,perms[SECURITY_ACCOUNT_VIEW]
        #/docs/** = authc, perms[document:read]
        #/user/user_list = perms["user:view"]
        #/user/user_** = perms["user:edit"]
        #/admin/** = roles[admin]
        -->
        <property name="filterChainDefinitions" >
			<value>
                #/login = authc
				/signin = authc
                /logout = logout
                #/workbench = authc

                /resources/** = anon

                /u/** authc
                /user/** authc

                /admin/** = authc, roles[admin]
                /** = anon
			</value>
		</property>
	</bean>

	<!-- shiro对ehcache的缓存管理直接使用spring的缓存工厂 -->
	<bean id="shiroEhCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
	    <property name="cacheManager" ref="ehCacheManagerFactory" />
	</bean>

	<!-- 用户授权信息Cache, 采用EhCache -->
	<!-- <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" /> -->
	<!--
	<bean id="shiroEhCacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		# <property name="cacheManagerConfigFile" value="classpath:ehcache-default.xml"/>
		<property name="cacheManager" ref="ehCacheManager" />
	</bean>
	-->

	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>

	<!-- AOP式方法级权限检查  -->
 	<!-- Enable Shiro Annotations for Spring-configured beans.  Only run after -->
	<!-- the lifecycleBeanProcessor has run: -->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
		<property name="proxyTargetClass" value="true" />
	</bean>
	<!-- 启用Shiro注解 例如,@RequiresRoles,@RequiresPermissions 等等 -->
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
	    <property name="securityManager" ref="securityManager"/>
	</bean>

</beans>

redpajama_set_name: RedPajamaGithub


text:
import logging
import sys
if (sys.version_info > (3,)):
  from urllib.parse import quote
else:
  from urllib import quote
import jsonpickle
from cairis.core.Attacker import Attacker
from cairis.tools.JsonConverter import json_deserialize
from cairis.core.AttackerEnvironmentProperties import AttackerEnvironmentProperties
from cairis.test.CairisDaemonTestCase import CairisDaemonTestCase
import os
from cairis.mio.ModelImport import importModelFile

__author__ = 'Robin Quetin, Shamal Faily'

class AttackerAPITests(CairisDaemonTestCase):

  @classmethod
  def setUpClass(cls):
    importModelFile(os.environ['CAIRIS_SRC'] + '/../examples/exemplars/NeuroGrid/NeuroGrid.xml',1,'test')

  def setUp(self):
    # region Class fields
    self.logger = logging.getLogger(__name__)
    self.existing_attacker_name = 'Mallory'
    self.existing_environment_name_1 = 'Stroke'
    self.existing_environment_name_2 = 'Psychosis'
    self.existing_motive_names = ['Hactivism', 'Money']
    self.existing_role_names = ['Hacker', 'Developer']
    self.existing_capabilities = [
      {
        'name':'Resources/Equipment',
        'value': 'Low'
      },
      {
        'name': 'Knowledge/Methods',
        'value': 'High'
      }
    ]
    attacker_class = Attacker.__module__+'.'+Attacker.__name__
    # endregion

  def test_get_all(self):
    method = 'test_get_all'
    rv = self.app.get('/api/attackers?session_id=test')
    if (sys.version_info > (3,)):
      attackers = jsonpickle.decode(rv.data.decode('utf-8'))
    else:
      attackers = jsonpickle.decode(rv.data)
    self.assertIsNotNone(attackers, 'No results after deserialization')
    self.assertIsInstance(attackers, dict, 'The result is not a dictionary as expected')
    self.assertGreater(len(attackers), 0, 'No attackers in the dictionary')
    self.logger.info('[%s] Attackers found: %d', method, len(attackers))
    attacker = list(attackers.values())[0]
    self.logger.info('[%s] First attacker: %s\n', method, attacker['theName'])

  def test_get_all_summary(self):
    method = 'test_get_all_summary'
    rv = self.app.get('/api/attackers/summary?session_id=test')
    if (sys.version_info > (3,)):
      ats = json_deserialize(rv.data.decode('utf-8'))
    else:
      ats = json_deserialize(rv.data)
    self.assertIsNotNone(ats, 'No results after deserialization')
    self.assertGreater(len(ats), 0, 'No attacker summaries')
    self.assertIsInstance(ats[0], dict)
    self.logger.info('[%s] Attackers found: %d', method, len(ats))
    self.logger.info('[%s] First attacker summary: %s [%s]\n', method, ats[0]['theName'])

  def test_get_by_name(self):
    method = 'test_get_by_name'
    url = '/api/attackers/name/%s?session_id=test' % quote(self.existing_attacker_name)
    rv = self.app.get(url)
    self.assertIsNotNone(rv.data, 'No response')
    self.logger.debug('[%s] Response data: %s', method, rv.data)
    if (sys.version_info > (3,)):
      attacker = jsonpickle.decode(rv.data.decode('utf-8'))
    else:
      attacker = jsonpickle.decode(rv.data)
    self.assertIsNotNone(attacker, 'No results after deserialization')
    self.logger.info('[%s] Attacker: %s\n', method, attacker['theName'])

  def test_delete(self):
    method = 'test_delete'
    url = '/api/attackers/name/%s?session_id=test' % quote(self.prepare_new_attacker().theName)
    new_attacker_body = self.prepare_json()

    self.app.delete(url)
    self.logger.info('[%s] Object to delete: %s', method, new_attacker_body)
    self.app.post('/api/attackers', content_type='application/json', data=new_attacker_body)
    self.logger.info('[%s] URL: %s', method, url)
    rv = self.app.delete(url)
    if (sys.version_info > (3,)):
      responseData = rv.data.decode('utf-8')
    else:
      responseData = rv.data
    self.logger.info('[%s] Response data: %s', method, responseData)
    self.assertIsNotNone(responseData, 'No response')
    json_resp = jsonpickle.decode(responseData)
    self.assertIsInstance(json_resp, dict, 'The response cannot be converted to a dictionary')
    message = json_resp.get('message', None)
    self.assertIsNotNone(message, 'No message in response')
    self.logger.info('[%s] Message: %s\n', method, message)

  def test_post(self):
    method = 'test_post'
    url = '/api/attackers'
    self.logger.info('[%s] URL: %s', method, url)
    new_attacker_body = self.prepare_json()

    self.app.delete('/api/attackers/name/%s?session_id=test' % quote(self.prepare_new_attacker().theName))
    rv = self.app.post(url, content_type='application/json', data=new_attacker_body)
    if (sys.version_info > (3,)):
      responseData = rv.data.decode('utf-8')
    else:
      responseData = rv.data
    self.logger.debug('[%s] Response data: %s', method, responseData)
    json_resp = jsonpickle.decode(responseData)
    self.assertIsNotNone(json_resp, 'No results after deserialization')

    rv = self.app.delete('/api/attackers/name/%s?session_id=test' % quote(self.prepare_new_attacker().theName))

  def test_put(self):
    method = 'test_put'
    url = '/api/attackers'
    self.logger.info('[%s] URL: %s', method, url)
    new_attacker_body = self.prepare_json()

    rv = self.app.delete('/api/attackers/name/%s?session_id=test' % quote(self.prepare_new_attacker().theName))
    rv = self.app.post(url, content_type='application/json', data=new_attacker_body)
    if (sys.version_info > (3,)):
      responseData = rv.data.decode('utf-8')
    else:
      responseData = rv.data
    self.logger.debug('[%s] Response data: %s', method, responseData)
    json_resp = jsonpickle.decode(responseData)
    self.assertIsNotNone(json_resp, 'No results after deserialization')

    attacker_to_update = self.prepare_new_attacker()
    attacker_to_update.theName = 'Edited test attacker'
    attacker_to_update.theId = -1
    upd_env_body = self.prepare_json(attacker=attacker_to_update)
    rv = self.app.put('/api/attackers/name/%s?session_id=test' % quote(self.prepare_new_attacker().theName), data=upd_env_body, content_type='application/json')
    if (sys.version_info > (3,)):
      responseData = rv.data.decode('utf-8')
    else:
      responseData = rv.data
    self.assertIsNotNone(responseData, 'No response')
    json_resp = jsonpickle.decode(responseData)
    self.assertIsNotNone(json_resp)
    self.assertIsInstance(json_resp, dict)
    message = json_resp.get('message', None)
    self.assertIsNotNone(message, 'No message in response')
    self.logger.info('[%s] Message: %s', method, message)
    self.assertGreater(message.find('successfully updated'), -1, 'The attacker was not successfully updated')

    rv = self.app.get('/api/attackers/name/%s?session_id=test' % quote(attacker_to_update.theName))
    if (sys.version_info > (3,)):
      responseData = rv.data.decode('utf-8')
    else:
      responseData = rv.data
    upd_attacker = jsonpickle.decode(responseData)
    self.assertIsNotNone(upd_attacker, 'Unable to decode JSON data')
    self.logger.debug('[%s] Response data: %s', method, responseData)
    self.logger.info('[%s] Attacker: %s\n', method, upd_attacker['theName'])

    rv = self.app.delete('/api/attackers/name/%s?session_id=test' % quote(attacker_to_update.theName))

  def prepare_new_attacker(self):
    new_attacker_props = [
      AttackerEnvironmentProperties(
        environmentName=self.existing_environment_name_1,
        roles=self.existing_role_names,
        motives=self.existing_motive_names,
        capabilities=self.existing_capabilities
      ),
      AttackerEnvironmentProperties(
        environmentName=self.existing_environment_name_2,
        roles=self.existing_role_names,
        motives=self.existing_motive_names,
        capabilities=self.existing_capabilities
      )
    ]

    new_attacker = Attacker(
      attackerId=-1,
      attackerName='Test attacker',
      attackerDescription='This is a test attacker',
      attackerImage='',
      tags=['test', 'test123'],
      environmentProperties=[]
    )
    new_attacker.theEnvironmentProperties = new_attacker_props

    new_attacker.theEnvironmentDictionary = {}
    new_attacker.theAttackerPropertyDictionary = {}

    delattr(new_attacker, 'theEnvironmentDictionary')
    delattr(new_attacker, 'theAttackerPropertyDictionary')

    return new_attacker

  def prepare_dict(self, attacker=None):
    if attacker is None:
      attacker = self.prepare_new_attacker()
    else:
      assert isinstance(attacker, Attacker)

    return {
      'session_id': 'test',
      'object': attacker,
    }

  def prepare_json(self, data_dict=None, attacker=None):
    if data_dict is None:
      data_dict = self.prepare_dict(attacker=attacker)
    else:
      assert isinstance(data_dict, dict)
    new_attacker_body = jsonpickle.encode(data_dict, unpicklable=False)
    self.logger.info('JSON data: %s', new_attacker_body)
    return new_attacker_body


text:
package com.snowplowanalytics.snowplow.tracker.emitter;

import com.snowplowanalytics.snowplow.tracker.payload.SelfDescribingJson;
import com.snowplowanalytics.snowplow.tracker.payload.TrackerPayload;
import com.snowplowanalytics.snowplow.tracker.http.HttpClientAdapter;
import org.junit.Assert;
import org.junit.Test;

public class BatchEmitterBuilderTest {

    @Test
    public void setNeitherHttpClientAdapterOrCollectorUrl_shouldThrowException() {
        Exception exception = Assert.assertThrows(Exception.class, () -> BatchEmitter.builder().build());
        Assert.assertEquals("Collector url must be specified if not using a httpClientAdapter", exception.getMessage());
    }

    @Test
    public void setCollectorUrlAndNoHttpClientAdapter_shouldInitialiseCorrectly() {
        BatchEmitter emitter = BatchEmitter.builder().url("https://mycollector.com").build();
        Assert.assertNotNull(emitter);
    }

    @Test
    public void setHttpClientAdapterAndNoCollectorUrl_shouldInitialiseCorrectly() {
        HttpClientAdapter mockHttpClientAdapter = new HttpClientAdapter() {
            @Override
            public int post(SelfDescribingJson payload) {
                return 0;
            }

            @Override
            public int get(TrackerPayload payload) {
                return 0;
            }

            @Override
            public String getUrl() {
                return null;
            }

            @Override
            public Object getHttpClient() {
                return null;
            }
        };

        BatchEmitter emitter = BatchEmitter.builder().httpClientAdapter(mockHttpClientAdapter).build();
        Assert.assertNotNull(emitter);
    }
}


text:
package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/google/gapid/core/app"
	"github.com/google/gapid/core/log"
	"github.com/google/gapid/gapis/service"
	"github.com/google/gapid/gapis/stringtable"
)

type reportVerb struct{ ReportFlags }

func init() {
	verb := &reportVerb{
		ReportFlags: ReportFlags{
			CommandFilterFlags: CommandFilterFlags{
				Context: -1,
			},
		},
	}
	app.AddVerb(&app.Verb{
		Name:      "report",
		ShortHelp: "Check a capture replays without issues",
		Action:    verb,
	})
}

func (verb *reportVerb) Run(ctx context.Context, flags flag.FlagSet) error {
	if flags.NArg() != 1 {
		app.Usage(ctx, "Exactly one gfx trace file expected, got %d", flags.NArg())
		return nil
	}

	capture, err := filepath.Abs(flags.Arg(0))
	if err != nil {
		log.Errf(ctx, err, "Could not find capture file: %v", flags.Arg(0))
	}

	client, err := getGapis(ctx, verb.Gapis, verb.Gapir)
	if err != nil {
		return log.Err(ctx, err, "Failed to connect to the GAPIS server")
	}
	defer client.Close()

	stringTables, err := client.GetAvailableStringTables(ctx)
	if err != nil {
		return log.Err(ctx, err, "Failed get list of string tables")
	}

	var stringTable *stringtable.StringTable
	if len(stringTables) > 0 {
		// TODO: Let the user pick the string table.
		stringTable, err = client.GetStringTable(ctx, stringTables[0])
		if err != nil {
			return log.Err(ctx, err, "Failed get string table")
		}
	}

	capturePath, err := client.LoadCapture(ctx, capture)
	if err != nil {
		return log.Err(ctx, err, "Failed to load the capture file")
	}

	device, err := getDevice(ctx, client, capturePath, verb.Gapir)
	if err != nil {
		return err
	}

	filter, err := verb.commandFilter(ctx, client, capturePath)
	if err != nil {
		return log.Err(ctx, err, "Failed to build the CommandFilter")
	}

	boxedCommands, err := client.Get(ctx, capturePath.Commands().Path())
	if err != nil {
		return log.Err(ctx, err, "Failed to acquire the capture's atoms")
	}
	commands := boxedCommands.(*service.Commands).List

	boxedReport, err := client.Get(ctx, capturePath.Report(device, filter).Path())
	if err != nil {
		return log.Err(ctx, err, "Failed to acquire the capture's report")
	}

	var reportWriter io.Writer = os.Stdout
	if verb.Out != "" {
		f, err := os.OpenFile(verb.Out, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
		if err != nil {
			return log.Err(ctx, err, "Failed to open report output file")
		}
		defer f.Close()
		reportWriter = f
	}

	report := boxedReport.(*service.Report)
	for _, e := range report.Items {
		where := ""
		if e.Command != nil {
			where = fmt.Sprintf("%v %v ", e.Command.Indices, commands[e.Command.Indices[0]]) // TODO: Subcommands
		}
		msg := report.Msg(e.Message).Text(stringTable)
		fmt.Fprintln(reportWriter, fmt.Sprintf("[%s] %s%s", e.Severity.String(), where, msg))
	}

	if len(report.Items) == 0 {
		fmt.Fprintln(reportWriter, "No issues found")
	} else {
		fmt.Fprintf(reportWriter, "%d issues found\n", len(report.Items))
	}

	return nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
  <bill>
    <relatedBills />
    <latestAction>
      <actionDate>2017-04-26</actionDate>
      <links />
      <text>Referred to the House Committee on Oversight and Government Reform.</text>
    </latestAction>
    <introducedDate>2017-04-26</introducedDate>
    <committeeReports />
    <cosponsors />
    <calendarNumbers />
    <subjects>
      <billSubjects>
        <policyArea>
          <name>Government Operations and Politics</name>
        </policyArea>
        <legislativeSubjects>
          <item>
            <name>Appropriations</name>
          </item>
          <item>
            <name>Budget process</name>
          </item>
          <item>
            <name>Public contracts and procurement</name>
          </item>
          <item>
            <name>Wages and earnings</name>
          </item>
        </legislativeSubjects>
      </billSubjects>
    </subjects>
    <sponsors>
      <item>
        <firstName>ELEANOR</firstName>
        <lastName>NORTON</lastName>
        <identifiers>
          <lisID>868</lisID>
          <bioguideId>N000147</bioguideId>
          <gpoId>7871</gpoId>
        </identifiers>
        <bioguideId>N000147</bioguideId>
        <middleName>HOLMES</middleName>
        <district>0</district>
        <fullName>Rep. Norton, Eleanor Holmes [D-DC-At Large]</fullName>
        <byRequestType />
        <party>D</party>
        <state>DC</state>
      </item>
    </sponsors>
    <notes />
    <createDate>2017-04-27T03:11:50Z</createDate>
    <recordedVotes />
    <version>1.0.0</version>
    <laws />
    <originChamber>House</originChamber>
    <summaries>
      <billSummaries>
        <item>
          <versionCode>00</versionCode>
          <actionDate>2017-04-26</actionDate>
          <name>Introduced in House</name>
          <lastSummaryUpdateDate>2017-10-04T20:19:38Z</lastSummaryUpdateDate>
          <updateDate>2017-04-26T04:00:00Z</updateDate>
          <actionDesc>Introduced in House</actionDesc>
          <text><![CDATA[
Low-Wage Federal Contractor Employee Back Pay Act of 2017

This bill amends the Continuing Appropriations Act, 2016 to require the federal government to provide compensation to the employees of federal contractors that provide retail, food, custodial, and security services to the federal government if such employees are placed on unpaid leave as a result of any lapse in appropriations beginning in FY2017.
]]></text>
        </item>
      </billSummaries>
    </summaries>
    <titles>
      <item>
        <title>Low-Wage Federal Contractor Employee Back Pay Act of 2017</title>
        <chamberCode />
        <titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
        <chamberName />
        <parentTitleType />
      </item>
      <item>
        <title>Low-Wage Federal Contractor Employee Back Pay Act of 2017</title>
        <chamberCode />
        <titleType>Short Titles as Introduced</titleType>
        <chamberName />
        <parentTitleType />
      </item>
      <item>
        <title>To provide for the compensation of Federal contractor employees that may be placed on unpaid leave as a result of the Federal Government shutdown, and for other purposes.</title>
        <chamberCode />
        <titleType>Official Title as Introduced</titleType>
        <chamberName />
        <parentTitleType />
      </item>
      <item>
        <title>Low-Wage Federal Contractor Employee Back Pay Act of 2017</title>
        <chamberCode />
        <titleType>Display Title</titleType>
        <chamberName />
        <parentTitleType />
      </item>
    </titles>
    <title>Low-Wage Federal Contractor Employee Back Pay Act of 2017</title>
    <actions>
      <actionTypeCounts>
        <placeholderTextForB>1</placeholderTextForB>
        <introducedInHouse>1</introducedInHouse>
        <introducedInTheHouse>1</introducedInTheHouse>
        <billReferrals>1</billReferrals>
      </actionTypeCounts>
      <actionByCounts>
        <houseOfRepresentatives>3</houseOfRepresentatives>
      </actionByCounts>
      <item>
        <links />
        <type>IntroReferral</type>
        <actionCode>H11100</actionCode>
        <sourceSystem>
          2
          <name>House floor actions</name>
        </sourceSystem>
        <actionDate>2017-04-26</actionDate>
        <committee>
          <systemCode>hsgo00</systemCode>
          <name>Oversight and Government Reform Committee</name>
        </committee>
        <text>Referred to the House Committee on Oversight and Government Reform.</text>
      </item>
      <item>
        <links>
          <link>
            <url>https://www.congress.gov/congressional-record/volume-163/extensions-of-remarks-section/page/E548</url>
            <name>E548</name>
          </link>
        </links>
        <type>IntroReferral</type>
        <actionCode>B00100</actionCode>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionDate>2017-04-26</actionDate>
        <committee />
        <text>Sponsor introductory remarks on measure. (CR E548)</text>
      </item>
      <item>
        <links />
        <type>IntroReferral</type>
        <actionCode>Intro-H</actionCode>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionDate>2017-04-26</actionDate>
        <committee />
        <text>Introduced in House</text>
      </item>
      <item>
        <links />
        <type>IntroReferral</type>
        <actionCode>1000</actionCode>
        <sourceSystem>
          9
          <name>Library of Congress</name>
        </sourceSystem>
        <actionDate>2017-04-26</actionDate>
        <committee />
        <text>Introduced in House</text>
      </item>
    </actions>
    <billType>HR</billType>
    <cboCostEstimates />
    <amendments />
    <updateDate>2017-10-04T20:30:10Z</updateDate>
    <constitutionalAuthorityStatementText><![CDATA[
From the Congressional Record Online through the Government Publishing Office [www.gpo.gov]By Ms. NORTON:H.R. 2178.Congress has the power to enact this legislation pursuantto the following:clause 7 of section 9 of article I of the Constitution.[Page H2898]
]]></constitutionalAuthorityStatementText>
    <committees>
      <billCommittees>
        <item>
          <name>Oversight and Government Reform Committee</name>
          <activities>
            <item>
              <name>Referred to</name>
              <date>2017-04-26T14:01:25Z</date>
            </item>
          </activities>
          <type>Standing</type>
          <chamber>House</chamber>
          <subcommittees />
          <systemCode>hsgo00</systemCode>
        </item>
      </billCommittees>
    </committees>
    <congress>115</congress>
    <billNumber>2178</billNumber>
    <policyArea>
      <name>Government Operations and Politics</name>
    </policyArea>
  </bill>
  <dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
    <dc:format>text/xml</dc:format>
    <dc:language>EN</dc:language>
    <dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
    <dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
    <dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
  </dublinCore>
</billStatus>


text:
package com.sequenceiq.cloudbreak.domain;

import com.sequenceiq.cloudbreak.api.endpoint.v4.common.DetailedStackStatus;
import com.sequenceiq.cloudbreak.converter.DefaultEnumConverter;

public class DetailedStackStatusConverter extends DefaultEnumConverter<DetailedStackStatus> {

    @Override
    public DetailedStackStatus getDefault() {
        return DetailedStackStatus.AVAILABLE;
    }
}


text:
package pki

import (
	cryptorand "crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"encoding/pem"
	"errors"
	"fmt"
	"io/ioutil"
	"math"
	"math/big"
	"net"
	"os"
	"path/filepath"
	"reflect"
	"strings"
	"time"

	"github.com/rancher/rke/hosts"
	"github.com/rancher/rke/pki/cert"
	v3 "github.com/rancher/types/apis/management.cattle.io/v3"
	"github.com/sirupsen/logrus"
)

var (
	oidExtensionExtendedKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}
	oidExtKeyUsageServerAuth     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
	oidExtKeyUsageClientAuth     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
)

func GenerateSignedCertAndKey(
	caCrt *x509.Certificate,
	caKey *rsa.PrivateKey,
	serverCrt bool,
	commonName string,
	altNames *cert.AltNames,
	reusedKey *rsa.PrivateKey,
	orgs []string) (*x509.Certificate, *rsa.PrivateKey, error) {
	// Generate a generic signed certificate
	var rootKey *rsa.PrivateKey
	var err error
	rootKey = reusedKey
	if reusedKey == nil {
		rootKey, err = cert.NewPrivateKey()
		if err != nil {
			return nil, nil, fmt.Errorf("Failed to generate private key for %s certificate: %v", commonName, err)
		}
	}
	usages := []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}
	if serverCrt {
		usages = append(usages, x509.ExtKeyUsageServerAuth)
	}
	if altNames == nil {
		altNames = &cert.AltNames{}
	}
	caConfig := cert.Config{
		CommonName:   commonName,
		Organization: orgs,
		Usages:       usages,
		AltNames:     *altNames,
	}
	clientCert, err := newSignedCert(caConfig, rootKey, caCrt, caKey)
	if err != nil {
		return nil, nil, fmt.Errorf("Failed to generate %s certificate: %v", commonName, err)
	}
	return clientCert, rootKey, nil
}

func GenerateCertSigningRequestAndKey(
	serverCrt bool,
	commonName string,
	altNames *cert.AltNames,
	reusedKey *rsa.PrivateKey,
	orgs []string) ([]byte, *rsa.PrivateKey, error) {
	// Generate a generic signed certificate
	var rootKey *rsa.PrivateKey
	var err error
	rootKey = reusedKey
	if reusedKey == nil {
		rootKey, err = cert.NewPrivateKey()
		if err != nil {
			return nil, nil, fmt.Errorf("Failed to generate private key for %s certificate: %v", commonName, err)
		}
	}
	usages := []asn1.ObjectIdentifier{oidExtKeyUsageClientAuth}
	if serverCrt {
		usages = append(usages, oidExtKeyUsageServerAuth)
	}
	marshalledUsages, err := asn1.Marshal(usages)
	if err != nil {
		return nil, nil, fmt.Errorf("error marshalling key usages while generating csr: %v", err)
	}

	extensions := []pkix.Extension{{
		Id:       oidExtensionExtendedKeyUsage,
		Critical: false,
		Value:    marshalledUsages,
	}}
	if altNames == nil {
		altNames = &cert.AltNames{}
	}
	caConfig := cert.Config{
		CommonName:   commonName,
		Organization: orgs,
		AltNames:     *altNames,
	}
	clientCSR, err := newCertSigningRequest(caConfig, rootKey, extensions)

	if err != nil {
		return nil, nil, fmt.Errorf("Failed to generate %s certificate: %v", commonName, err)
	}
	return clientCSR, rootKey, nil
}

func GenerateCACertAndKey(commonName string, privateKey *rsa.PrivateKey) (*x509.Certificate, *rsa.PrivateKey, error) {
	var err error
	rootKey := privateKey
	if rootKey == nil {
		rootKey, err = cert.NewPrivateKey()
		if err != nil {
			return nil, nil, fmt.Errorf("Failed to generate private key for CA certificate: %v", err)
		}
	}
	caConfig := cert.Config{
		CommonName: commonName,
	}
	kubeCACert, err := cert.NewSelfSignedCACert(caConfig, rootKey)
	if err != nil {
		return nil, nil, fmt.Errorf("Failed to generate CA certificate: %v", err)
	}

	return kubeCACert, rootKey, nil
}

func GetIPHostAltnamesForHost(host *hosts.Host) *cert.AltNames {
	var ips []net.IP
	dnsNames := []string{}
	// Check if node address is a valid IP
	if nodeIP := net.ParseIP(host.Address); nodeIP != nil {
		ips = append(ips, nodeIP)
	} else {
		dnsNames = append(dnsNames, host.Address)
	}

	// Check if node internal address is a valid IP
	if len(host.InternalAddress) != 0 && host.InternalAddress != host.Address {
		if internalIP := net.ParseIP(host.InternalAddress); internalIP != nil {
			ips = append(ips, internalIP)
		} else {
			dnsNames = append(dnsNames, host.InternalAddress)
		}
	}
	// Add hostname to the ALT dns names
	if len(host.HostnameOverride) != 0 && host.HostnameOverride != host.Address {
		dnsNames = append(dnsNames, host.HostnameOverride)
	}
	return &cert.AltNames{
		IPs:      ips,
		DNSNames: dnsNames,
	}
}

func GetAltNames(cpHosts []*hosts.Host, clusterDomain string, KubernetesServiceIP net.IP, SANs []string) *cert.AltNames {
	ips := []net.IP{}
	dnsNames := []string{}
	for _, host := range cpHosts {
		// Check if node address is a valid IP
		if nodeIP := net.ParseIP(host.Address); nodeIP != nil {
			ips = append(ips, nodeIP)
		} else {
			dnsNames = append(dnsNames, host.Address)
		}

		// Check if node internal address is a valid IP
		if len(host.InternalAddress) != 0 && host.InternalAddress != host.Address {
			if internalIP := net.ParseIP(host.InternalAddress); internalIP != nil {
				ips = append(ips, internalIP)
			} else {
				dnsNames = append(dnsNames, host.InternalAddress)
			}
		}
		// Add hostname to the ALT dns names
		if len(host.HostnameOverride) != 0 && host.HostnameOverride != host.Address {
			dnsNames = append(dnsNames, host.HostnameOverride)
		}
	}

	for _, host := range SANs {
		// Check if node address is a valid IP
		if nodeIP := net.ParseIP(host); nodeIP != nil {
			ips = append(ips, nodeIP)
		} else {
			dnsNames = append(dnsNames, host)
		}
	}

	ips = append(ips, net.ParseIP("127.0.0.1"))
	ips = append(ips, KubernetesServiceIP)
	dnsNames = append(dnsNames, []string{
		"localhost",
		"kubernetes",
		"kubernetes.default",
		"kubernetes.default.svc",
		"kubernetes.default.svc." + clusterDomain,
	}...)
	return &cert.AltNames{
		IPs:      ips,
		DNSNames: dnsNames,
	}
}

func (c *CertificatePKI) ToEnv() []string {
	env := []string{}
	if c.Key != nil {
		env = append(env, c.KeyToEnv())
	}
	if c.Certificate != nil {
		env = append(env, c.CertToEnv())
	}
	if c.Config != "" && c.ConfigEnvName != "" {
		env = append(env, c.ConfigToEnv())
	}
	return env
}

func (c *CertificatePKI) CertToEnv() string {
	encodedCrt := cert.EncodeCertPEM(c.Certificate)
	return fmt.Sprintf("%s=%s", c.EnvName, string(encodedCrt))
}

func (c *CertificatePKI) KeyToEnv() string {
	encodedKey := cert.EncodePrivateKeyPEM(c.Key)
	return fmt.Sprintf("%s=%s", c.KeyEnvName, string(encodedKey))
}

func (c *CertificatePKI) ConfigToEnv() string {
	return fmt.Sprintf("%s=%s", c.ConfigEnvName, c.Config)
}

func getEnvFromName(name string) string {
	return strings.Replace(strings.ToUpper(name), "-", "_", -1)
}

func getKeyEnvFromEnv(env string) string {
	return fmt.Sprintf("%s_KEY", env)
}

func getConfigEnvFromEnv(env string) string {
	return fmt.Sprintf("KUBECFG_%s", env)
}

func GetCrtNameForHost(host *hosts.Host, prefix string) string {
	var newAddress string
	if len(host.InternalAddress) != 0 && host.InternalAddress != host.Address {
		newAddress = strings.Replace(host.InternalAddress, ".", "-", -1)
	} else {
		newAddress = strings.Replace(host.Address, ".", "-", -1)
	}
	return prefix + "-" + newAddress
}

func GetCertPath(name string) string {
	return CertPathPrefix + name + ".pem"
}

func GetKeyPath(name string) string {
	return CertPathPrefix + name + "-key.pem"
}

func GetConfigPath(name string) string {
	return CertPathPrefix + "kubecfg-" + name + ".yaml"
}

func GetCertTempPath(name string) string {
	return TempCertPath + name + ".pem"
}

func GetKeyTempPath(name string) string {
	return TempCertPath + name + ".pem"
}

func GetConfigTempPath(name string) string {
	return TempCertPath + "kubecfg-" + name + ".yaml"
}

func ToCertObject(componentName, commonName, ouName string, certificate *x509.Certificate, key *rsa.PrivateKey, csrASN1 []byte) CertificatePKI {
	var config, configPath, configEnvName, certificatePEM, keyPEM string
	var csr *x509.CertificateRequest
	var csrPEM []byte
	if len(commonName) == 0 {
		commonName = getDefaultCN(componentName)
	}

	envName := getEnvFromName(componentName)
	keyEnvName := getKeyEnvFromEnv(envName)
	caCertPath := GetCertPath(CACertName)
	path := GetCertPath(componentName)
	keyPath := GetKeyPath(componentName)
	if certificate != nil {
		certificatePEM = string(cert.EncodeCertPEM(certificate))
	}
	if key != nil {
		keyPEM = string(cert.EncodePrivateKeyPEM(key))
	}
	if csrASN1 != nil {
		csr, _ = x509.ParseCertificateRequest(csrASN1)
		csrPEM = pem.EncodeToMemory(&pem.Block{
			Type: "CERTIFICATE REQUEST", Bytes: csrASN1,
		})
	}

	if componentName != CACertName && componentName != KubeAPICertName && !strings.Contains(componentName, EtcdCertName) && !strings.Contains(componentName, KubeletCertName) && componentName != ServiceAccountTokenKeyName {
		config = getKubeConfigX509("https://127.0.0.1:6443", "local", componentName, caCertPath, path, keyPath)
		configPath = GetConfigPath(componentName)
		configEnvName = getConfigEnvFromEnv(envName)
	}

	return CertificatePKI{
		Certificate:    certificate,
		Key:            key,
		CSR:            csr,
		CertificatePEM: certificatePEM,
		KeyPEM:         keyPEM,
		CSRPEM:         string(csrPEM),
		Config:         config,
		Name:           componentName,
		CommonName:     commonName,
		OUName:         ouName,
		EnvName:        envName,
		KeyEnvName:     keyEnvName,
		ConfigEnvName:  configEnvName,
		Path:           path,
		KeyPath:        keyPath,
		ConfigPath:     configPath,
	}
}

func getDefaultCN(name string) string {
	return fmt.Sprintf("system:%s", name)
}

func getCertKeys(rkeNodes []v3.RKEConfigNode, nodeRole string, rkeConfig *v3.RancherKubernetesEngineConfig) []string {
	// static certificates each node needs
	certList := []string{CACertName, KubeProxyCertName, KubeNodeCertName}
	allHosts := hosts.NodesToHosts(rkeNodes, "")
	if IsKubeletGenerateServingCertificateEnabledinConfig(rkeConfig) {
		for _, host := range allHosts {
			// Add per node kubelet certificates (used for kube-api -> kubelet connection)
			certList = append(certList, GetCrtNameForHost(host, KubeletCertName))
		}
	}
	// etcd
	if nodeRole == etcdRole {
		etcdHosts := hosts.NodesToHosts(rkeNodes, nodeRole)
		for _, host := range etcdHosts {
			certList = append(certList, GetCrtNameForHost(host, EtcdCertName))
		}
		return certList
	}
	// control
	if nodeRole == controlRole {
		controlCertList := []string{
			KubeAPICertName,
			ServiceAccountTokenKeyName,
			KubeControllerCertName,
			KubeSchedulerCertName,
			EtcdClientCertName,
			EtcdClientCACertName,
			RequestHeaderCACertName,
			APIProxyClientCertName,
		}
		certList = append(certList, controlCertList...)
		return certList
	}
	// worker
	return certList
}

func GetKubernetesServiceIP(serviceClusterRange string) (net.IP, error) {
	ip, ipnet, err := net.ParseCIDR(serviceClusterRange)
	if err != nil {
		return nil, fmt.Errorf("Failed to get kubernetes service IP from Kube API option [service_cluster_ip_range]: %v", err)
	}
	ip = ip.Mask(ipnet.Mask)
	for j := len(ip) - 1; j >= 0; j-- {
		ip[j]++
		if ip[j] > 0 {
			break
		}
	}
	return ip, nil
}

func GetLocalKubeConfig(configPath, configDir string) string {
	baseDir := filepath.Dir(configPath)
	if len(configDir) > 0 {
		baseDir = filepath.Dir(configDir)
	}
	fileName := filepath.Base(configPath)
	baseDir += "/"
	return fmt.Sprintf("%s%s%s", baseDir, KubeAdminConfigPrefix, fileName)
}

func populateCertMap(tmpCerts map[string]CertificatePKI, localConfigPath string, extraHosts []*hosts.Host) map[string]CertificatePKI {
	certs := make(map[string]CertificatePKI)
	// CACert
	certs[CACertName] = ToCertObject(CACertName, "", "", tmpCerts[CACertName].Certificate, tmpCerts[CACertName].Key, nil)
	// KubeAPI
	certs[KubeAPICertName] = ToCertObject(KubeAPICertName, "", "", tmpCerts[KubeAPICertName].Certificate, tmpCerts[KubeAPICertName].Key, nil)
	// kubeController
	certs[KubeControllerCertName] = ToCertObject(KubeControllerCertName, "", "", tmpCerts[KubeControllerCertName].Certificate, tmpCerts[KubeControllerCertName].Key, nil)
	// KubeScheduler
	certs[KubeSchedulerCertName] = ToCertObject(KubeSchedulerCertName, "", "", tmpCerts[KubeSchedulerCertName].Certificate, tmpCerts[KubeSchedulerCertName].Key, nil)
	// KubeProxy
	certs[KubeProxyCertName] = ToCertObject(KubeProxyCertName, "", "", tmpCerts[KubeProxyCertName].Certificate, tmpCerts[KubeProxyCertName].Key, nil)
	// KubeNode
	certs[KubeNodeCertName] = ToCertObject(KubeNodeCertName, KubeNodeCommonName, KubeNodeOrganizationName, tmpCerts[KubeNodeCertName].Certificate, tmpCerts[KubeNodeCertName].Key, nil)
	// KubeAdmin
	kubeAdminCertObj := ToCertObject(KubeAdminCertName, KubeAdminCertName, KubeAdminOrganizationName, tmpCerts[KubeAdminCertName].Certificate, tmpCerts[KubeAdminCertName].Key, nil)
	kubeAdminCertObj.Config = tmpCerts[KubeAdminCertName].Config
	kubeAdminCertObj.ConfigPath = localConfigPath
	certs[KubeAdminCertName] = kubeAdminCertObj
	// etcd
	for _, host := range extraHosts {
		etcdName := GetCrtNameForHost(host, EtcdCertName)
		etcdCrt, etcdKey := tmpCerts[etcdName].Certificate, tmpCerts[etcdName].Key
		certs[etcdName] = ToCertObject(etcdName, "", "", etcdCrt, etcdKey, nil)
	}
	// Request header ca
	certs[RequestHeaderCACertName] = ToCertObject(RequestHeaderCACertName, "", "", tmpCerts[RequestHeaderCACertName].Certificate, tmpCerts[RequestHeaderCACertName].Key, nil)
	// Api proxy client
	certs[APIProxyClientCertName] = ToCertObject(APIProxyClientCertName, "", "", tmpCerts[APIProxyClientCertName].Certificate, tmpCerts[APIProxyClientCertName].Key, nil)
	return certs
}

// Overriding k8s.io/client-go/util/cert.NewSignedCert function to extend the expiration date to 10 years instead of 1 year
func newSignedCert(cfg cert.Config, key *rsa.PrivateKey, caCert *x509.Certificate, caKey *rsa.PrivateKey) (*x509.Certificate, error) {
	serial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64))
	if err != nil {
		return nil, err
	}
	if len(cfg.CommonName) == 0 {
		return nil, errors.New("must specify a CommonName")
	}
	if len(cfg.Usages) == 0 {
		return nil, errors.New("must specify at least one ExtKeyUsage")
	}

	certTmpl := x509.Certificate{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: cfg.Organization,
		},
		DNSNames:     cfg.AltNames.DNSNames,
		IPAddresses:  cfg.AltNames.IPs,
		SerialNumber: serial,
		NotBefore:    caCert.NotBefore,
		NotAfter:     time.Now().Add(duration365d * 10).UTC(),
		KeyUsage:     x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
		ExtKeyUsage:  cfg.Usages,
	}
	certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &certTmpl, caCert, key.Public(), caKey)
	if err != nil {
		return nil, err
	}
	return x509.ParseCertificate(certDERBytes)
}

func newCertSigningRequest(cfg cert.Config, key *rsa.PrivateKey, extensions []pkix.Extension) ([]byte, error) {
	if len(cfg.CommonName) == 0 {
		return nil, errors.New("must specify a CommonName")
	}
	if len(extensions) == 0 {
		return nil, errors.New("must specify at least one Extension")
	}

	certTmpl := x509.CertificateRequest{
		Subject: pkix.Name{
			CommonName:   cfg.CommonName,
			Organization: cfg.Organization,
		},
		DNSNames:        cfg.AltNames.DNSNames,
		IPAddresses:     cfg.AltNames.IPs,
		ExtraExtensions: extensions,
	}
	return x509.CreateCertificateRequest(cryptorand.Reader, &certTmpl, key)
}

func isFileNotFoundErr(e error) bool {
	if strings.Contains(e.Error(), "no such file or directory") ||
		strings.Contains(e.Error(), "Could not find the file") ||
		strings.Contains(e.Error(), "No such container:path:") {
		return true
	}
	return false
}

func DeepEqualIPsAltNames(oldIPs, newIPs []net.IP) bool {
	if len(oldIPs) != len(newIPs) {
		return false
	}
	oldIPsStrings := make([]string, len(oldIPs))
	newIPsStrings := make([]string, len(newIPs))
	for i := range oldIPs {
		oldIPsStrings = append(oldIPsStrings, oldIPs[i].String())
		newIPsStrings = append(newIPsStrings, newIPs[i].String())
	}
	return reflect.DeepEqual(oldIPsStrings, newIPsStrings)
}

func TransformPEMToObject(in map[string]CertificatePKI) map[string]CertificatePKI {
	var certificate *x509.Certificate
	out := map[string]CertificatePKI{}
	for k, v := range in {
		certs, _ := cert.ParseCertsPEM([]byte(v.CertificatePEM))
		key, _ := cert.ParsePrivateKeyPEM([]byte(v.KeyPEM))
		if len(certs) > 0 {
			certificate = certs[0]
		}
		if key != nil {
			key = key.(*rsa.PrivateKey)
		}
		o := CertificatePKI{
			ConfigEnvName:  v.ConfigEnvName,
			Name:           v.Name,
			Config:         v.Config,
			CommonName:     v.CommonName,
			OUName:         v.OUName,
			EnvName:        v.EnvName,
			Path:           v.Path,
			KeyEnvName:     v.KeyEnvName,
			KeyPath:        v.KeyPath,
			ConfigPath:     v.ConfigPath,
			Certificate:    certificate,
			CertificatePEM: v.CertificatePEM,
			KeyPEM:         v.KeyPEM,
		}
		if key != nil {
			o.Key = key.(*rsa.PrivateKey)
		}

		out[k] = o
	}
	return out
}

func ReadCSRsAndKeysFromDir(certDir string) (map[string]CertificatePKI, error) {
	certMap := make(map[string]CertificatePKI)
	if _, err := os.Stat(certDir); os.IsNotExist(err) {
		return certMap, nil
	}

	files, err := ioutil.ReadDir(certDir)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		if strings.Contains(file.Name(), "-csr.pem") {
			certName := strings.TrimSuffix(file.Name(), "-csr.pem")
			logrus.Debugf("[certificates] Loading %s csr from directory [%s]", certName, certDir)
			// fetching csr
			csrASN1, err := getCSRFromFile(certDir, certName+"-csr.pem")
			if err != nil {
				return nil, err
			}
			// fetching key
			key, err := getKeyFromFile(certDir, certName+"-key.pem")
			if err != nil {
				return nil, err
			}
			certMap[certName] = ToCertObject(certName, getCommonName(certName), getOUName(certName), nil, key, csrASN1)
		}
	}

	return certMap, nil
}

func ReadCertsAndKeysFromDir(certDir string) (map[string]CertificatePKI, error) {
	certMap := make(map[string]CertificatePKI)
	if _, err := os.Stat(certDir); os.IsNotExist(err) {
		return certMap, nil
	}

	files, err := ioutil.ReadDir(certDir)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		logrus.Debugf("[certificates] reading file %s from directory [%s]", file.Name(), certDir)
		// fetching cert
		cert, err := getCertFromFile(certDir, file.Name())
		if err != nil {
			continue
		}
		// fetching the cert's key
		certName := strings.TrimSuffix(file.Name(), ".pem")
		key, err := getKeyFromFile(certDir, certName+"-key.pem")
		if err != nil {
			continue
		}
		certMap[certName] = ToCertObject(certName, getCommonName(certName), getOUName(certName), cert, key, nil)
	}

	return certMap, nil
}

func getCommonName(certName string) string {
	switch certName {
	case KubeNodeCertName:
		return KubeNodeCommonName
	default:
		return certName
	}
}

func getOUName(certName string) string {
	switch certName {
	case KubeNodeCertName:
		return KubeNodeOrganizationName
	case KubeAdminCertName:
		return KubeAdminOrganizationName
	default:
		return ""
	}
}

func getCertFromFile(certDir string, fileName string) (*x509.Certificate, error) {
	var certificate *x509.Certificate
	certPEM, _ := ioutil.ReadFile(filepath.Join(certDir, fileName))
	if len(certPEM) > 0 {
		certificates, err := cert.ParseCertsPEM(certPEM)
		if err != nil {
			return nil, fmt.Errorf("failed to read certificate [%s]: %v", fileName, err)
		}
		certificate = certificates[0]
	}
	return certificate, nil
}

func getKeyFromFile(certDir string, fileName string) (*rsa.PrivateKey, error) {
	var key *rsa.PrivateKey
	keyPEM, _ := ioutil.ReadFile(filepath.Join(certDir, fileName))
	if len(keyPEM) > 0 {
		keyInterface, err := cert.ParsePrivateKeyPEM(keyPEM)
		if err != nil {
			return nil, fmt.Errorf("failed to read key [%s]: %v", fileName, err)
		}
		key = keyInterface.(*rsa.PrivateKey)
	}
	return key, nil
}

func getCSRFromFile(certDir string, fileName string) ([]byte, error) {
	csrPEM, err := ioutil.ReadFile(filepath.Join(certDir, fileName))
	if err != nil {
		return nil, fmt.Errorf("failed to read csr [%s]: %v", fileName, err)
	}
	csrASN1, _ := pem.Decode(csrPEM)
	return csrASN1.Bytes, nil
}

func WriteCertificates(certDirPath string, certBundle map[string]CertificatePKI) error {
	if _, err := os.Stat(certDirPath); os.IsNotExist(err) {
		err = os.MkdirAll(certDirPath, 0755)
		if err != nil {
			return err
		}
	}

	for certName, cert := range certBundle {
		if cert.CertificatePEM != "" {
			certificatePath := filepath.Join(certDirPath, certName+".pem")
			if err := ioutil.WriteFile(certificatePath, []byte(cert.CertificatePEM), 0640); err != nil {
				return fmt.Errorf("Failed to write certificate to path %v: %v", certificatePath, err)
			}
			logrus.Debugf("Successfully Deployed certificate file at [%s]", certificatePath)
		}

		if cert.KeyPEM != "" {
			keyPath := filepath.Join(certDirPath, certName+"-key.pem")
			if err := ioutil.WriteFile(keyPath, []byte(cert.KeyPEM), 0640); err != nil {
				return fmt.Errorf("Failed to write key to path %v: %v", keyPath, err)
			}
			logrus.Debugf("Successfully Deployed key file at [%s]", keyPath)
		}

		if cert.CSRPEM != "" {
			csrPath := filepath.Join(certDirPath, certName+"-csr.pem")
			if err := ioutil.WriteFile(csrPath, []byte(cert.CSRPEM), 0640); err != nil {
				return fmt.Errorf("Failed to write csr to path %v: %v", csrPath, err)
			}
			logrus.Debugf("Successfully Deployed csr file at [%s]", csrPath)
		}
	}
	logrus.Infof("Successfully Deployed certificates at [%s]", certDirPath)
	return nil
}

func ValidateBundleContent(rkeConfig *v3.RancherKubernetesEngineConfig, certBundle map[string]CertificatePKI, configPath, configDir string) error {
	// ensure all needed certs exists
	// make sure all CA Certs exist
	if certBundle[CACertName].Certificate == nil {
		return fmt.Errorf("Failed to find master CA certificate")
	}
	if certBundle[RequestHeaderCACertName].Certificate == nil {
		logrus.Warnf("Failed to find RequestHeader CA certificate, using master CA certificate")
		certBundle[RequestHeaderCACertName] = ToCertObject(RequestHeaderCACertName, RequestHeaderCACertName, "", certBundle[CACertName].Certificate, nil, nil)
	}
	// make sure all components exists
	ComponentsCerts := []string{
		KubeAPICertName,
		KubeControllerCertName,
		KubeSchedulerCertName,
		KubeProxyCertName,
		KubeNodeCertName,
		KubeAdminCertName,
		APIProxyClientCertName,
	}
	for _, certName := range ComponentsCerts {
		if certBundle[certName].Certificate == nil || certBundle[certName].Key == nil {
			return fmt.Errorf("Failed to find [%s] Certificate or Key", certName)
		}
	}
	etcdHosts := hosts.NodesToHosts(rkeConfig.Nodes, etcdRole)
	for _, host := range etcdHosts {
		etcdName := GetCrtNameForHost(host, EtcdCertName)
		if certBundle[etcdName].Certificate == nil || certBundle[etcdName].Key == nil {
			return fmt.Errorf("Failed to find etcd [%s] Certificate or Key", etcdName)
		}
	}
	// Configure kubeconfig
	cpHosts := hosts.NodesToHosts(rkeConfig.Nodes, controlRole)
	localKubeConfigPath := GetLocalKubeConfig(configPath, configDir)
	if len(cpHosts) > 0 {
		kubeAdminCertObj := certBundle[KubeAdminCertName]
		kubeAdminConfig := GetKubeConfigX509WithData(
			"https://"+cpHosts[0].Address+":6443",
			rkeConfig.ClusterName,
			KubeAdminCertName,
			string(cert.EncodeCertPEM(certBundle[CACertName].Certificate)),
			string(cert.EncodeCertPEM(certBundle[KubeAdminCertName].Certificate)),
			string(cert.EncodePrivateKeyPEM(certBundle[KubeAdminCertName].Key)))
		kubeAdminCertObj.Config = kubeAdminConfig
		kubeAdminCertObj.ConfigPath = localKubeConfigPath
		certBundle[KubeAdminCertName] = kubeAdminCertObj
	}
	return validateCAIssuer(rkeConfig, certBundle)
}

func validateCAIssuer(rkeConfig *v3.RancherKubernetesEngineConfig, certBundle map[string]CertificatePKI) error {
	// make sure all certs are signed by CA cert
	caCert := certBundle[CACertName].Certificate
	ComponentsCerts := []string{
		KubeAPICertName,
		KubeControllerCertName,
		KubeSchedulerCertName,
		KubeProxyCertName,
		KubeNodeCertName,
		KubeAdminCertName,
	}
	etcdHosts := hosts.NodesToHosts(rkeConfig.Nodes, etcdRole)
	for _, host := range etcdHosts {
		etcdName := GetCrtNameForHost(host, EtcdCertName)
		ComponentsCerts = append(ComponentsCerts, etcdName)
	}
	for _, componentCert := range ComponentsCerts {
		if certBundle[componentCert].Certificate.Issuer.CommonName != caCert.Subject.CommonName {
			return fmt.Errorf("Component [%s] is not signed by the custom CA certificate", componentCert)
		}
	}
	requestHeaderCACert := certBundle[RequestHeaderCACertName].Certificate
	if certBundle[APIProxyClientCertName].Certificate.Issuer.CommonName != requestHeaderCACert.Subject.CommonName {
		return fmt.Errorf("Component [%s] is not signed by the custom Request Header CA certificate", APIProxyClientCertName)
	}
	return nil
}

func ReadCertToStr(file string) (string, error) {
	certStr, err := ioutil.ReadFile(file)
	if err != nil {
		return "", fmt.Errorf("failed to read certificate [%s]: %v", file, err)
	}
	return string(certStr), nil
}

func IsValidCertStr(c string) (bool, error) {
	_, err := cert.ParseCertsPEM([]byte(c))
	if err != nil {
		return false, err
	}
	return true, nil
}

func IsKubeletGenerateServingCertificateEnabledinConfig(rkeConfig *v3.RancherKubernetesEngineConfig) bool {
	if rkeConfig.Services.Kubelet.GenerateServingCertificate {
		return true
	}
	return false
}


text:
package reflect.cpp;

import java.io.PrintStream;

import reflect.api.Class;
import reflect.api.Property;

public abstract class PropWriter extends TypeUtils {
	private PrintStream out;
	private Class clazz;
	private Template tmplt = new Template();
	private String indent;
	protected boolean isStatic;

	private void onProperty(PrintStream _out, String _indent, Class _clazz, String _ns_dummy, boolean _isStatic, String type, String name) {
		String var;
		String classRetType;
		String nsRetType;
		String rawRetType;

		out = _out;
		clazz = _clazz;
		indent = _indent;
		isStatic = _isStatic;

		tmplt.clear();
		tmplt.setHost(this);

		var = "m_" + name;
		rawRetType = type;

		classRetType = j2c(getType(rawRetType, clazz.getName()));
		nsRetType = j2c(getType(rawRetType, _ns_dummy));

		tmplt.put("name", name);
		tmplt.put("var", var);
		tmplt.put("rawRetType", rawRetType);
		tmplt.put("classRetType", classRetType);
		tmplt.put("nsRetType", nsRetType);

		onProperty();
	}
	abstract void onProperty();

	public void put(String key, String replacement) {
		tmplt.put(key, replacement);
	}

	void templateLine(String tmplt) {
		out.print(indent);
		this.tmplt.println(out, tmplt);
	}

	public static void print(PrintStream out, String indent, Class clazz, PropWriter cb) {
		final String ns_dummy = clazz.getPackage() + ".?";
		for (Property prop: clazz.getProperties()) {
			if (!isKnownClassOrBuiltin(prop.getSignature()))
				continue;
			cb.onProperty(out, indent, clazz, ns_dummy, prop.isStatic(), prop.getSignature(), prop.getName());
		}
	}
}


text:
<?php

/**
 * The "orders" collection of methods.
 * Typical usage is:
 *  <code>
 *   $playmoviespartnerService = new Google_Service_Playmoviespartner(...);
 *   $orders = $playmoviespartnerService->orders;
 *  </code>
 */
class Google_Service_Playmoviespartner_AccountsOrdersResource extends Google_Service_Resource
{
  /**
   * Get an Order given its id. See _Authentication and Authorization rules_ and
   * _Get methods rules_ for more information about this method. (orders.get)
   *
   * @param string $accountId REQUIRED. See _General rules_ for more information
   * about this field.
   * @param string $orderId REQUIRED. Order ID.
   * @param array $optParams Optional parameters.
   * @return Google_Service_Playmoviespartner_Order
   */
  public function get($accountId, $orderId, $optParams = array())
  {
    $params = array('accountId' => $accountId, 'orderId' => $orderId);
    $params = array_merge($params, $optParams);
    return $this->call('get', array($params), "Google_Service_Playmoviespartner_Order");
  }
  /**
   * List Orders owned or managed by the partner. See _Authentication and
   * Authorization rules_ and _List methods rules_ for more information about this
   * method. (orders.listAccountsOrders)
   *
   * @param string $accountId REQUIRED. See _General rules_ for more information
   * about this field.
   * @param array $optParams Optional parameters.
   *
   * @opt_param int pageSize See _List methods rules_ for info about this field.
   * @opt_param string pageToken See _List methods rules_ for info about this
   * field.
   * @opt_param string pphNames See _List methods rules_ for info about this
   * field.
   * @opt_param string studioNames See _List methods rules_ for info about this
   * field.
   * @opt_param string name Filter Orders that match a title name (case-
   * insensitive, sub-string match).
   * @opt_param string status Filter Orders that match one of the given status.
   * @opt_param string customId Filter Orders that match a case-insensitive,
   * partner-specific custom id.
   * @return Google_Service_Playmoviespartner_ListOrdersResponse
   */
  public function listAccountsOrders($accountId, $optParams = array())
  {
    $params = array('accountId' => $accountId);
    $params = array_merge($params, $optParams);
    return $this->call('list', array($params), "Google_Service_Playmoviespartner_ListOrdersResponse");
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class energy.usef.agr.model.SynchronisationConnectionStatusType (usef-root-pom 1.3.6 API)</title>
<meta name="date" content="2016-09-29">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
energy.usef.agr.model.SynchronisationConnectionStatusType

Packages that use SynchronisationConnectionStatusType

Package
Description

energy.usef.agr.model

Model classes of the Aggregator.

energy.usef.agr.repository

Repository classes of the Aggregator.

Uses of SynchronisationConnectionStatusType in energy.usef.agr.model

Methods in energy.usef.agr.model that return SynchronisationConnectionStatusType

Modifier and Type
Method and Description

SynchronisationConnectionStatusType
SynchronisationConnection.findStatusForCRO(String domain)

SynchronisationConnectionStatusType
SynchronisationConnectionStatus.getStatus()

static SynchronisationConnectionStatusType
SynchronisationConnectionStatusType.valueOf(String name)

Returns the enum constant of this type with the specified name.

static SynchronisationConnectionStatusType[]
SynchronisationConnectionStatusType.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in energy.usef.agr.model with parameters of type SynchronisationConnectionStatusType

Modifier and Type
Method and Description

void
SynchronisationConnectionStatus.setStatus(SynchronisationConnectionStatusType status)

Uses of SynchronisationConnectionStatusType in energy.usef.agr.repository

Methods in energy.usef.agr.repository with parameters of type SynchronisationConnectionStatusType

Modifier and Type
Method and Description

Long
SynchronisationConnectionStatusRepository.countSynchronisationConnectionStatusWithStatus(SynchronisationConnectionStatusType statusType)

Count's the amount of statusses with a certain status Type.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016. All rights reserved.


text:
/*
    MIT LICENSE @2016 Ivan Lausuch <ilausuch@gmail.com>
    Developed at CEU University
*/

/* global ilModelConfiguration, ilModelFieldQuery */

ilModelDataProviderOData = function (config) {

	if (config===undefined)
		config={};

	if (config.context===undefined)
		config.context=ilModelConfiguration.defaultContext;

	this.config=config;
	this.url=config.url;
	this.context=config.context;

	this.init=function(parentClass,name){
    	this.parentClass = parentClass;
    	this.name=name;
    };

    this.$preparePk=function(pk){

	    if (this.config.pkMethod===undefined)
	    	this.config.pkMethod=ilModelDataProviderOData.PkMethods.firstField;

	    return this.config.pkMethod(pk,this.parentClass);

    };

    this.$get=function (config, options) {
        if (this.url===undefined || this.url==="")
        	throw new ilModelException("ilModelDataProviderOData","You must complete the url definition "+this.name+" data provider in "+this.parentClass.$className+". Ejm: "+this.parentClass.$className+".$dataProviders."+this.name+".url=\"<odata entity url>\"");

        url=this.url;

        var promise=new ilModelPromise();

        if (config.pk !== undefined) {
	        if (config.queryString)
            url = url + this.$preparePk(config.pk);//guid'" + config.id + "')";
        }

        url += "?";

        if (config.top !== undefined)
            url = url + "$top=" + config.top + "&";

        if (config.skip !== undefined)
            url = url + "$skip=" + config.skip + "&";

        if (config.expand !== undefined)
            url = url + "$expand=" + config.expand + "&";

	if (config.select !== undefined)
            url = url + "$select=" + config.select + "&";

        if (config.queryString !== undefined)
            url = url + "$filter=" + config.queryString + "&";

		if (config.orderby !== undefined)
			if (config.orderbyDesc !== undefined && config.orderbyDesc)
				url = url + "$orderby=" + config.orderby + "desc &";
			else
				url = url + "$orderby=" + config.orderby + "&";

		if (config.operation !== undefined)
			url = url + "$$op=" + config.operation + "&";

        if (this.config.debug) console.debug("OData", "call", call);

        var $this = this;

		var call={
			url:url,
	        method:"GET"
	    };

        this.context.http.call(call).then(
        	function(result){
		        if ($this.config.debug) console.debug("OData", "Raw result", result);

		        var className=$this.parentClass;

		        if (config.isList) {
	                var list = result.value;
	                var newList = [];

	                list.forEach(function (item) {
	                    newList.push(className.createIfNotExist(item));
	                });

	                if (config.first)
	                	promise.ready(newList[0]);
	                else
	                	promise.ready(newList);
	            }
	            else {
	                promise.ready(className.createIfNotExist(result));
	            }
	        },
	        function(err){
		        promise.error(err);
	        });

        return promise;
    };

    this.$call=function (method, config) {
	    var promise=new ilModelPromise({owner:this});

        var call = {
            method: method,
            url: this.url,
            headers: this.$headers
        };

        if (config.pk !== undefined) {
            call.url = call.url + this.$preparePk(config.pk);
        }

        if (config.data !== undefined)
            call.data = config.data;

        if (this.debug) console.debug("OData", "call", call);
        var $this = this;

        this.context.http.call(call).then(function (result) {

	        if ($this.debug) console.debug("OData", "Raw result", result);

            if (config.isList) {
                var list = result.data.value;
                var newList = [];
                list.forEach(function (item) {
                    newList.push(item);
                });
                promise.ready(newList);
            }
            else {
                promise.ready(result);
            }

        }, function (error) {
	        if (error.statusText)
            	promise.error(error.statusText);
            else
            	promise.error(error);
        });

        return promise;
    };

    this.prepareOptions=function(config,options){
	    for(var k in options){
		    var value=options[k];
		    var name=k.toLowerCase();

		    switch(name){
				case "top":
				case "len":
					config.top=value;
				break;
				case "skip":
				case "init":
					config.skip=value;
				break;
				case "expand":
					config.expand=value;
				break;
				case "select":
					config.select=value;
				break;
				case "op":
				case "operation":
					config.operation=value;
				break;
				case "orderby":
					config.orderby=value;
				break;
				case "orderbydesc":
					config.orderbyDesc=value;
				break;
				/*
				case "filter":
					config.queryString=value;
				break;
				*/
				case "querystring":
					config.queryString=value;
				break;

		    }
	    }
	    return config;
    };

    this.get=function (pk,options) {

	    var list=[];
	    for (var k in pk)
	    	list.push(new ilModelFieldQuery.Equals(k,pk[k]));

	    if (options!==undefined && options.filter!==undefined)
	    	list.push(options.filter);

	    var query=ilModelFieldQuery.And(list);

        //return this.$get(this.prepareOptions({ pk: pk, isList:false},options));
        return this.$get(this.prepareOptions({ queryString: ilModelDataProviderOData.toQueryString(this.parentClass,query), isList: true, first:true,top:1 }, options),options);
    };

    this.query=function (query,options) {
        return this.$get(this.prepareOptions({ queryString: ilModelDataProviderOData.toQueryString(this.parentClass,query), isList: true }, options),options);
    };

    this.all=function (options) {
        return this.$get(this.prepareOptions({ isList: true }, options));
    };

    this.create=function (data) {
        return this.$call("POST", { data: data });
    };

    this.replace=function (pk, data) {
        return this.$call("PUT", { pk: pk, data: data });
    };

    this.modify=function (pk, data) {
        return this.$call("PATCH", { pk: pk, data: data });
    };

    this.remove=function (pk) {
        return this.$call("DELETE", { pk: pk });
    };
};

ilModelDataProviderOData.toQueryString=function(Model,query){

	switch(query.type){
		case "and":
		case "or":
			var res="";
			for (var i=0;i<query.list.length-1;i++){
				res+=ilModelDataProviderOData.toQueryString(Model,query.list[i])+" "+query.type+" ";
			}
			res+=ilModelDataProviderOData.toQueryString(Model,query.list[i]);

			return res;
		break;

		case "compare":
			var field=Model.getField(query.fieldName);

			if (field===undefined)
				throw new ilModelException("ilModelDataProviderOData.toQueryString","Cannot find "+query.fieldName+" field in model",{theModel:Model});

			var value=query.value;

			switch(field.type){
				case "string":
					value="'"+value+"'";
				break;
				case "guid":
					value="guid'"+value+"'";
				break;
			}

			var comp="";

			switch (query.method){
				case "=":
					return query.fieldName+" eq "+value;
				break;
				case "<>":
					return query.fieldName+" ne "+value;
				break;
				case "<":
					return query.fieldName+" lt "+value;
				break;
				case "<=":
					return query.fieldName+" le "+value;
				break;
				case ">":
					comp=query.fieldName+" gt "+value;
				break;
				case ">=":
					comp=query.fieldName+" ge "+value;
				break;
				case "endswith":
					comp="endswith("+query.fieldName+","+value+")";
				break;
				case "startswith":
					comp="startswith("+query.fieldName+","+value+")";
				break;
				case "substringof":
					comp="substringof("+query.fieldName+","+value+")";
				break;

				//TODO: Add more options of quering, Consult https://msdn.microsoft.com/en-us/library/hh169248(v=nav.90).aspx
				//TODO length
				//TODO replace
				//TODO substring
				//TODO tolower
				//TODO toupper
				//TODO trim
				//TODO concat
				//TODO day
				//TODO month
				//TODO year
				//TODO hour
				//TODO minute
				//TODO second
				//TODO round
				//TODO floor
				//TODO ceiling

				default:
					comp=query.method;
			}

			return +" "+comp;
		break;
	}
};

ilModelDataProviderOData.PkMethods={
	v3:function(pk,parentClass){
		var result="(";

	    for (var name in pk){
		    var value=pk[name];

		    var field=undefined;

		    parentClass.$fields.some(function(field2){
				if (field2.name===name && field2.pk===true){
					field=field2;
					return true;
				}
		    });

		    if (field===undefined)
		    	throw new ilModelException("ilModelDataProviderOData","Field "+name+" is not a PK of "+parentClass.$className);

		    result+=name+"=";

		    switch(field.type){
			    case "guid":
			    	result+="guid'"+value+"'";
			    break;
			    case "int":
			    case "float":
			    	result+=value;
			    break;

			    default:
			    	result+="'"+value+"'";
		    }

		    result+=",";
	    }

	    result.substr(0,result.length-1);; //Remove last ,

	    result+=")";

	    return result;
	},
	firstField:function(pk,parentClass){
		var result="(";

	    for (var name in pk){
		    var value=pk[name];

		    var field=undefined;

		    parentClass.$fields.some(function(field2){
				if (field2.name===name && field2.pk===true){
					field=field2;
					return true;
				}
		    });

		    if (field===undefined)
		    	throw new ilModelException("ilModelDataProviderOData","Field "+name+" is not a PK of "+parentClass.$className);

		    switch(field.type){
			    case "guid":
			    	result+="guid'"+value+"'";
			    break;
			    case "int":
			    case "float":
			    	result+=value;
			    break;

			    default:
			    	result+="'"+value+"'";
		    }

		    break; //Only one
	    }

	    result+=")";

	    return result;
	}
};


text:
package com.longluo.demo.flowlayout;

import android.app.Activity;
import android.os.Bundle;

import com.longluo.demo.R;

public class FlowLayoutDemoActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flowlayout_demo2);

    }
}


text:
import React, {Component} from 'react';
import PropTypes from 'prop-types';

import Line from './Line';

export default class Content extends Component {
  constructor(props) {
    super(props);
    this.state = {
      decorated: props.text,
    };
  }
  render() {
    return (
      <div>
        {this.props.text.split('\n').map((r, i) => <Line key={i} raw={r} />)}
      </div>
    );
  }
  static propTypes = {
    text: PropTypes.string.isRequired,
  }
}


text:
#ifndef _ASSERT_H_
#define _ASSERT_H_

#if defined( NDEBUG ) || !defined( DEBUG )

#define assert(_Expression)     ((void)0)

#else

//void assert( int expression );
#include "logging/RhoLog.h"

#define assert(exp) RHO_ASSERT(exp)

#endif //NDEBUG

#endif //_ASSERT_H_


text:
using System;
using System.Xml.Serialization;

namespace Aop.Api.Domain
{
    /// <summary>
    /// KoubeiSalesKbassetStuffPurchaseorderQueryModel Data Structure.
    /// </summary>
    [Serializable]
    public class KoubeiSalesKbassetStuffPurchaseorderQueryModel : AopObject
    {
        /// <summary>
        /// 每页大小:最小1,最大100
        /// </summary>
        [XmlElement("page_size")]
        public string PageSize { get; set; }
    }
}


text:
title: Context API
---

# Context API

The Context API has been implemented in the 16.3 version of React.

It existed before, but was in beta, and thus, unadvised to work with.

The goal of Context API is to allow developers to have an easy communication between components, without needing them to be closely related (Parent/Children components).
This also reduce the need for prop drilling (passing down the props through several components), which allows for a cleaner code, easier to maintain and update.

This get to its full potential when we want to share data that will be accessed by multiple components.

This is based around two things : a Provider and a Consumer.

## Provider

On a file created exclusively to provide data, TimeProvider.js, let's say we want to share some time between components.

```javascript
// Import createContext
import React, { createContext, Component } from 'react';

// Initialize a context with a time value to it
export const TimeContext = createContext({
  time: '',
});

// Create the TimeProvider class to be used by index.js as a provider and initialize a default value
class TimeProvider extends Component {
  state = {
    time: '17:00',
  };

  // Passing the state that we just set as value to be used by our consumer and returning its children
  render() {
    return (
      <TimeContext.Provider value={this.state}>
        {this.props.children}
      </TimeContext.Provider>
    );
  }
}

export default TimeProvider;
```
We need to tweak a bit the component that will call the child which needs to consume our context (<ShowTime /> in this case).

```javascript
// index.js
import React from "react";
import ReactDOM from "react-dom";
import { ShowTime} from "./ShowTime";

// Importing our provider
import TimeProvider from "./utils/timeProvider";

// Calling our Hello component inside our provider
function App() {
  return (
      <TimeProvider>
        <ShowTime />
      </TimeProvider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
```

## Consumer
In the ShowTime.js file, let's call the time value using the consumer :

```javascript
// on ShowTime.js
import React from "react";

import { TimeContext } from "./utils/TimeProvider";

export default () => (
  <TimeContext.Consumer>
    {value => <p> It's {value.time} ! </p>}
  </TimeContext.Consumer>
);
```

This should show :
```javascript
<p> It's 17:00 ! </p>
```

### Modify the context dynamically
In order to change the time that we'll provide to the ShowTime component, we need to give our context a function, that can be used by the consumer to update a value.

Let's just add it to our Provider
```javascript
// utils.TimeProvider.js
...
// This time we initialize a function to set the time
export const TimeContext = createContext({
  time: "",
  setTime: () => {}
});

// We define the setTime function to store the time we'll give it
class TimeProvider extends Component {
  state = {
    time : "17:00",
    setTime: time => this.setState({ time : time })
  };

  render() {
    return (
      <TimeContext.Provider value={this.state}>
        {this.props.children}
      </TimeContext.Provider>
    );
  }
}

export default TimeProvider;
```

And back on our Consumer :

```javascript
// on ShowTime.js
import React from "react";

import { TimeContext } from "./utils/TimeProvider";

export default () => (
  <TimeContext.Consumer>
    {value => <p> It's {value.time} ! </p>}
    <input type="text" value={time} onChange={e => setTime(e.target.value)} />
  </TimeContext.Consumer>
);
```

This will give us an input to modify the time that'll be displayed.

We need to remember using three things :
- Create a Provider that will manage our data shared (also called a Store)
- Create a Consumer that will communicate with the store
- Surrounding our Consumer Component with the Provider created so it can use its data

### More Information

- [React - Context Official Documentation ](https://reactjs.org/docs/context.html)


text:
set -euo pipefail

scripts_dir="$(dirname "$0")"
# git-tag-parser.sh has been shell-checked separately.
# shellcheck source=/dev/null
source "${scripts_dir}"/git-tag-parser.sh
# shellcheck source=/dev/null
source "${scripts_dir}"/docker.sh

versions=$(get_versions "${TAG}")
FUNCTION_TYPE="$2"

# https://github.com/GoogleContainerTools/kpt/issues/1394
# This make it work for npm 7.0.0+
export npm_package_kpt_docker_repo_base="${GCR_REGISTRY}"

case "$1" in
  build)
    for version in ${versions}; do
      docker_build "load" "${FUNCTION_TYPE}" "ts" "${CURRENT_FUNCTION}" "${version}"
    done
    ;;
  push)
    for version in ${versions}; do
      docker_build "push" "${FUNCTION_TYPE}" "ts" "${CURRENT_FUNCTION}" "${version}"
    done
    ;;
  *)
    echo "Usage: $0 {build|push}"
    exit 1
esac


text:
//------------------------------------------------------------------------------
//  Copyright (c) 2014-2016 the original author or authors. All Rights Reserved.
//
//  NOTICE: You are permitted to use, modify, and distribute this file
//  in accordance with the terms of the license agreement accompanying it.
//------------------------------------------------------------------------------

using Robotlegs.Bender.Extensions.EventManagement.API;
using Moq;
using System;
using NUnit.Framework;
using Robotlegs.Bender.Extensions.EventCommand.Support;

namespace Robotlegs.Bender.Extensions.Modularity.Impl
{

	public class ModuleConnectionConfiguratorTest
	{

		/*============================================================================*/
		/* Public Properties                                                          */
		/*============================================================================*/

		public Mock<IEventDispatcher> channelDispatcher = new Mock<IEventDispatcher>();

		public Mock<IEventDispatcher> localDispatcher = new Mock<IEventDispatcher>();

		/*============================================================================*/
		/* Private Properties                                                         */
		/*============================================================================*/

		private ModuleConnectionConfigurator subject;

		/*============================================================================*/
		/* Test Setup and Teardown                                                    */
		/*============================================================================*/

		[SetUp]
		public void Setup()
		{
			subject = new ModuleConnectionConfigurator(localDispatcher.Object, channelDispatcher.Object);
		}

		/*============================================================================*/
		/* Tests                                                                      */
		/*============================================================================*/

		[Test]
		public void Sets_Up_Relaying_From_Local_To_Channel()
		{
			Enum expectedType = SupportEvent.Type.TYPE1;
			subject.RelayEvent(expectedType);
			localDispatcher.Verify (
				_localDispatcher => _localDispatcher.AddEventListener(
					It.Is<Enum>(arg1 => arg1 == expectedType),
					It.Is<Action<IEvent>>( arg2 => arg2 == channelDispatcher.Object.Dispatch)
				),
				Times.Once);
		}

		[Test]
		public void Sets_Up_Receiving_From_Channel_To_Local()
		{
			Enum expectedType = SupportEvent.Type.TYPE1;
			subject.ReceiveEvent(expectedType);
			channelDispatcher.Verify (
				_channelDispatcher => _channelDispatcher.AddEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType),
					It.Is<Action<IEvent>>(arg2 => arg2 == localDispatcher.Object.Dispatch)
				),
				Times.Once);
		}

		[Test]
		public void Suspends_Relaying()
		{
			Enum expectedType = SupportEvent.Type.TYPE1;
			subject.RelayEvent(expectedType);
			subject.Suspend();

			localDispatcher.Verify (
				_localDispatcher => _localDispatcher.RemoveEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType),
					It.IsAny<Action<IEvent>>()
				),
				Times.Once);
		}

		[Test]
		public void Resumes_Relaying()
		{
			Enum expectedType = SupportEvent.Type.TYPE1;
			subject.RelayEvent(expectedType);
			subject.Suspend();
			subject.Resume();

			localDispatcher.Verify (
				_localDispatcher => _localDispatcher.AddEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType),
					It.Is<Action<IEvent>>(arg1 => arg1 == channelDispatcher.Object.Dispatch)
				),
				Times.Exactly(2));
		}

		[Test]
		public void Suspends_Receiving()
		{
			Enum expectedType = SupportEvent.Type.TYPE1;
			subject.ReceiveEvent(expectedType);
			subject.Suspend();

			channelDispatcher.Verify (
				_channelDispatcher => _channelDispatcher.RemoveEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType),
					It.IsAny<Action<IEvent>>()
				),
				Times.Once);
		}

		[Test]
		public void Resumes_Receiving()
		{
			Enum expectedType = SupportEvent.Type.TYPE1;
			subject.ReceiveEvent(expectedType);
			subject.Suspend();
			subject.Resume();

			channelDispatcher.Verify (
				_channelDispatcher => _channelDispatcher.AddEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType),
					It.Is<Action<IEvent>>(arg2 => arg2 == localDispatcher.Object.Dispatch)
				),
				Times.Exactly(2));
		}

		[Test]
		public void Removes_Listeners_After_Destruction()
		{
			Enum expectedType1 = SupportEvent.Type.TYPE1;
			Enum expectedType2 = SupportEvent.Type.TYPE2;

			subject.RelayEvent(expectedType1);
			subject.ReceiveEvent(expectedType2);
			subject.Destroy();

			localDispatcher.Verify (
				_localDispatcher => _localDispatcher.RemoveEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType1),
					It.IsAny<Action<IEvent>>()
				),
				Times.Once);

			channelDispatcher.Verify (
				_channelDispatcher => _channelDispatcher.RemoveEventListener(
					It.Is<Enum> (arg1 => arg1 == expectedType2),
					It.IsAny<Action<IEvent>>()
				),
				Times.Once);
		}
	}
}