<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~~~~~~licensing~~~~~~
  support
  ==========
  Copyright (C) 2020 - 2021 EmDev LLC
  ==========
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
  
       http://www.apache.org/licenses/LICENSE-2.0
  
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
  ~~~~~~/licensing~~~~~~
  -->

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
           xmlns:camelcxf="http://camel.apache.org/schema/blueprint/cxf"
           xmlns:cxf="http://cxf.apache.org/blueprint/core"
           xmlns:esbExchange="http://www.entaxy.ru/connector/universal/system/1.0"
           xmlns:soap-type="http://www.entaxy.ru/ExchangeTypes/1.0"
           xsi:schemaLocation="
             http://www.osgi.org/xmlns/blueprint/v1.0.0 https://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd
             http://cxf.apache.org/blueprint/core http://cxf.apache.org/schemas/blueprint/core.xsd
             ">

    <cm:property-placeholder persistent-id="uniform.service.support" update-strategy="reload">
        <cm:default-properties>
            <cm:property name="active.mode.dev" value="false"/>
            <cm:property name="test.empty.rate" value="20"/>

            <cm:property name="redelivery.maximumRedeliveries" value="2"/>
            <cm:property name="redelivery.deadLetterQueue" value="revert.message.dead"/>
            <cm:property name="acknowledge.completion.timeout" value="600000"/>
            <cm:property name="acknowledge.aggregation.repository" value="jdbcAggregationRepository"/>

            <cm:property name="active.validation" value="false"/>
            <cm:property name="active.username" value="Администратор"/>
            <cm:property name="active.password" value=""/>
            <cm:property name="test.empty.rate" value="20"/>
        </cm:default-properties>
    </cm:property-placeholder>

    <cm:property-placeholder persistent-id="uniform.service.ignite" update-strategy="reload"
                             placeholder-prefix="$ignite{">
        <cm:default-properties>
            <cm:property name="ignite.work.directory.path" value="/mnt/ignite"/>
            <cm:property name="ignite.backups" value="2"/>
            <cm:property name="ignite.addresses" value="127.0.0.1:47500,127.0.0.1:47501"/>
        </cm:default-properties>
    </cm:property-placeholder>

    <!--    авторизация? -->
    <camelcxf:cxfEndpoint id="soap-active"
                          address="/active_connector_test_consumer"
                          endpointName="esbExchange:esbExchangeSOAP"
                          serviceName="esbExchange:esbExchange"
                          wsdlURL="ru/entaxy/esb/platform/runtime/modules/uniform-service/wsdl/soap-active.wsdl">
        <camelcxf:properties>
            <entry key="dataFormat" value="PAYLOAD"/>
            <entry key="mtom-enabled" value="false"/>
            <entry key="schema-validation-enabled" value="${active.validation}"/>
            <entry key="username" value="${active.username}"/>
            <entry key="password" value="${active.password}"/>
        </camelcxf:properties>
    </camelcxf:cxfEndpoint>

    <reference id="dataSource" interface="javax.sql.DataSource" filter="(osgi.jndi.service.name=entaxy.esb.cache)"
               availability="mandatory"/>

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="jdbcAggregationRepository"
          class="ru.entaxy.esb.system.common.aggregation.repo.JdbcAggregationRepository">
        <property name="repositoryName" value="receive_acknowledge"/>
        <property name="transactionManager" ref="txManager"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="maximumRedeliveries" value="${redelivery.maximumRedeliveries}"/>
        <property name="deadLetterUri" value="entaxy-broker:queue:entaxy.${redelivery.deadLetterQueue}"/>
    </bean>

    <bean id="postgresAggregationRepository"
          class="ru.entaxy.esb.system.common.aggregation.repo.PostgresAggregationRepository">
        <property name="repositoryName" value="receive_acknowledge"/>
        <property name="transactionManager" ref="txManager"/>
        <property name="dataSource" ref="dataSource"/>
        <property name="maximumRedeliveries" value="${redelivery.maximumRedeliveries}"/>
        <property name="deadLetterUri" value="entaxy-broker:queue:entaxy.${redelivery.deadLetterQueue}"/>
    </bean>

    <bean id="igniteAggregationRepository"
          class="ru.entaxy.esb.system.common.aggregation.repo.IgniteAggregationRepository">
        <property name="bundleContext" ref="blueprintBundleContext"/>
        <property name="workDirectory" value="$ignite{ignite.work.directory.path}"/>
        <property name="backups" value="$ignite{ignite.backups}"/>
        <property name="maximumRedeliveries" value="${redelivery.maximumRedeliveries}"/>
        <property name="deadLetterUri" value="entaxy-broker:queue:entaxy.${redelivery.deadLetterQueue}"/>
        <property name="addresses" value="$ignite{ignite.addresses}"/>
    </bean>

    <reference id="hazelcastInstance" interface="com.hazelcast.core.HazelcastInstance" timeout="30000"/>

    <bean id="timeoutAwareAggregationStrategy"
          class="ru.entaxy.esb.system.common.aggregation.TimeoutAwareAggregationStrategyImpl">
        <argument index="0" value="NTX_Acknowledge"/>
    </bean>

    <bean id="aggregationProcessor" class="ru.entaxy.esb.system.common.aggregation.AggregationProcessorBean"
          init-method="init" destroy-method="doStop" activation="eager">
        <property name="camelContext" ref="soap-connector-context"/>
        <property name="aggregationRepositoryRef" value="${acknowledge.aggregation.repository}"/>
        <property name="aggregationStrategyRef" value="timeoutAwareAggregationStrategy"/>
        <property name="completionTimeout" value="${acknowledge.completion.timeout}"/>
        <property name="aggregateExpression" value="${headers.X-SystemUuid}:${headers.ENTAXY_AcknowledgeMsgID}"/>
        <property name="toDefinition" value="direct-vm:uniform-service-common-revert-no-acknowledge-messages?block=true&amp;timeout=60000"/>

        <property name="hazelcastInstance" ref="hazelcastInstance"/>
    </bean>

	<reference id="entaxy-broker" interface="org.apache.camel.Component"
				filter="(connection.name=entaxy-broker)"/>

    <camelContext id="soap-connector-context" xmlns="http://camel.apache.org/schema/blueprint"
                  errorHandlerRef="commonErrorHandler">

        <errorHandler id="commonErrorHandler" redeliveryPolicyRef="noRedelivery"
                      type="DeadLetterChannel" deadLetterUri="direct-vm:commonErrorEndpoint"/>
        <redeliveryPolicyProfile id="noRedelivery" disableRedelivery="true"/>

        <route id="transform-body">
            <from uri="direct-vm:uniform-service-transform-body"/>
            <transform>
                <simple>
                    ${body.replace('content xsi:type=', 'content xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type=')}
                </simple>
            </transform>
        </route>

        <route id="save-acknowledge">
            <from uri="direct-vm:uniform-service-common-save-acknowledge"/>
            <setHeader name="NTX_HeadersXMLStr">
                <simple resultType="String">${headers.NTX_HeadersXML}</simple>
            </setHeader>
            <to uri="entaxy-broker:queue:entaxy.uniform.service.exchange.aggregate?exchangePattern=InOnly&amp;asyncConsumer=true"/>

            <log message="Message ${headers.ENTAXY_AcknowledgeMsgID} from ${headers.NTX_OutQueue} saved in acknowledge"
                 loggingLevel="DEBUG"/>
        </route>

        <route id="aggregation">
            <from uri="entaxy-broker:queue:entaxy.uniform.service.exchange.aggregate?concurrentConsumers=50&amp;asyncConsumer=true&amp;acknowledgementModeName=CLIENT_ACKNOWLEDGE"/>
            <to uri="bean:aggregationProcessor"/>
        </route>

        <route id="revert-no-acknowledge-messages">
            <from uri="direct-vm:uniform-service-common-revert-no-acknowledge-messages"/>
            <choice>
                <when>
                    <simple>${headers.NTX_Acknowledge} == true</simple>
                    <log message="No acknowledge for ${headers.ENTAXY_AcknowledgeMsgID}; system queue: ${headers.NTX_OutQueue}"
                         loggingLevel="DEBUG"/>
                    <toD uri="entaxy-broker:queue:${headers.NTX_OutQueue}?exchangePattern=InOnly"/>
                </when>
            </choice>
        </route>

        <route id="receive-acknowledge">
            <from uri="direct-vm:uniform-service-receive-acknowledge"/>
            <log message="Receive acknowledge with ackId ${headers.ENTAXY_AcknowledgeMsgID}" loggingLevel="INFO"/>
            <setHeader name="NTX_AckMessage">
                <simple>true</simple>
            </setHeader>
            <to uri="entaxy-broker:queue:entaxy.uniform.service.exchange.aggregate?exchangePattern=InOnly&amp;asyncConsumer=true"/>

            <log message="Message ${headers.ENTAXY_AcknowledgeMsgID} acknowledge received" loggingLevel="DEBUG"/>
        </route>

        <!--ACTIVE-->
        <route id="send-package-active" streamCache="true">
            <from uri="direct-vm:uniform-service-send-package-active"/>
            <!--здесь не происходит отправка по адресу, указанному в cxf, так как в коннекторе проставляется заголовок
            CamelDestinationOverrideUrl, который перетирает адрес, указанный в cxf-->
            <to uri="cxf:bean:soap-active"/>
        </route>

        <!--        Test case-->
        <route id="soap-connector-active" streamCache="true" autoStartup="{{active.mode.dev}}">
            <from uri="cxf:bean:soap-active"/>
            <setHeader name="ENTAXY_EndpointName">
                <simple>uniform-service</simple>
            </setHeader>
            <to uri="direct-vm:uniform-service-soap-active?block=true&amp;timeout=60000"/>
        </route>

        <!--Test case for active connector -->
        <route id="cxf-test-consumer" streamCache="true">
            <from uri="direct-vm:uniform-service-soap-active"/>

            <choice>
                <when>
                    <simple>${headers.operationName} == 'GetPackets'</simple>
                    <setHeader name="currSeconds">
                        <simple resultType="Integer">${date:now:s}</simple>
                    </setHeader>
                    <setHeader name="ENTAXY_EmptyContent">
                        <simple resultType="Boolean">${headers.currSeconds} > {{test.empty.rate}}</simple>
                    </setHeader>
                    <log message="CXF-TEST-CONSUMER: EmptyContent=${headers.ENTAXY_EmptyContent}"
                         loggingLevel="INFO"/>
                    <setHeader name="ENTAXY_Source">
                        <constant>s1</constant>
                    </setHeader>
                    <setHeader name="ENTAXY_Destination">
                        <simple>${headers.NTX_SystemId}</simple>
                    </setHeader>
                    <setHeader name="ENTAXY_MessageUUID">
                        <constant>00000000-0000-0000-0000-000000000000</constant>
                    </setHeader>

                    <setHeader name="ENTAXY_AcknowledgeMsgID">
                        <constant>00000000-0000-0000-0000-000000000000</constant>
                    </setHeader>
                    <to uri="xslt:ru/entaxy/esb/platform/runtime/modules/uniform-service/xslt/GetPacketResponseTest.xsl"/>
                </when>
                <when>
                    <simple>${headers.operationName} == 'ConfirmGettingPackets'</simple>
                    <removeHeaders pattern="NTX_.+|ENTAXY_.+"/>
                    <setBody>
                        <simple><![CDATA[<test/>]]></simple>
                    </setBody>
                    <setHeader name="NTX_Status">
                        <constant>200</constant>
                    </setHeader>
                    <setHeader name="NTX_UUID">
                        <constant>00000000-0000-0000-0000-000000000000</constant>
                    </setHeader>
                    <to uri="xslt:ru/entaxy/esb/platform/runtime/modules/uniform-service/xslt/ConfirmGettingPacketResponse.xsl?failOnNullBody=false"/>
                </when>
                <when>
                    <simple>${headers.operationName} == 'PutPackets'</simple>
                    <removeHeaders pattern="NTX_.+|ENTAXY_.+"/>
                    <setBody>
                        <simple><![CDATA[<test/>]]></simple>
                    </setBody>
                    <to uri="xslt:ru/entaxy/esb/platform/runtime/modules/uniform-service/xslt/PutPacketResponse.xsl?failOnNullBody=false"/>
                </when>
                <otherwise>
                    <log message="CXF-TEST-CONSUMER: Unknown operation ${headers.operationName}" loggingLevel="ERROR"/>
                </otherwise>
            </choice>
        </route>
    </camelContext>
</blueprint>
