[#ftl attributes={"generated.type":"blueprint"}]
[#--

    ~~~~~~licensing~~~~~~
    connector
    ==========
    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~~~~~~

--]
<?xml version="1.0" encoding="UTF-8"?>
<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: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">

    <cm:property-placeholder persistent-id="uniform.service.support"
                             update-strategy="reload">
        <cm:default-properties>
            <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="bus.id" value="FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF"/>
            <cm:property name="get.destination" value=""/>
            <cm:property name="test.empty.rate" value="20"/>
            <cm:property name="acknowledge.aggregation.repository" value="jdbcAggregationRepository"/>
            <cm:property name="error.system.name" value="error"/>
        </cm:default-properties>
    </cm:property-placeholder>

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

    <bean id="soapOutConnector" class="ru.entaxy.esb.system.profile.commons.connectors.out.DirectVMOutConnectorImpl">
        <property name="endpointName" value="uniform-passive-service"/>
        <property name="systemName" value="[=systemName]"/>
        <property name="params">
            <map>
                <entry key="role" value="default"/>
                <entry key="type" value="uniform-service"/>
                <entry key="subtype" value="passive"/>
            </map>
        </property>
    </bean>

    <service ref="soapOutConnector" auto-export="interfaces">
        <service-properties>
            <entry key="endpointName" value="uniform-passive-service"/>
            <entry key="systemName" value="[=systemName]"/>
        </service-properties>
    </service>

    <bean id="uuidGenerator" class="java.util.UUID" scope="prototype" factory-method="randomUUID"/>

    <bean id="headersConverter" class="ru.entaxy.esb.system.common.util.HeadersConverter">
        <property name="namespace" value="http://www.entaxy.ru/ExchangeTypes/1.0"/>
        <property name="customHeaders" value="NTX_CustomHeaders"/>
        <property name="customHeaderPrefix" value="NTX_UNIFORM_EXCHANGE_CustomHeader"/>
    </bean>

    <bean id="headerMergeAggregator" class="ru.entaxy.esb.system.common.aggregation.HeaderMergeAggregatorImpl"/>

    <camelContext id="uniform-service-out-connector-[=systemName]-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="uniform-passive-service-out-connector">
            <from uri="direct-vm:uniform-passive-service-out-connector-[=systemName]"/>
            <choice>
                <when>
                    <simple>${headers.operationName} == 'ConfirmGettingPackets'</simple>
                    <to uri="direct:confirm-packets"/>
                </when>
                <when>
                    <simple>${headers.operationName} == 'GetPackets'</simple>
                    <to uri="direct:get-packets"/>
                </when>
                <otherwise>
                    <to uri="direct:sent-message"/>
                </otherwise>
            </choice>
        </route>

        <route id="sent-message">
            <from uri="direct:sent-message"/>
            <log message="Message ${headers} send to system" loggingLevel="TRACE"/>
            <when>
                <simple>${headers.ENTAXY_Priority} == null || ${headers.ENTAXY_Priority} == ""</simple>
                <setHeader name="ENTAXY_Priority">
                    <simple resultType="Integer">4</simple>
                </setHeader>
            </when>
            <setHeader name="NTX_OutQueue">
                <simple>entaxy.uniform.service.exchange.[=systemName]</simple>
            </setHeader>
            <removeHeaders pattern="X-.+"/>
            <toD uri="entaxy-broker:queue:${headers.NTX_OutQueue}?priority=${headers.ENTAXY_Priority}"/>
        </route>

        <route id="confirm-packets">
            <from uri="direct:confirm-packets"/>

            <setHeader name="NTX_UuidCount">
                <xpath resultType="Integer">count(/soap-type:uuids/soap-type:uuid)</xpath>
            </setHeader>
            <when>
                <simple>${headers.NTX_UuidCount} &gt; 1</simple>
                <throwException exceptionType="java.lang.UnsupportedOperationException"
                                message="Not supported more then 1 uuid"/>
            </when>
            <setBody>
                <xpath resultType="org.w3c.dom.Document">/soap-type:uuids/soap-type:uuid[1]</xpath>
            </setBody>

            <setHeader name="ENTAXY_AcknowledgeMsgID">
                <xpath resultType="String">/soap-type:uuid/text()</xpath>
            </setHeader>
            <to uri="direct-vm:uniform-service-receive-acknowledge"/>
            <setHeader name="NTX_UUID">
                <simple>${headers.ENTAXY_AcknowledgeMsgID}</simple>
            </setHeader>
            <to uri="xslt:ru/entaxy/esb/platform/runtime/modules/uniform-service/xslt/ConfirmGettingPacketResponse.xsl?failOnNullBody=false"/>
            <removeHeaders pattern="Authorization|breadcrumbId|NTX_.+|ENTAXY_.+"/>
        </route>

        <route id="get-packets">
            <from uri="direct:get-packets"/>
            <setHeader name="NTX_SystemId">
                <xpath>/soap-type:getPacketsRequest/soap-type:destination/soap-type:id/text()</xpath>
            </setHeader>
            <choice>
                <when>
                    <simple>${headers.NTX_SystemId} == ''</simple>
                    <setHeader name="NTX_SystemId">
                        <simple>${headers.X-SystemName}</simple>
                    </setHeader>
                </when>
                <when>
                    <simple>${headers.NTX_SystemId} != ${headers.X-SystemName}</simple>
                    <log message="Source name header and SystemId is not equals!" loggingLevel="WARN"/>
                    <throwException exceptionType="java.security.AccessControlException" message="Unauthorized"/>
                </when>
            </choice>

            <setHeader name="NTX_OutQueue">
                <simple>entaxy.uniform.service.exchange.[=systemName]</simple>
            </setHeader>
            <setHeader name="NTX_LimitCount">
                <xpath resultType="Integer">/soap-type:getPacketsRequest/soap-type:limitCount/text()</xpath>
            </setHeader>
            <setHeader name="NTX_LimitSize">
                <xpath resultType="Integer">/soap-type:getPacketsRequest/soap-type:limitSize/text()</xpath>
            </setHeader>
            <when>
                <simple>${headers.NTX_LimitCount} &gt; 1 || ${headers.NTX_LimitSize} &gt; 0</simple>
                <throwException exceptionType="java.lang.UnsupportedOperationException"
                                message="Not supported limitation mode! Only default values."/>
            </when>

            <log message="Fetch From JMS queue: ${headers.NTX_OutQueue}; SystemId=${headers.NTX_SystemId}"
                 loggingLevel="INFO"/>

            <setBody>
                <simple>${null}</simple>
            </setBody>

            <pollEnrich timeout="0" strategyRef="headerMergeAggregator">
                <simple>entaxy-broker:queue:${headers.NTX_OutQueue}</simple>
            </pollEnrich>

            <choice>
                <when>
                    <simple>${body} == null</simple>
                    <log message="No Messages" loggingLevel="WARN"/>
                    <setHeader name="NTX_Status">
                        <constant>204</constant>
                    </setHeader>
                    <to uri="xslt:ru/entaxy/esb/platform/runtime/modules/uniform-service/xslt/GetPacketResponse.xsl?failOnNullBody=false"/>
                    <removeHeaders pattern="NTX_Status"/>
                </when>
                <otherwise>
                    <log message="Get Message ${body}" loggingLevel="DEBUG"/>
                    <setHeader name="ENTAXY_AcknowledgeMsgID">
                        <simple>${bean:uuidGenerator.toString}</simple>
                    </setHeader>
                    <to uri="direct-vm:uniform-service-common-save-acknowledge?block=true&amp;timeout=70000"/>

                    <bean ref="headersConverter" method="json2xml"/>
                    <when>
                        <simple>${headers.CamelJms_IntMessageType} == 'String'</simple>
                        <bean beanType="org.apache.commons.lang3.StringEscapeUtils"
                              method="escapeXml(${body})"/>
                    </when>
                    <setBody>
                        <simple><![CDATA[<body>${body}</body>]]></simple>
                    </setBody>

                    <to uri="xslt:ru/entaxy/esb/platform/runtime/modules/uniform-service/xslt/GetPacketResponse.xsl"/>
                    <to uri="direct-vm:uniform-service-transform-body?block=true&amp;timeout=30000"/>
                    <log message="Send message ${headers.ENTAXY_MessageUUID} for ${headers.NTX_SystemId} ackId ${headers.ENTAXY_AcknowledgeMsgID}"
                         loggingLevel="INFO"/>
                    <removeHeaders pattern="JMS.+|NTX_.+|ENTAXY_.+"/>
                </otherwise>
            </choice>
        </route>
    </camelContext>

</blueprint>
