<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~~~~~~licensing~~~~~~
  support
  ==========
  Copyright (C) 2020 - 2024 EmDev LLC
  ==========
  You may not use this file except in accordance with the License Terms of the Copyright
  Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
  rights to the Software and any copies are the property of the Copyright Holder. Unless
  it is explicitly allowed the Copyright Holder, the User is prohibited from using the
  Software for commercial purposes to provide services to third parties.
  
  The Copyright Holder hereby declares that the Software is provided on an "AS IS".
  Under no circumstances does the Copyright Holder guarantee or promise that the
  Software provided by him will be suitable or not suitable for the specific purposes
  of the User, that the Software will meet all commercial and personal subjective
  expectations of the User, that the Software will work properly, without technical
  errors, quickly and uninterruptedly.
  
  Under no circumstances shall the Copyright Holder or its Affiliates is not liable
  to the User for any direct or indirect losses of the User, his expenses or actual
  damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
  or damage to data, property, etc.
  ~~~~~~/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>

    <!--    авторизация? -->
    <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>
	
	<reference id="igniteInstance" interface="org.apache.ignite.Ignite" availability="mandatory"/>
	
    <bean id="igniteAggregationRepository"
          class="ru.entaxy.esb.system.common.aggregation.repo.IgniteAggregationRepository">
        <property name="bundleContext" ref="blueprintBundleContext"/>
        <property name="ignite" ref="igniteInstance"/>
        <property name="maximumRedeliveries" value="${redelivery.maximumRedeliveries}"/>
        <property name="deadLetterUri" value="entaxy-broker:queue:entaxy.${redelivery.deadLetterQueue}"/>
    </bean>

    <bean id="jmsExtension" class="ru.entaxy.platform.core.support.runtime.camel.aggregation.JmsCamelAggregateExtension"/>

    <bean id="aggregateProcessor" class="ru.entaxy.esb.system.common.aggregation.hazelcast.DisconnectedMembershipListener">
        <property name="hazelcastInstance" ref="hazelcastInstance"/>
    </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>

	<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="${headers.NTX_loggingKey} 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"/>
            <aggregate id="aggregateProcessor" strategyRef="timeoutAwareAggregationStrategy"
                       aggregationRepositoryRef="{{acknowledge.aggregation.repository}}"
                       discardOnCompletionTimeout="false" completionSize="2">
                <correlationExpression>
                    <simple>${headers.X-SystemUuid}:${headers.ENTAXY_AcknowledgeMsgID}</simple>
                </correlationExpression>
                <completionTimeoutExpression>
                    <simple>{{acknowledge.completion.timeout}}</simple>
                </completionTimeoutExpression>

                <to uri="direct-vm:uniform-service-common-revert-no-acknowledge-messages?block=true&amp;timeout=60000"/>
            </aggregate>
        </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="${headers.NTX_loggingKey} 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="${headers.NTX_loggingKey} 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="${headers.NTX_loggingKey} 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="${headers.NTX_loggingKey} CXF-TEST-CONSUMER: EmptyContent=${headers.ENTAXY_EmptyContent}"
                         loggingLevel="INFO"/>
                    <setHeader name="ENTAXY_Source">
                        <constant>system-1c</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="${headers.NTX_loggingKey} CXF-TEST-CONSUMER: Unknown operation ${headers.operationName}" loggingLevel="ERROR"/>
                </otherwise>
            </choice>
        </route>
    </camelContext>
</blueprint>
