diff --git a/platform-backward-compat/LICENSE.txt b/platform-backward-compat/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform-backward-compat/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform-backward-compat/blueprint-generator-service/LICENSE.txt b/platform-backward-compat/blueprint-generator-service/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform-backward-compat/blueprint-generator-service/pom.xml b/platform-backward-compat/blueprint-generator-service/pom.xml new file mode 100644 index 00000000..317a3baf --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/pom.xml @@ -0,0 +1,76 @@ + + 4.0.0 + + ru.entaxy.platform + platform-backward-compat + 1.10.0 + + ru.entaxy.platform.backward-compat + blueprint-generator-service + bundle + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: BLUEPRINT GENERATOR SERVICE + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: BLUEPRINT GENERATOR SERVICE + + + ru.entaxy.platform.core.blueprint.generator + + + + + org.apache.karaf + org.apache.karaf.util + + + + org.osgi + org.osgi.service.component.annotations + 1.4.0 + compile + + + + + ru.entaxy.esb.platform.runtime.base.connecting.generator + + generator-api + ${project.version} + + + + ru.entaxy.esb.platform.runtime.base.connecting.generator + + generator-factory + ${project.version} + + + + + + + org.apache.felix + maven-bundle-plugin + ${maven-bundle-plugin.version} + true + + + true + <_dsannotations>* + + + + + + + diff --git a/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/Blueprint.java b/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/Blueprint.java new file mode 100644 index 00000000..ef707c28 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/Blueprint.java @@ -0,0 +1,69 @@ +/*- + * ~~~~~~licensing~~~~~~ + * blueprint-generator + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.blueprint.generator; + +import java.util.HashMap; +import java.util.Map; + +public class Blueprint { + + private String name; + private byte[] body; + + private Map properties = new HashMap<>(); + + public Blueprint(String name, byte[] body) { + this.name = name; + this.body = body; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public byte[] getBody() { + return body; + } + + public void setBody(byte[] body) { + this.body = body; + } + + public Map getProperties() { + return properties; + } + + @Override + public String toString() { + return "Blueprint{" + + "name='" + name + '\'' + + '}'; + } +} diff --git a/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/BlueprintGenerator.java b/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/BlueprintGenerator.java new file mode 100644 index 00000000..f7b5d8f2 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/BlueprintGenerator.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * blueprint-generator + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.blueprint.generator; + +import java.net.URL; +import java.util.Map; + +public interface BlueprintGenerator { + + Blueprint createBlueprint(URL templateUrl, String templateName, String systemName, Map params) + throws Exception; + + Blueprint createBlueprint(String templateName, String systemName, Map params) + throws Exception; +} diff --git a/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/BlueprintGeneratorImpl.java b/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/BlueprintGeneratorImpl.java new file mode 100644 index 00000000..2ee107af --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/java/ru/entaxy/platform/core/blueprint/generator/BlueprintGeneratorImpl.java @@ -0,0 +1,113 @@ +/*- + * ~~~~~~licensing~~~~~~ + * blueprint-generator + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.blueprint.generator; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.base.generator.template.Template; +import ru.entaxy.base.generator.template.TemplateAwareGenerator; +import ru.entaxy.base.generator.template.TemplateImpl; +import ru.entaxy.base.generator.template.TemplateService; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generator; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.factory.GeneratorFactory; + +@Component(service = {BlueprintGenerator.class}, immediate = true) +public class BlueprintGeneratorImpl implements BlueprintGenerator { + + private static final Logger LOG = LoggerFactory.getLogger(BlueprintGeneratorImpl.class); + private static final String SYSTEM_NAME = "systemName"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + protected TemplateService templateService; + + @Override + public Blueprint createBlueprint(URL templateUrl, String templateName, String systemName, Map params) + throws Exception { + TemplateImpl template = new TemplateImpl(); + template.setTemplateName(templateName); + template.setTemplateLocation(templateUrl.toString()); + template.setType("ftl"); + return createBlueprintWithTemplate(template, systemName, params); + } + + @Override + public Blueprint createBlueprint(String templateName, String systemName, Map params) throws Exception { + Template template = templateService.getTemplateById(templateName); + if (template == null) { + LOG.error("Template not found: [{}]", templateName); + // TODO throw exception + return null; + } + return createBlueprintWithTemplate(template, systemName, params); + } + + protected Blueprint createBlueprintWithTemplate(ru.entaxy.base.generator.template.Template template, + String systemName, Map params) throws Exception { + TemplateAwareGenerator generator = GeneratorFactory.createGenerator(template); + if (generator == null) { + LOG.error("Generator not found for template: [{}]", template.getId()); + // TODO throw exception + return null; + } + addSystemParam(params, systemName); + Map parameters = new HashMap<>(); + parameters.putAll(params); + Generated result = generator.generate(template,parameters); + if ((result == null) || (result.getObject() == null)) { + LOG.error("Generator returned null for template: [{}]", template.getId()); + // TODO throw exception + return null; + } + if (!Generated.GENERATED_TYPE_BLUEPRINT.equals(result.getType())) { + LOG.error("Generator returned type [{}], while [{}] is expected for template: [{}]" + , result.getType() + , Generated.GENERATED_TYPE_BLUEPRINT + , template.getId()); + // TODO throw exception + return null; + } + Blueprint blueprint = new Blueprint(template.getTemplateName(), result.getObject().toString().getBytes()); + blueprint.getProperties().putAll(result.getProperties()); + blueprint.getProperties().put("template.name", template.getTemplateName()); + blueprint.getProperties().put("template.id", template.getId()); + blueprint.getProperties().put("template.type", template.getType()); + return blueprint; + } + + private void addSystemParam(Map params, String systemName) { + params.put(SYSTEM_NAME, systemName); + } + +} diff --git a/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/bridge-profile.ftl b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/bridge-profile.ftl new file mode 100644 index 00000000..f8ec2a15 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/bridge-profile.ftl @@ -0,0 +1,39 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + system:[=systemName] + + + + + diff --git a/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/default-route.ftl b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/default-route.ftl new file mode 100644 index 00000000..49a697f3 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/default-route.ftl @@ -0,0 +1,48 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + + + + + + + + + + ${headers.ENTAXY_Destination} == 'nsi' + && ${headers.ENTAXY_DestinationType} == null + + + true + + + + + + + ${headers.ENTAXY_DestinationType} == 'system.name' + + + + ${headers.ENTAXY_DestinationType} == 'system-group.name' + + + + ${headers.ENTAXY_DestinationType} == 'queue.name' + + + + ${headers.ENTAXY_DestinationType} == 'topic.name' + + + + + + + + + diff --git a/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/metadata.json b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/metadata.json new file mode 100644 index 00000000..5f01bc16 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/metadata.json @@ -0,0 +1,23 @@ +{ + "templates":[ + { + "id":"bridge-profile", + /* by default: + "name":"{id}", + "type":"ftl", + "path":"DEFAULT_PATH" + "filename":"{id}" + "fullname":"{id}.{type}", + */ + "description":"Ftl template for bridge profile" + }, + { + "id":"default-route", + "description":"Ftl template for default route from profile" + }, + { + "id":"profile", + "description":"Ftl template for system profile" + } + ] +} \ No newline at end of file diff --git a/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/profile.ftl b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/profile.ftl new file mode 100644 index 00000000..8e555cd9 --- /dev/null +++ b/platform-backward-compat/blueprint-generator-service/src/main/resources/ru/entaxy/templates/profile.ftl @@ -0,0 +1,75 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${headers.NTX_NextPoint} != null + + ${headers.NTX_NextPoint} + + + + + + + + + + + + + +[#-- --] +[#-- --] +[#-- ${headers.NTX_Origin} == null--] +[#-- --] +[#-- --] +[#-- --] + + + + diff --git a/platform-backward-compat/connector-storage/LICENSE.txt b/platform-backward-compat/connector-storage/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform-backward-compat/connector-storage/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform-backward-compat/connector-storage/pom.xml b/platform-backward-compat/connector-storage/pom.xml new file mode 100644 index 00000000..6ad6e267 --- /dev/null +++ b/platform-backward-compat/connector-storage/pom.xml @@ -0,0 +1,28 @@ + + + 4.0.0 + + + ru.entaxy.platform + platform-backward-compat + 1.10.0 + + + ru.entaxy.platform.backward-compat + connector-storage + bundle + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: CONNECTOR :: STORAGE + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: CONNECTOR :: STORAGE + + + ru.entaxy.platform.base.objects.connector.storage + + + + + ru.entaxy.esb.system.registry.connector + connector-impl + ${project.version} + + + diff --git a/platform-backward-compat/connector-storage/src/main/java/ru/entaxy/platform/base/objects/connector/storage/ConnectorObjectStorage.java b/platform-backward-compat/connector-storage/src/main/java/ru/entaxy/platform/base/objects/connector/storage/ConnectorObjectStorage.java new file mode 100644 index 00000000..943c7ba4 --- /dev/null +++ b/platform-backward-compat/connector-storage/src/main/java/ru/entaxy/platform/base/objects/connector/storage/ConnectorObjectStorage.java @@ -0,0 +1,113 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connector-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.base.objects.connector.storage; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import ru.entaxy.esb.system.connector.impl.ConnectorService; +import ru.entaxy.esb.system.jpa.SystemService; +import ru.entaxy.esb.system.management.bundle.jpa.entity.BundleEntity; +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.objects.EntaxyObjectStorage; + +@Component(service = EntaxyObjectStorage.class, immediate = true) +public class ConnectorObjectStorage implements EntaxyObjectStorage { + + private static final Logger log = LoggerFactory.getLogger(ConnectorObjectStorage.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY, collectionType = CollectionType.SERVICE) + protected ConnectorService connectorService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, collectionType = CollectionType.SERVICE) + protected SystemService systemService; + + @SuppressWarnings("serial") + protected Map fieldMap = new HashMap<>() { + { + put("name", "objectId"); + put("version", "artifact.version"); + } + }; + + protected Map fieldBundleMap = new HashMap<>() { + { + put("name", "bundleId"); + put("type", "artifact.type"); + put("status", "artifact.status"); + put("version", "artifact.version"); + put("url", "bundleLocation"); + } + }; + + @Override + public String[] getObjectTypes() { + return new String[] {EntaxyObject.OBJECT_TYPES.CONNECTOR}; + } + + @Override + public Object store(Map data) { + + JsonObject jsonObject = new JsonObject(); + Gson gson = new Gson(); + + for (Map.Entry entry : fieldMap.entrySet()) { + if (data.containsKey(entry.getValue())) + jsonObject.add(entry.getKey(), gson.toJsonTree(data.get(entry.getValue()))); + } + JsonObject bundleJsonObject = new JsonObject(); + for (Map.Entry entry : fieldBundleMap.entrySet()) { + if (data.containsKey(entry.getValue())) + bundleJsonObject.add(entry.getKey(), gson.toJsonTree(data.get(entry.getValue()))); + } + + log.debug("JSON :: " + jsonObject.toString()); + ru.entaxy.esb.system.connector.entity.Connector connector = + gson.fromJson(jsonObject, ru.entaxy.esb.system.connector.entity.Connector.class); + connector.setTemplateName(data.get("factoryId").toString()); + connector.setCreateDate(new Date()); + connector.setCreatedBy("admin"); + + log.debug("JSON Bundle :: " + bundleJsonObject.toString()); + BundleEntity bundleEntity = gson.fromJson(bundleJsonObject, BundleEntity.class); + connector.setBundleEntity(bundleEntity); + ru.entaxy.esb.system.jpa.entity.System system = systemService.getByUuid(data.get("profile").toString()); + connectorService.addNewConnector(system, connector); + + return null; + } +} diff --git a/platform-backward-compat/pom.xml b/platform-backward-compat/pom.xml new file mode 100644 index 00000000..fbcc54bb --- /dev/null +++ b/platform-backward-compat/pom.xml @@ -0,0 +1,47 @@ + + + 4.0.0 + + ru.entaxy.esb + root + 1.10.0 + + ru.entaxy.platform + platform-backward-compat + pom + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY + + + + com.google.code.gson + gson + + + org.osgi + org.osgi.service.component.annotations + + + org.apache.felix + org.apache.felix.scr + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + ru.entaxy.esb.platform.runtime.base.objects-base + objects-core + ${project.version} + + + + + blueprint-generator-service + profile-management-service-adapters + connector-storage + profile-storage + + + diff --git a/platform-backward-compat/profile-management-service-adapters/LICENSE.txt b/platform-backward-compat/profile-management-service-adapters/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform-backward-compat/profile-management-service-adapters/pom.xml b/platform-backward-compat/profile-management-service-adapters/pom.xml new file mode 100644 index 00000000..67c94d15 --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/pom.xml @@ -0,0 +1,131 @@ + + + 4.0.0 + + + ru.entaxy.platform + platform-backward-compat + 1.10.0 + + + ru.entaxy.platform.backward-compat + profile-management-service-adapters + bundle + + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: PROFILE MANAGEMENT SERVICE ADAPTERS + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: PROFILE MANAGEMENT SERVICE ADAPTERS + + + + + + + ru.entaxy.esb.platform.core.management.profile.adapters + + + + + + + org.osgi + org.osgi.service.component.annotations + 1.4.0 + compile + + + org.apache.felix + org.apache.felix.scr + 2.1.20 + + + + ru.entaxy.esb.platform.runtime.base + + base-support + ${project.version} + + + + ru.entaxy.esb.platform.runtime.core.management + profile-management + ${project.version} + + + ru.entaxy.esb.system.management.profile.manager + profile-manager + ${project.version} + + + ru.entaxy.esb.system.registry.systems + system-api + ${project.version} + + + ru.entaxy.esb.system.management + system-management-api + ${project.version} + + + + ru.entaxy.esb.system.management.connector.manager + + connector-manager + ${project.version} + + + ru.entaxy.esb.system.management.bundle.jpa + bundle-service + ${project.version} + + + ru.entaxy.esb.system.registry.connector + connector-api + ${project.version} + + + ru.entaxy.esb.system.registry.connector + connector-impl + ${project.version} + + + ru.entaxy.esb.system.core.permission + permission-api + ${project.version} + + + ru.entaxy.platform.security.jaas + entaxy-legacy-auth-api + ${project.version} + + + + ru.entaxy.esb.system.management.permission.manager + + permission-manager + ${project.version} + + + + + + org.apache.felix + maven-bundle-plugin + true + + + <_dsannotations>* + + + + + + + diff --git a/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/AccountManagerAdapter.java b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/AccountManagerAdapter.java new file mode 100644 index 00000000..4a8efbed --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/AccountManagerAdapter.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management-service-adapters + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.adapters; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.esb.system.auth.basic.jpa.api.BasicAuthService; +import ru.entaxy.platform.core.management.profile.support.legacy.AccountManager; + +@Component(service = AccountManager.class, immediate = true) +public class AccountManagerAdapter implements AccountManager { + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + BasicAuthService basicAuthService; + + @Override + public String getAccountForSystem(String systemUuid) throws Exception { + return basicAuthService.getBySystem(systemUuid).get().getLogin(); + } + + @Override + public void createAccountForSystem(String login, String password, String systemUUID, String createdBy, + String editedBy) throws Exception { + basicAuthService.saveCommon(login, password, systemUUID, createdBy, editedBy); + } + +} diff --git a/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/ConnectorManagerAdapter.java b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/ConnectorManagerAdapter.java new file mode 100644 index 00000000..bbf9905e --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/ConnectorManagerAdapter.java @@ -0,0 +1,135 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management-service-adapters + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.adapters; + +import java.util.Map; + +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.esb.system.connector.entity.Connector; +import ru.entaxy.esb.system.connector.impl.ConnectorService; +import ru.entaxy.esb.system.jpa.SystemService; +import ru.entaxy.esb.system.jpa.entity.System; +import ru.entaxy.esb.system.management.bundle.jpa.dto.BundleDto; +import ru.entaxy.esb.system.management.bundle.jpa.dto.BundleStatus; +import ru.entaxy.esb.system.management.connector.manager.ConnectorManager; +import ru.entaxy.esb.system.management.connector.manager.dto.ConnectorDto; + +@Component(service = ru.entaxy.platform.core.management.profile.support.legacy.ConnectorManager.class, immediate = true) +public class ConnectorManagerAdapter + implements ru.entaxy.platform.core.management.profile.support.legacy.ConnectorManager { + + @Reference(service = ConnectorManager.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + ConnectorManager connectorManager; + + @Reference(service = SystemService.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + SystemService systemService; + + @Reference(service = ConnectorService.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + ConnectorService connectorService; + + @Override + public void addConnector(String idOrName, String connectorFactoryId, Map parameters) + throws Exception { + + System system = getSystemByIdOrName(idOrName); + if (system == null) + throw new IllegalArgumentException("System not found by Id or Name [" + idOrName + "]"); + ConnectorDto connectorDto = new ConnectorDto(); + connectorDto.setConnectorParams(parameters); + connectorDto.setSystemUuid(system.getUuid()); + connectorDto.setTemplateName(connectorFactoryId); + + // FIXME remove hardcoded + connectorDto.setCreatedBy("admin"); + + checkBundleResult(connectorManager.installConnector(connectorDto), BundleStatus.ACTIVE); + + } + + @Override + public void removeConnector(String idOrName, String connectorName) throws Exception { + + System system = getSystemByIdOrName(idOrName); + if (system == null) + throw new IllegalArgumentException("System not found by Id or Name [" + idOrName + "]"); + + Connector connector = connectorService.getConnectorByName(connectorName); + if (connector == null) + throw new IllegalArgumentException("Connector not found by Name [" + connectorName + "]"); + + checkBundleResult(connectorManager.uninstallConnector(connector), BundleStatus.UNINSTALL); + } + + @Override + public void startConnector(String idOrName, String connectorName) throws Exception { + + System system = getSystemByIdOrName(idOrName); + if (system == null) + throw new IllegalArgumentException("System not found by Id or Name [" + idOrName + "]"); + + Connector connector = connectorService.getConnectorByName(connectorName); + if (connector == null) + throw new IllegalArgumentException("Connector not found by Name [" + connectorName + "]"); + + checkBundleResult(connectorManager.startConnector(connector), BundleStatus.ACTIVE); + + } + + @Override + public void stopConnector(String idOrName, String connectorName) throws Exception { + + System system = getSystemByIdOrName(idOrName); + if (system == null) + throw new IllegalArgumentException("System not found by Id or Name [" + idOrName + "]"); + + Connector connector = connectorService.getConnectorByName(connectorName); + if (connector == null) + throw new IllegalArgumentException("Connector not found by Name [" + connectorName + "]"); + + checkBundleResult(connectorManager.stopConnector(connector), BundleStatus.RESOLVED); + + } + + protected System getSystemByIdOrName(String idOrName) { + System result = systemService.getByName(idOrName); + if (result == null) + result = systemService.getByUuid(idOrName); + return result; + } + + protected void checkBundleResult(BundleDto bundleDto, BundleStatus expectedStatus) throws Exception { + if ((bundleDto == null) || !expectedStatus.equals(bundleDto.getStatus())) + throw new Exception("Result bundle is null or in a wrong state"); + + } +} diff --git a/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/PermissionManagerAdapter.java b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/PermissionManagerAdapter.java new file mode 100644 index 00000000..dd4117f7 --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/PermissionManagerAdapter.java @@ -0,0 +1,114 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management-service-adapters + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.adapters; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.esb.system.core.permission.jpa.PermissionService; +import ru.entaxy.esb.system.core.permission.jpa.entity.Permission; +import ru.entaxy.esb.system.jpa.SystemService; +import ru.entaxy.esb.system.management.permission.manager.dto.PermissionDto; +import ru.entaxy.platform.core.management.profile.support.legacy.PermissionManager; + +@Component(service = PermissionManager.class, + immediate = true) +public class PermissionManagerAdapter implements PermissionManager { + + @Reference(service = ru.entaxy.esb.system.management.permission.manager.PermissionManager.class, + cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + ru.entaxy.esb.system.management.permission.manager.PermissionManager permissionManager; + + @Reference(service = PermissionService.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + PermissionService permissionService; + + @Reference(service = SystemService.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + SystemService systemService; + + @Override + public List getObjectPermissions(String objectId) throws Exception { + ru.entaxy.esb.system.jpa.entity.System system = getRequiredSystemByIdOrName(objectId); + List permissions = permissionService.getAllById(system.getId(), "system"); + long systemId = system.getId(); + List result = new ArrayList<>(); + for (Permission perm : permissions) { + if (perm.getObjectId() == systemId) { + if ("system".equals(perm.getSubjectType())) { + ru.entaxy.esb.system.jpa.entity.System s = systemService.get(Long.parseLong(perm.getSubjectId())); + if (s != null) + result.add(s.getName()); + } + } + } + return result; + } + + @Override + public List getSubjectPermissions(String subjectId) throws Exception { + ru.entaxy.esb.system.jpa.entity.System system = getRequiredSystemByIdOrName(subjectId); + List permissions = permissionService.getAllById(system.getId(), "system"); + String systemId = system.getId() + ""; + List result = new ArrayList<>(); + for (Permission perm : permissions) { + if (perm.getSubjectId().equals(systemId)) { + ru.entaxy.esb.system.jpa.entity.System s = systemService.get(perm.getObjectId()); + if (s != null) + result.add(s.getName()); + } + } + return result; + } + + @Override + public void createPermission(String objectId, String subjectId) throws Exception { + PermissionDto dto = new PermissionDto(objectId, subjectId); + permissionManager.createPermission(dto); + } + + protected ru.entaxy.esb.system.jpa.entity.System getSystemByIdOrName(String idOrName) { + ru.entaxy.esb.system.jpa.entity.System result = systemService.getByName(idOrName); + if (result == null) + result = systemService.getByUuid(idOrName); + return result; + } + + protected ru.entaxy.esb.system.jpa.entity.System getRequiredSystemByIdOrName(String idOrName) throws Exception { + ru.entaxy.esb.system.jpa.entity.System result = systemService.getByName(idOrName); + if (result == null) + result = systemService.getByUuid(idOrName); + if (result == null) + throw new IllegalArgumentException("System not found by Id or Name: [" + idOrName + "]"); + return result; + } +} diff --git a/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/ProfileManagerAdapter.java b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/ProfileManagerAdapter.java new file mode 100644 index 00000000..4e8204fa --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/ProfileManagerAdapter.java @@ -0,0 +1,112 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management-service-adapters + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.adapters; + +import javax.naming.OperationNotSupportedException; + +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.esb.system.jpa.SystemService; +import ru.entaxy.esb.system.jpa.entity.System; +import ru.entaxy.esb.system.management.profile.manager.ProfileManager; +import ru.entaxy.esb.system.management.profile.manager.dto.ProfileDto; +import ru.entaxy.esb.system.management.profile.manager.mapper.ProfileMapper; + +@Component( + service = {ru.entaxy.platform.core.management.profile.support.legacy.ProfileManager.class}, immediate = true) +public class ProfileManagerAdapter implements ru.entaxy.platform.core.management.profile.support.legacy.ProfileManager { + + @Reference(service = ProfileManager.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + ProfileManager profileManager; + + @Reference(service = ProfileMapper.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + ProfileMapper profileMapper; + + @Reference(service = SystemService.class, cardinality = ReferenceCardinality.MANDATORY, + collectionType = CollectionType.SERVICE) + SystemService systemService; + + @Override + public void createProfile(String id, String name, String description) throws Exception { + ProfileDto dto = new ProfileDto(); + dto.setUuid(id); + dto.setName(name); + dto.setDescription(description); + + // TODO get the user name from JMX, + // need to investigate, how + dto.setCreatedBy("admin"); + + profileManager.installProfile(dto); + } + + @Override + public void startProfile(String idOrName) throws Exception { + ProfileDto dto = getProfileForSystem(getSystemByIdOrName(idOrName)); + if (dto == null) + throw new IllegalArgumentException("System/profile not found for [" + idOrName + "]"); + profileManager.startProfile(dto); + } + + @Override + public void stopProfile(String idOrName) throws Exception { + ProfileDto dto = getProfileForSystem(getSystemByIdOrName(idOrName)); + if (dto == null) + throw new IllegalArgumentException("System/profile not found for [" + idOrName + "]"); + profileManager.stopProfile(dto); + } + + @Override + public void uninstallProfile(String idOrName) throws Exception { + ProfileDto dto = getProfileForSystem(getSystemByIdOrName(idOrName)); + if (dto == null) + throw new IllegalArgumentException("System/profile not found for [" + idOrName + "]"); + profileManager.uninstallProfile(dto); + } + + @Override + public String getProfileConfig(String idOrName) throws Exception { + throw new OperationNotSupportedException(); + } + + protected System getSystemByIdOrName(String idOrName) { + System result = systemService.getByName(idOrName); + if (result == null) + result = systemService.getByUuid(idOrName); + return result; + } + + protected ProfileDto getProfileForSystem(System system) { + if (system == null) + return null; + return profileMapper.toProfileDto(system); + } +} diff --git a/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/SystemManagerAdapter.java b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/SystemManagerAdapter.java new file mode 100644 index 00000000..684dccd7 --- /dev/null +++ b/platform-backward-compat/profile-management-service-adapters/src/main/java/ru/entaxy/esb/platform/core/management/profile/adapters/SystemManagerAdapter.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management-service-adapters + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.adapters; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.esb.system.jpa.SystemService; +import ru.entaxy.platform.core.management.profile.support.legacy.SystemManager; + +@Component(service = SystemManager.class, immediate = true) +public class SystemManagerAdapter implements SystemManager { + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + SystemService systemService; + + @Override + public String getUUIDbyName(String name) throws Exception { + return systemService.getByName(name).getUuid(); + } + +} diff --git a/platform-backward-compat/profile-storage/LICENSE.txt b/platform-backward-compat/profile-storage/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform-backward-compat/profile-storage/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform-backward-compat/profile-storage/pom.xml b/platform-backward-compat/profile-storage/pom.xml new file mode 100644 index 00000000..2f97c6ca --- /dev/null +++ b/platform-backward-compat/profile-storage/pom.xml @@ -0,0 +1,27 @@ + + 4.0.0 + + + ru.entaxy.platform + platform-backward-compat + 1.10.0 + + + ru.entaxy.platform.backward-compat + profile-storage + bundle + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: PROFILE :: STORAGE + ENTAXY :: PLATFORM :: BACKWARD COMPATIBILITY :: PROFILE :: STORAGE + + + ru.entaxy.platform.base.objects.profile.storage + + + + + ru.entaxy.esb.system.registry.systems + system-api + ${project.version} + + + diff --git a/platform-backward-compat/profile-storage/src/main/java/ru/entaxy/platform/base/objects/profile/storage/SystemObjectStorage.java b/platform-backward-compat/profile-storage/src/main/java/ru/entaxy/platform/base/objects/profile/storage/SystemObjectStorage.java new file mode 100644 index 00000000..c93e714f --- /dev/null +++ b/platform-backward-compat/profile-storage/src/main/java/ru/entaxy/platform/base/objects/profile/storage/SystemObjectStorage.java @@ -0,0 +1,112 @@ +/*- + * ~~~~~~licensing~~~~~~ + * test-producers + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.base.objects.profile.storage; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.JsonObject; + +import ru.entaxy.esb.system.jpa.SystemService; +import ru.entaxy.esb.system.management.bundle.jpa.entity.BundleEntity; +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.objects.EntaxyObjectStorage; + +@Component(service = EntaxyObjectStorage.class, immediate = true) +public class SystemObjectStorage implements EntaxyObjectStorage { + + private static final Logger log = LoggerFactory.getLogger(SystemObjectStorage.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY, collectionType = CollectionType.SERVICE) + protected SystemService systemService; + + @SuppressWarnings("serial") + protected Map fieldMap = new HashMap<>() { + { + put("uuid", "objectId"); + put("name", "systemName"); + put("description", "description"); + put("version", "artifact.version"); + put("isDefaultRoute", "useDefaultRoute"); + } + }; + + protected Map fieldBundleMap = new HashMap<>() { + { + put("name", "bundleId"); + put("type", "artifact.type"); + put("status", "artifact.status"); + put("version", "artifact.version"); + put("url", "bundleLocation"); + } + }; + + @Override + public String[] getObjectTypes() { + return new String[] {EntaxyObject.OBJECT_TYPES.PROFILE}; + } + + @Override + public Object store(Map data) { + + JsonObject jsonObject = new JsonObject(); + Gson gson = new Gson(); + + for (Entry entry : fieldMap.entrySet()) { + if (data.containsKey(entry.getValue())) + jsonObject.add(entry.getKey(), gson.toJsonTree(data.get(entry.getValue()))); + } + JsonObject bundleJsonObject = new JsonObject(); + for (Entry entry : fieldBundleMap.entrySet()) { + if (data.containsKey(entry.getValue())) + bundleJsonObject.add(entry.getKey(), gson.toJsonTree(data.get(entry.getValue()))); + } + + log.debug("JSON :: " + jsonObject.toString()); + ru.entaxy.esb.system.jpa.entity.System system = + gson.fromJson(jsonObject, ru.entaxy.esb.system.jpa.entity.System.class); + system.setCreateDate(new Date()); + system.setCreatedBy("admin"); + + log.debug("JSON Bundle :: " + bundleJsonObject.toString()); + BundleEntity bundleEntity = gson.fromJson(bundleJsonObject, BundleEntity.class); + system.setBundleEntity(bundleEntity); + systemService.create(system); + + return null; + } + +} diff --git a/platform-backward-compat/src/main/features/features.xml b/platform-backward-compat/src/main/features/features.xml new file mode 100644 index 00000000..b07e0a01 --- /dev/null +++ b/platform-backward-compat/src/main/features/features.xml @@ -0,0 +1,153 @@ + + + + + + + mvn:ru.entaxy.esb/platform/${project.version}/xml/features + + + + + entaxy-platform + + entaxy-backward-compatibility-resources + + entaxy-bc-system + + entaxy-bc-api + + entaxy-bc-impl + + entaxy-bc-management + + entaxy-bc-modules + + + + + + + mvn:ru.entaxy.platform/platform-backward-compat/${project.version}/script/entaxy.bc.shell + + + + + + entaxy-platform + + mvn:ru.entaxy.esb.system/system-parent/${project.version}/cfg/ru.entaxy.esb + + + mvn:ru.entaxy.esb.system/system-parent/${project.version}/cfg/org.apache.felix.hc.generalchecks.BundlesStartedCheck-system + + mvn:ru.entaxy.esb.system.commons/system-commons/${project.version} + mvn:ru.entaxy.esb.system.core/template/${project.version} + + + + + entaxy-bc-system + + mvn:ru.entaxy.platform.security.jaas/entaxy-legacy-auth-api/${project.version} + mvn:ru.entaxy.esb.system.registry.systems/system-api/${project.version} + mvn:ru.entaxy.esb.system.registry.connector/connector-api/${project.version} + + mvn:ru.entaxy.esb.system.core.permission/permission-api/${project.version} + + + + + + + entaxy-bc-api + + mvn:ru.entaxy.platform.security.jaas/entaxy-legacy-auth/${project.version} + + mvn:ru.entaxy.esb.system.registry.systems/system-impl/${project.version} + + mvn:ru.entaxy.esb.system.registry.connector/connector-impl/${project.version} + + mvn:ru.entaxy.esb.system.core.permission/permission-common/${project.version} + mvn:ru.entaxy.esb.system.core.permission/permission-handler/${project.version} + mvn:ru.entaxy.esb.system.core.permission/permission-component/${project.version} + mvn:ru.entaxy.esb.system.core.permission/permission-impl/${project.version} + + + + + + + + entaxy-bc-api + entaxy-bc-impl + + mvn:ru.entaxy.platform.backward-compat/blueprint-generator-service/${project.version} + + mvn:ru.entaxy.esb.system.core.dispatcher/dispatcher/${project.version} + mvn:ru.entaxy.esb.system.management.bundle.jpa/bundle-service/${project.version} + + mvn:ru.entaxy.esb.system.management.bundle.manager/bundle-manager/${project.version} + mvn:ru.entaxy.esb.system.management.connector.manager/connector-manager/${project.version} + + mvn:ru.entaxy.esb.system.management.profile.manager/profile-manager/${project.version} + mvn:ru.entaxy.esb.system.management.bridge.profile.manager/bridge-profile-manager/${project.version} + mvn:ru.entaxy.esb.system.management.route.manager/route-manager/${project.version} + + mvn:ru.entaxy.esb.system.management.permission.manager/permission-manager/${project.version} + mvn:ru.entaxy.esb.system.auth.basic.htpasswd/htpasswd/${project.version} + + mvn:ru.entaxy.esb.system.management/system-management-api/${project.version} + + + + + + mvn:ru.entaxy.platform.backward-compat/profile-management-service-adapters/${project.version} + mvn:ru.entaxy.platform.backward-compat/profile-storage/${project.version} + mvn:ru.entaxy.platform.backward-compat/connector-storage/${project.version} + + + diff --git a/platform-backward-compat/src/main/scripts/entaxy.bc.shell.script b/platform-backward-compat/src/main/scripts/entaxy.bc.shell.script new file mode 100644 index 00000000..4544abbe --- /dev/null +++ b/platform-backward-compat/src/main/scripts/entaxy.bc.shell.script @@ -0,0 +1,60 @@ +entaxy:back-comp = { + + service = (service:get org.apache.karaf.features.FeaturesService) + + if { $1'' equals "install" } { + + # check repo + _repo = (feature:repo-list | grep ru.entaxy.platform/platform-backward-compat) + _repo_length = ($_repo length) + if { $_repo_length'' equals "0" } { + echo "Installing feature repo ru.entaxy.platform/platform-backward-compat/${project.version}" + feature:repo-add mvn:ru.entaxy.platform/platform-backward-compat/${project.version}/xml/features + } + + _platform_feature = ($service getFeature entaxy-platform) + _feature_id = $_platform_feature getId + _status = ($service getState $_feature_id) toString + + if { $_status equals "Uninstalled" } { + echo "Entaxy Platform not found, installation aborted" + } else { + _bc_feature = ($service getFeature entaxy-backward-compatibility-modules) + _feature_id = $_bc_feature getId + _status = ($service getState $_feature_id) toString + + if { $_status equals "Uninstalled" } { + echo "Installing feature 'entaxy-backward-compatibility-modules'" + feature:install -r -v entaxy-backward-compatibility-modules + echo + echo " --> DONE" + } else { + echo "Feature 'entaxy-backward-compatibility-modules' is already installed" + } + + } + + } else { + if { $1'' equals "uninstall" } { + echo "Uninstalling feature 'entaxy-backward-compatibility-modules'" + feature:uninstall -r -v entaxy-backward-compatibility-modules + echo + echo " --> DONE" + } else { + + _bc_feature = ($service getFeature entaxy-backward-compatibility-modules) + _feature_id = $_bc_feature getId + _status = ($service getState $_feature_id) toString + + if { $_status equals "Uninstalled" } { + echo + echo " --> UNINSTALLED" + } else { + echo + echo " --> INSTALLED" + } + + } + + } +} \ No newline at end of file diff --git a/platform-backward-compat/src/main/scripts/generated/fragments.xml b/platform-backward-compat/src/main/scripts/generated/fragments.xml new file mode 100644 index 00000000..39f396e1 --- /dev/null +++ b/platform-backward-compat/src/main/scripts/generated/fragments.xml @@ -0,0 +1,5 @@ + + + mvn:ru.entaxy.platform/platform-backward-compat/1.10.0/script/entaxy.bc.shell + + \ No newline at end of file diff --git a/platform-provided-modules/LICENSE.txt b/platform-provided-modules/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform-provided-modules/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform-provided-modules/pom.xml b/platform-provided-modules/pom.xml new file mode 100644 index 00000000..3375ac21 --- /dev/null +++ b/platform-provided-modules/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + + ru.entaxy.esb + root + 1.10.0 + + ru.entaxy + platform-provided-modules + pom + ENTAXY :: PLATFORM PROVIDED MODULES + ENTAXY :: PLATFORM PROVIDED MODULES + + + + + + src/main/provided + true + ${project.build.directory}/provided + + + src/main/support + true + ${project.build.directory}/support + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${build-helper-maven-plugin.version} + + + attach-provided + + attach-artifact + + + + + + + ${project.build.directory}/provided/ui.xml + + xml + ui + + + ${project.build.directory}/support/ui/collect-ui-features.xslt + + xslt + collect-ui-features + + + ${project.build.directory}/support/ui/process-ui-modules.xslt + + xslt + process-ui-modules + + + + + + maven-install-plugin + + + install-provided-modules-data + package + + install-file + + + ${platform.provided.groupId} + ${platform.provided.data.artifactId} + ${project.version} + ui + xml + false + ${project.build.directory}/provided/ui.xml + + + + + + + + + diff --git a/platform-provided-modules/src/main/provided/ui.xml b/platform-provided-modules/src/main/provided/ui.xml new file mode 100644 index 00000000..4bf27688 --- /dev/null +++ b/platform-provided-modules/src/main/provided/ui.xml @@ -0,0 +1,27 @@ + + + diff --git a/platform-provided-modules/src/main/support/ui/collect-ui-features.xslt b/platform-provided-modules/src/main/support/ui/collect-ui-features.xslt new file mode 100644 index 00000000..731c4ca6 --- /dev/null +++ b/platform-provided-modules/src/main/support/ui/collect-ui-features.xslt @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + ]]>]]> + + + + + + + + + + + + diff --git a/platform-provided-modules/src/main/support/ui/process-ui-modules.xslt b/platform-provided-modules/src/main/support/ui/process-ui-modules.xslt new file mode 100644 index 00000000..9cf5979d --- /dev/null +++ b/platform-provided-modules/src/main/support/ui/process-ui-modules.xslt @@ -0,0 +1,52 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/integration/LICENSE.txt b/platform/integration/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/LICENSE.txt b/platform/integration/applications/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/applications/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/application-api/LICENSE.txt b/platform/integration/applications/application-api/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/applications/application-api/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/application-api/pom.xml b/platform/integration/applications/application-api/pom.xml new file mode 100644 index 00000000..f8fe57df --- /dev/null +++ b/platform/integration/applications/application-api/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + ru.entaxy.platform.integration + applications + 1.10.0 + + ru.entaxy.platform.integration.applications + application-api + bundle + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: API + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: API + + + + ru.entaxy.platform.integration.applications, + ru.entaxy.platform.integration.applications.descriptor, + ru.entaxy.platform.integration.applications.exceptions, + ru.entaxy.platform.integration.applications.item.project, + ru.entaxy.platform.integration.applications.storage, + ru.entaxy.platform.integration.applications.utils + + + + + + ru.entaxy.esb.platform.runtime.base.resources + resources-api + ${project.version} + + + ru.entaxy.esb.platform.runtime.core + object-runtime-core + ${project.version} + + + ru.entaxy.esb.platform.runtime.core + artifact-management + ${project.version} + + + + diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationContent.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationContent.java new file mode 100644 index 00000000..1c4de2e9 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationContent.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; +import java.util.stream.Collectors; + +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; + +public interface ApplicationContent { + + ApplicationDescriptor getDescriptor(); + + List getItems(); + + default List getEditables() { + return getItems().stream().filter(item -> item.isEditable()).collect(Collectors.toList()); + }; + + default List getRevisionables() { + return getItems().stream().filter(item -> item.isRevisionable()).collect(Collectors.toList()); + }; + + List getResources(); +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationItem.java new file mode 100644 index 00000000..4da41664 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationItem.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.io.InputStream; + +public interface ApplicationItem { + + InputStream getInputStream(); + + void update(InputStream inputStream) throws Exception; + + boolean isEditable(); + + boolean isRevisionable(); + + String getLocation(); + + EntaxyApplication.ITEM_TYPE getType(); + + String getId(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationManager.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationManager.java new file mode 100644 index 00000000..217a000e --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationManager.java @@ -0,0 +1,139 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectAlreadyExistsException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.exceptions.StorageNotEnabledException; +import ru.entaxy.platform.integration.applications.exceptions.StorageNotFoundException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; + +public interface ApplicationManager { + + // storages + + ApplicationStorage getStorage(String storageName); + + default List getActiveStorages() { + return getStorages(true); + }; + + default List getStorages(boolean enabledOnly) { + if (!enabledOnly) + return getAllStorages(); + return getAllStorages().stream().filter(s -> s.isEnabled()).collect(Collectors.toList()); + }; + + List getAllStorages(); + + void addStorage(ApplicationStorage applicationStorage) throws StorageException; + + void removeStorage(ApplicationStorage applicationStorage) throws StorageException; + + // projects + + default EntaxyApplicationProject createProject(String storageName, String applicationName, String initialVersion) + throws ProjectException, StorageException { + ApplicationStorage storage = getStorage(storageName); + if (storage == null) + throw new StorageNotFoundException(storageName); + if (!storage.isEnabled()) + throw new StorageNotEnabledException(storageName); + EntaxyApplicationProject app = storage.getProject(applicationName); + if (app != null) + throw new ProjectAlreadyExistsException(applicationName); + app = storage.createProject(applicationName); + app.createVersion(initialVersion); + return app; + }; + + default List getProjects() { + List result = new ArrayList<>(); + for (ApplicationStorage storage : getActiveStorages()) { + result.addAll(storage.getProjects()); + } + return result; + } + + default List getProjects(String storageName) + throws ProjectException, StorageException { + ApplicationStorage storage = getStorage(storageName); + if (storage == null) + throw new StorageNotFoundException(storageName); + return getProjects(storage); + } + + default List getProjects(ApplicationStorage storage) + throws ProjectException, StorageException { + if (!storage.isEnabled()) + throw new StorageNotEnabledException(storage.getName()); + return storage.getProjects(); + } + + void exportToFile(EntaxyApplicationProjectVersion version, String filePath) throws ProjectVersionException; + + void exportToRepository(EntaxyApplicationProjectVersion version, String repositoryName) throws ProjectVersionException; + + // applications + + default List getApplications() { + List result = new ArrayList<>(); + for (ApplicationStorage storage : getActiveStorages()) { + result.addAll(storage.getApplications()); + } + return result; + } + + default List getApplications(String storageName) + throws ProjectException, StorageException { + ApplicationStorage storage = getStorage(storageName); + if (storage == null) + throw new StorageNotFoundException(storageName); + return getApplications(storage); + } + + default List getApplications(ApplicationStorage storage) + throws ProjectException, StorageException { + if (!storage.isEnabled()) + throw new StorageNotEnabledException(storage.getName()); + return storage.getApplications(); + } + + + EntaxyApplication importApplicationFromFile(String storageName, String filePath) + throws ApplicationException, StorageException; + + EntaxyApplication importApplicationFromRepository(String storageName, String mavenUrl) + throws ApplicationException, StorageException; + + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectContent.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectContent.java new file mode 100644 index 00000000..3525772f --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectContent.java @@ -0,0 +1,70 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; +import java.util.Map; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.integration.applications.exceptions.ItemException; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectResource; + +public interface ApplicationProjectContent { + + public interface STANDARD_PROPERTIES { + String APPLICATION = "application"; + String GROUP = "group"; + String VERSION = "version"; + String CREATED_ON = "createdOn"; + String CREATED_BY = "createdBy"; + String MODIFIED_ON = "modifiedOn"; + String MODIFIED_BY = "modifiedBy"; + } + + List getItems(); + + List getItems(Class itemClass); + + void addItem(ApplicationProjectItem item) throws ItemException; + + void ignoreItem(ApplicationProjectItem item) throws ItemException; + + void removeItem(ApplicationProjectItem item) throws ItemException; + + default boolean isConsistent() { + return getItems().stream().filter(item -> (item.isRequired() && !item.isIgnored())).count() == 0; + } + + ApplicationProjectItem addObject(EntaxyRuntimeObject runtimeObject); + + ApplicationProjectItem addResource(EntaxyRuntimeObjectResource runtimeObjectResource); + + ApplicationProjectItem addResource(EntaxyResource entaxyResource); + + Map getProperties(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectInfo.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectInfo.java new file mode 100644 index 00000000..f8dcc877 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectInfo.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; + +public interface ApplicationProjectInfo { + + + String getName(); + + String getGroup(); + + long getCreatedOn(); + + String getCreatedBy(); + + long getLastModifiedOn(); + + String getLastModifiedBy(); + + String getLatestVersion(); + + List getAvailableVersions(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectItem.java new file mode 100644 index 00000000..50715895 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationProjectItem.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; + +public interface ApplicationProjectItem { + + String getId(); + + EntaxyApplication.ITEM_SCOPE getScope(); + + EntaxyApplication.ITEM_TYPE getType(); + + boolean isGhost(); + + boolean isRequired(); + + List getRequiredBy(); + + List getRequirements(); + + List getColocated(); + + boolean isIgnored(); + + void ignore(); + + boolean isPlatform(); +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationResource.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationResource.java new file mode 100644 index 00000000..9b9ff182 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationResource.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.io.InputStream; + +public interface ApplicationResource { + + InputStream getInputStream(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationStorage.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationStorage.java new file mode 100644 index 00000000..02b538a3 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/ApplicationStorage.java @@ -0,0 +1,93 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; +import java.util.Map; + +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; + +public interface ApplicationStorage { + + // storage itself + + String getName(); + + String getType(); + + Map getInfo(); + + boolean isEnabled(); + + void enable(); + + void disable(); + + // projects + + List getProjects(); + + EntaxyApplicationProject getProject(String applicationName); + + void addProject(EntaxyApplicationProject project) throws ProjectException, StorageException; + + void removeProject(EntaxyApplicationProject project) throws ProjectException, StorageException; + + EntaxyApplicationProject createProject(String applicationName) + throws ProjectException, StorageException; + + // applications + + public interface ApplicationImportContent { + + Map getItems(); + + void clear(); + } + + public interface ApplicationImportItem { + String getName(); + + String getLocation(); + + String getPath(); + + InputStream getInputStream() throws IOException; + } + + List getApplications(); + + EntaxyApplication getApplication(String applicationName); + + void removeApplication(EntaxyApplication application) throws ApplicationException, StorageException; + + EntaxyApplication createApplication(ApplicationImportContent content) throws ApplicationException, StorageException; + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplication.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplication.java new file mode 100644 index 00000000..c66cb118 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplication.java @@ -0,0 +1,83 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; + +import ru.entaxy.esb.resources.EntaxyResource.RESOURCE_SCOPE; +import ru.entaxy.platform.base.objects.EntaxyObject.OBJECT_RELATION_SCOPE; + +public interface EntaxyApplication { + + String DESCRIPTOR_NAME = "descriptor.json"; + + String DEFAULT_GROUP_ID = "entaxy.application"; + + enum ITEM_TYPE { + OBJECT, + CONFIG, + BUNDLE, + RESOURCE, + FEATURES + } + + enum ITEM_SCOPE { + DESIGN, + RUNTIME, + UNKNOWN; + + public static ITEM_SCOPE convert(OBJECT_RELATION_SCOPE originScope) { + try { + return ITEM_SCOPE.valueOf(originScope.name().toUpperCase()); + } catch (Exception e) { + return UNKNOWN; + } + } + + public static ITEM_SCOPE convert(RESOURCE_SCOPE originScope) { + try { + return ITEM_SCOPE.valueOf(originScope.name().toUpperCase()); + } catch (Exception e) { + return UNKNOWN; + } + } + + } + + String getName(); + + ApplicationStorage getStorage(); + + List getVersions(); + + EntaxyApplicationVersion getLatestVersion(); + + EntaxyApplicationVersion getVersion(String version); + + void removeVersion(String version); + + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationProject.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationProject.java new file mode 100644 index 00000000..5c87f20b --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationProject.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; + +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; + +public interface EntaxyApplicationProject { + String getName(); + + String getGroup(); + + ApplicationStorage getStorage(); + + void save(); + + void disgard(); + + List getVersions(); + + EntaxyApplicationProjectVersion getLatestVersion(); + + EntaxyApplicationProjectVersion getVersion(String version); + + EntaxyApplicationProjectVersion createVersion(String version) throws ProjectVersionException; + + EntaxyApplicationProjectVersion createVersion(String version, String fromVersion) throws ProjectVersionException; + + void removeVersion(String version); + + ApplicationProjectInfo getInfo(); +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationProjectVersion.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationProjectVersion.java new file mode 100644 index 00000000..7fa2f3f6 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationProjectVersion.java @@ -0,0 +1,84 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.io.InputStream; +import java.net.URL; + +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; + +public interface EntaxyApplicationProjectVersion extends ApplicationProjectContent { + + public enum VERSION_STATUS { + NEW, + MODIFIED, + BUILT + } + + EntaxyApplicationProject getApplication(); + + String getVersionNumber(); + + default int compareTo(EntaxyApplicationProjectVersion otherVersion) { + String[] thisV = otherVersion.getVersionNumber().split("\\."); + String[] otherV = otherVersion.getVersionNumber().split("\\."); + + for (int i = 0; i < Math.max(thisV.length, otherV.length); i++) { + try { + int thisValue = Integer.parseInt(thisV[i]); + int otherValue = Integer.parseInt(otherV[i]); + if (thisValue > otherValue) + return 1; + if (thisValue < otherValue) + return -1; + } catch (Exception ignore) { + continue; + } + } + + return 0; + } + + void save(); + + void disgard(); + + URL build() throws ProjectVersionException; + + boolean isBuildAvailable(); + + URL getBuildUrl(); + + InputStream getBuild(); + + ApplicationDescriptor getBuildInfo(); + + VERSION_STATUS getStatus(); + + boolean isDirty(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationRevision.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationRevision.java new file mode 100644 index 00000000..2a40255c --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationRevision.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; + +public interface EntaxyApplicationRevision extends ApplicationContent { + + public enum REVISION_STATUS { + NEW, + CONFIGURED, + DEPLOYED, + INSTALLED, + UNINSTALLED + } + + int getRevisionNumber(); + + REVISION_STATUS getStatus(); + + void configure() throws RevisionException; + + void deploy() throws RevisionException; + + void install() throws RevisionException; + + void uninstall() throws RevisionException; + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationVersion.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationVersion.java new file mode 100644 index 00000000..b927f5d3 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/EntaxyApplicationVersion.java @@ -0,0 +1,90 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications; + +import java.util.List; + +import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionException; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.exceptions.RevisionIllegalNumber; + +public interface EntaxyApplicationVersion extends ApplicationContent { + + EntaxyApplication getApplication(); + + String getVersionNumber(); + + List getRevisions(); + + EntaxyApplicationRevision getLastRevision(); + + default int compareTo(EntaxyApplicationVersion otherVersion) { + String[] thisV = otherVersion.getVersionNumber().split("\\."); + String[] otherV = otherVersion.getVersionNumber().split("\\."); + + for (int i = 0; i < Math.max(thisV.length, otherV.length); i++) { + try { + int thisValue = Integer.parseInt(thisV[i]); + int otherValue = Integer.parseInt(otherV[i]); + if (thisValue > otherValue) + return 1; + if (thisValue < otherValue) + return -1; + } catch (Exception ignore) { + continue; + } + } + + return 0; + } + + default EntaxyApplicationRevision getRevision(String revision) throws RevisionException { + int rev = -1; + try { + rev = Integer.parseInt(revision); + } catch (Exception ignore) { + + } + if (rev < 0) + throw new RevisionIllegalNumber(getApplication().getName(), getVersionNumber(), revision); + return getRevision(rev); + }; + + EntaxyApplicationRevision getRevision(int revision); + + // creates next revision from last revision + default EntaxyApplicationRevision createRevision() throws ApplicationVersionException { + if (getLastRevision() == null) + // create initial revision + return createRevision(-1); + return createRevision(getLastRevision().getRevisionNumber()); + }; + + // creates next revision from given revision + // -1 means create origin revision + EntaxyApplicationRevision createRevision(int fromRevision) throws ApplicationVersionException; + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationComponent.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationComponent.java new file mode 100644 index 00000000..dfcd105c --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationComponent.java @@ -0,0 +1,84 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.descriptor; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.integration.applications.EntaxyApplication; + +public class ApplicationComponent { + + public String id; + public EntaxyApplication.ITEM_TYPE type; + public String internalLocation; + public String mavenLocation; + public String targetProtocol; + public String targetLocation; + public String targetQueryString; + + public int priority; + + public String getId() { + return id; + } + + public EntaxyApplication.ITEM_TYPE getType() { + return type; + } + + public String getInternalLocation() { + return internalLocation; + } + + public String getMavenLocation() { + return mavenLocation; + } + + public String getTargetLocation() { + return targetLocation; + } + + public int getPriority() { + return priority; + } + + public String getTargetProtocol() { + return targetProtocol; + } + + public String getTargetQueryString() { + return targetQueryString; + } + + public String getFullTargetLocation() { + StringBuffer result = new StringBuffer(); + if (CommonUtils.isValid(targetProtocol)) + result.append(targetProtocol).append(':'); + result.append(targetLocation); + if (CommonUtils.isValid(targetQueryString)) + result.append('?').append(targetQueryString); + return result.toString(); + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationContentItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationContentItem.java new file mode 100644 index 00000000..bd8d385e --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationContentItem.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.descriptor; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; + +public class ApplicationContentItem { + + public String id; + public EntaxyApplication.ITEM_TYPE type; + public String componentId; + + public String getId() { + return id; + } + + public EntaxyApplication.ITEM_TYPE getType() { + return type; + } + + public String getComponentId() { + return componentId; + } + + + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationDescriptor.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationDescriptor.java new file mode 100644 index 00000000..4dbdd891 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationDescriptor.java @@ -0,0 +1,112 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.descriptor; + +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; + +public class ApplicationDescriptor { + + public String name; + public String group; + public String version; + public String buildOn; + public String buildBy; + + public String mavenUrl; + public String mavenAsset; + + public ApplicationFeatures features; + + public volatile List requirements = new ArrayList<>(); + + public volatile List items = new ArrayList<>(); + + public volatile List components = new ArrayList<>(); + + public String getName() { + return name; + } + + public String getGroup() { + return group; + } + + public String getVersion() { + return version; + } + + public String getBuildOn() { + return buildOn; + } + + public String getBuildBy() { + return buildBy; + } + + public String getMavenUrl() { + return mavenUrl; + } + + public String getMavenAsset() { + return mavenAsset; + } + + public List getRequirements() { + return requirements; + } + + public List getItems() { + return items; + } + + public List getComponents() { + return components; + } + + public List getComponents(EntaxyApplication.ITEM_TYPE type) { + if (type == null) + return getComponents(); + return components.stream().filter(comp -> type.equals(comp.type)).collect(Collectors.toList()); + } + + public List getBundleComponents() { + return getComponents(ITEM_TYPE.BUNDLE); + } + + public List getConfigComponents() { + return getComponents(ITEM_TYPE.CONFIG); + } + + public ApplicationFeatures getFeatures() { + return features; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationFeatures.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationFeatures.java new file mode 100644 index 00000000..3801f672 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationFeatures.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.descriptor; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; + +public class ApplicationFeatures extends ApplicationComponent { + + public ApplicationFeatures() { + id = "application.features"; + type = EntaxyApplication.ITEM_TYPE.FEATURES; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationRequirement.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationRequirement.java new file mode 100644 index 00000000..fe57237e --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/descriptor/ApplicationRequirement.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.descriptor; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; + +public class ApplicationRequirement { + + public String id; + public EntaxyApplication.ITEM_TYPE type; + public EntaxyApplication.ITEM_SCOPE scope; + + public String getId() { + return id; + } + + public EntaxyApplication.ITEM_TYPE getType() { + return type; + } + + public EntaxyApplication.ITEM_SCOPE getScope() { + return scope; + } + + + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationCausedException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationCausedException.java new file mode 100644 index 00000000..e19b622b --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationCausedException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationCausedException extends ApplicationException { + + private static final long serialVersionUID = 1L; + + public ApplicationCausedException(String applicationName, Throwable cause) { + super(applicationName, cause); + } + + @Override + public String getMessage() { + return String.format("Application exception on [%s]: %s", applicationName, getCause().getMessage()); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationDescriptorIsInvalid.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationDescriptorIsInvalid.java new file mode 100644 index 00000000..3d46ffcd --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationDescriptorIsInvalid.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationDescriptorIsInvalid extends ApplicationException { + + private static final long serialVersionUID = 1L; + + public ApplicationDescriptorIsInvalid(String applicationName) { + super(applicationName); + } + + @Override + protected String getMessageInfo() { + return "descriptor is invalid"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationDescriptorNotFound.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationDescriptorNotFound.java new file mode 100644 index 00000000..6cfb388d --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationDescriptorNotFound.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationDescriptorNotFound extends ApplicationException { + + private static final long serialVersionUID = 1L; + + public ApplicationDescriptorNotFound(String applicationName) { + super(applicationName); + } + + @Override + protected String getMessageInfo() { + return "descriptor not found"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationException.java new file mode 100644 index 00000000..11c3245d --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationException.java @@ -0,0 +1,60 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public abstract class ApplicationException extends EntaxyApplicationsException { + + private static final long serialVersionUID = 1L; + protected String applicationName; + + public ApplicationException(String applicationName) { + super(); + this.applicationName = applicationName; + } + + public ApplicationException(String applicationName, Throwable cause) { + super(cause); + this.applicationName = applicationName; + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + + @Override + public String getMessage() { + return String.format("Application %s: [%s]", getMessageInfo(), applicationName); + } + + protected String getMessageInfo() { + return "exception"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationImportCausedException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationImportCausedException.java new file mode 100644 index 00000000..ffe89289 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationImportCausedException.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationImportCausedException extends ApplicationException { + + private static final long serialVersionUID = 1L; + + public ApplicationImportCausedException(String applicationName, Throwable cause) { + super(applicationName, cause); + } + + @Override + public String getMessage() { + return String.format("Application exception while importing from [%s]: %s", applicationName, + getCause().getMessage()); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationNotFoundException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationNotFoundException.java new file mode 100644 index 00000000..d26cfb69 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationNotFoundException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationNotFoundException extends ApplicationException { + + private static final long serialVersionUID = 1L; + + public ApplicationNotFoundException(String applicationName) { + super(applicationName); + // TODO Auto-generated constructor stub + } + + @Override + protected String getMessageInfo() { + return "not found"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionAlreadyExists.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionAlreadyExists.java new file mode 100644 index 00000000..c62153b8 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionAlreadyExists.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationVersionAlreadyExists extends ApplicationVersionException { + + private static final long serialVersionUID = 1L; + + public ApplicationVersionAlreadyExists(String applicationName, String versionNumber) { + super(applicationName, versionNumber); + } + + @Override + protected String getMessageInfo() { + return "already exists"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionCausedException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionCausedException.java new file mode 100644 index 00000000..66e20885 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionCausedException.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationVersionCausedException extends ApplicationVersionException { + + private static final long serialVersionUID = 1L; + + public ApplicationVersionCausedException(String applicationName, Throwable e, String versionNumber) { + super(applicationName, e, versionNumber); + } + + @Override + public String getMessage() { + return String.format("Aplication version exception: [%s]/[%s]; %s", getApplicationName(), getVersionNumber(), + getCause().getMessage()); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionException.java new file mode 100644 index 00000000..83d2ddf7 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ApplicationVersionException.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ApplicationVersionException extends ApplicationException { + + private static final long serialVersionUID = 1L; + + String versionNumber; + + public ApplicationVersionException(String applicationName, String versionNumber) { + super(applicationName); + setVersionNumber(versionNumber); + } + + public ApplicationVersionException(String applicationName, Throwable e, String versionNumber) { + super(applicationName, e); + setVersionNumber(versionNumber); + } + + public String getVersionNumber() { + return versionNumber; + } + + public void setVersionNumber(String versionNumber) { + this.versionNumber = versionNumber; + } + + @Override + public String getMessage() { + return String.format("Application version %s: [%s]/[%s]", getMessageInfo(), applicationName, versionNumber); + } + + protected String getMessageInfo() { + return "caused exception"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/EntaxyApplicationsException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/EntaxyApplicationsException.java new file mode 100644 index 00000000..14888c1d --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/EntaxyApplicationsException.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class EntaxyApplicationsException extends Exception { + + private static final long serialVersionUID = 1L; + + public EntaxyApplicationsException() { + super(); + } + + public EntaxyApplicationsException(Throwable cause) { + super(cause); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemException.java new file mode 100644 index 00000000..32cec13c --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemException.java @@ -0,0 +1,47 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public abstract class ItemException extends ProjectVersionException { + + private static final long serialVersionUID = 1L; + + protected String itemId; + + public ItemException(String applicationName, String versionNumber, String itemId) { + super(applicationName, versionNumber); + this.itemId = itemId; + } + + public String getItemId() { + return itemId; + } + + public void setItemId(String itemId) { + this.itemId = itemId; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemIsGhostException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemIsGhostException.java new file mode 100644 index 00000000..269aa8dd --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemIsGhostException.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ItemIsGhostException extends ItemException { + + + + private static final long serialVersionUID = 1L; + + public ItemIsGhostException(String applicationName, String versionNumber, String itemId) { + super(applicationName, versionNumber, itemId); + } + + @Override + public String getMessage() { + return String.format("Item operation not allowed for ghost: [%s]", itemId); + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemIsPlatformException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemIsPlatformException.java new file mode 100644 index 00000000..2861a0fe --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemIsPlatformException.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ItemIsPlatformException extends ItemException { + + + + private static final long serialVersionUID = 1L; + + public ItemIsPlatformException(String applicationName, String versionNumber, String itemId) { + super(applicationName, versionNumber, itemId); + } + + @Override + public String getMessage() { + return String.format("Item operation not allowed for platform object: [%s]", itemId); + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemNotFoundException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemNotFoundException.java new file mode 100644 index 00000000..b00e2f99 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ItemNotFoundException.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ItemNotFoundException extends ItemException { + + private static final long serialVersionUID = 1L; + + public ItemNotFoundException(String applicationName, String versionNumber, String itemId) { + super(applicationName, versionNumber, itemId); + } + + @Override + public String getMessage() { + return String.format("Item [%s] not found in [%s]/[%s]", itemId, applicationName, versionNumber); + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectAlreadyExistsException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectAlreadyExistsException.java new file mode 100644 index 00000000..d9025951 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectAlreadyExistsException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectAlreadyExistsException extends ProjectException { + + private static final long serialVersionUID = 1L; + + public ProjectAlreadyExistsException(String applicationName) { + super(applicationName); + } + + @Override + public String getMessage() { + return String.format("Application [%s] already exists", applicationName); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectException.java new file mode 100644 index 00000000..586ac1ca --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectException.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public abstract class ProjectException extends EntaxyApplicationsException { + + private static final long serialVersionUID = 1L; + protected String applicationName; + + public ProjectException(String applicationName) { + super(); + this.applicationName = applicationName; + } + + public ProjectException(String applicationName, Throwable cause) { + super(cause); + this.applicationName = applicationName; + } + + public String getApplicationName() { + return applicationName; + } + + public void setApplicationName(String applicationName) { + this.applicationName = applicationName; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectNotFoundException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectNotFoundException.java new file mode 100644 index 00000000..2a674b18 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectNotFoundException.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectNotFoundException extends ProjectException { + + public ProjectNotFoundException(String applicationName) { + super(applicationName); + } + + @Override + public String getMessage() { + return String.format("Application [%s] not found", applicationName); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionBuildNotAvailable.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionBuildNotAvailable.java new file mode 100644 index 00000000..87eddc57 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionBuildNotAvailable.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectVersionBuildNotAvailable extends ProjectVersionException { + + private static final long serialVersionUID = 1L; + + public ProjectVersionBuildNotAvailable(String applicationName, String versionNumber) { + super(applicationName, versionNumber); + } + + @Override + protected String getMessageInfo() { + return "bild not available"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionCausedException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionCausedException.java new file mode 100644 index 00000000..ddc5db2e --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionCausedException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectVersionCausedException extends ProjectVersionException { + + private static final long serialVersionUID = 1L; + + public ProjectVersionCausedException(String applicationName, String versionNumber, Throwable cause) { + super(applicationName, versionNumber, cause); + } + + @Override + public String getMessage() { + return String.format("Version exception on [%s]/[%s]: %s", applicationName, versionNumber, + getCause().getMessage()); + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionException.java new file mode 100644 index 00000000..3c952d87 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionException.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectVersionException extends ProjectException { + + private static final long serialVersionUID = 1L; + + protected String versionNumber; + + public ProjectVersionException(String applicationName, String versionNumber) { + super(applicationName); + this.versionNumber = versionNumber; + } + + public ProjectVersionException(String applicationName, String versionNumber, Throwable cause) { + super(applicationName, cause); + this.versionNumber = versionNumber; + } + + public String getVersionNumber() { + return versionNumber; + } + + public void setVersionNumber(String versionNumber) { + this.versionNumber = versionNumber; + } + + @Override + public String getMessage() { + return String.format("Version %s: [%s]/[%s]", getMessageInfo(), applicationName, versionNumber); + } + + protected String getMessageInfo() { + return "caused exception"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionIsDirtyException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionIsDirtyException.java new file mode 100644 index 00000000..5a9f0f52 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionIsDirtyException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectVersionIsDirtyException extends ProjectVersionException { + + private static final long serialVersionUID = 1L; + + public ProjectVersionIsDirtyException(String applicationName, String versionNumber) { + super(applicationName, versionNumber); + } + + @Override + protected String getMessageInfo() { + return "is dirty"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionNotConsistentException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionNotConsistentException.java new file mode 100644 index 00000000..b239ac82 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionNotConsistentException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectVersionNotConsistentException extends ProjectVersionException { + + private static final long serialVersionUID = 1L; + + public ProjectVersionNotConsistentException(String applicationName, String versionNumber) { + super(applicationName, versionNumber); + } + + @Override + protected String getMessageInfo() { + return "not consistent"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionNotFoundException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionNotFoundException.java new file mode 100644 index 00000000..8f3fa827 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/ProjectVersionNotFoundException.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class ProjectVersionNotFoundException extends ProjectVersionException { + + private static final long serialVersionUID = 1L; + + public ProjectVersionNotFoundException(String applicationName, String versionNumber) { + super(applicationName, versionNumber); + } + + @Override + public String getMessageInfo() { + return "not found"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionCausedException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionCausedException.java new file mode 100644 index 00000000..b0e24ceb --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionCausedException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class RevisionCausedException extends RevisionException { + + private static final long serialVersionUID = 1L; + + public RevisionCausedException(String applicationName, Throwable e, String versionNumber, int revisionNumber) { + super(applicationName, e, versionNumber, revisionNumber); + } + + @Override + public String getMessage() { + return String.format("Application revision [%s]/[%s]:[%d] caused exception: %s", getApplicationName(), + getVersionNumber(), getRevisionNumber(), getCause().getMessage()); + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionException.java new file mode 100644 index 00000000..8002627f --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionException.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class RevisionException extends ApplicationVersionException { + + private static final long serialVersionUID = 1L; + int revisionNumber; + + public RevisionException(String applicationName, String versionNumber, int revisionNumber) { + super(applicationName, versionNumber); + setRevisionNumber(revisionNumber); + } + + public RevisionException(String applicationName, Throwable e, String versionNumber, int revisionNumber) { + super(applicationName, e, versionNumber); + setRevisionNumber(revisionNumber); + } + + public int getRevisionNumber() { + return revisionNumber; + } + + public void setRevisionNumber(int revisionNumber) { + this.revisionNumber = revisionNumber; + } + + @Override + public String getMessage() { + return String.format("Application revision %s: [%s]/[%s]:[%d]", getMessageInfo(), getApplicationName(), + getVersionNumber(), getRevisionNumber()); + } + + @Override + protected String getMessageInfo() { + return "caused exception"; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionIllegalNumber.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionIllegalNumber.java new file mode 100644 index 00000000..09ca0d71 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionIllegalNumber.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class RevisionIllegalNumber extends RevisionException { + + private static final long serialVersionUID = 1L; + + String illegalNumber; + + public RevisionIllegalNumber(String applicationName, String versionNumber, String illegalNumber) { + super(applicationName, versionNumber, 0); + setIllegalNumber(illegalNumber); + } + + public String getIllegalNumber() { + return illegalNumber; + } + + public void setIllegalNumber(String illegalNumber) { + this.illegalNumber = illegalNumber; + } + + @Override + public String getMessage() { + return String.format("Illegal revision number [%s] in application: [%s]/[%s]", illegalNumber, + getApplicationName(), getVersionNumber()); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionIllegalTransition.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionIllegalTransition.java new file mode 100644 index 00000000..38a404aa --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionIllegalTransition.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision.REVISION_STATUS; + +public class RevisionIllegalTransition extends RevisionException { + + private static final long serialVersionUID = 1L; + + protected REVISION_STATUS fromStatus; + + protected REVISION_STATUS toStatus; + + public RevisionIllegalTransition(String applicationName, String versionNumber, int revisionNumber, + REVISION_STATUS fromStatus, REVISION_STATUS toStatus) { + super(applicationName, versionNumber, revisionNumber); + this.fromStatus = fromStatus; + this.toStatus = toStatus; + } + + @Override + protected String getMessageInfo() { + return String.format("transition not allowed from [%s] to [%s]", fromStatus.name(), toStatus.name()); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionNotConfigurable.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionNotConfigurable.java new file mode 100644 index 00000000..adf4d032 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionNotConfigurable.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class RevisionNotConfigurable extends RevisionException { + + private static final long serialVersionUID = 1L; + + public RevisionNotConfigurable(String applicationName, String versionNumber, int revisionNumber) { + super(applicationName, versionNumber, revisionNumber); + } + + @Override + protected String getMessageInfo() { + return "not configurable"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionNotFound.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionNotFound.java new file mode 100644 index 00000000..bb257c40 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionNotFound.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class RevisionNotFound extends RevisionException { + + private static final long serialVersionUID = 1L; + + public RevisionNotFound(String applicationName, String versionNumber, int revisionNumber) { + super(applicationName, versionNumber, revisionNumber); + } + + @Override + protected String getMessageInfo() { + return "not found"; + } +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionRequirementsNotSatisfied.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionRequirementsNotSatisfied.java new file mode 100644 index 00000000..7c3c453d --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/RevisionRequirementsNotSatisfied.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +import java.util.List; + +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; + +public class RevisionRequirementsNotSatisfied extends RevisionException { + + private static final long serialVersionUID = 1L; + + protected List requirements; + + public RevisionRequirementsNotSatisfied(String applicationName, String versionNumber, int revisionNumber, + List requirements) { + super(applicationName, versionNumber, revisionNumber); + this.requirements = requirements; + } + + @Override + protected String getMessageInfo() { + String data = "requirements not satisfied:"; + for (ApplicationRequirement req : requirements) + data = data.concat("\n\t").concat(req.getId()).concat(": ").concat(req.getType().name()).concat(" / ") + .concat(req.getScope().name()); + return data.concat("\n"); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageException.java new file mode 100644 index 00000000..eadb2e23 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageException.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public abstract class StorageException extends EntaxyApplicationsException { + + private static final long serialVersionUID = 1L; + protected String storageName; + + public StorageException(String storageName) { + super(); + this.storageName = storageName; + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageNotEnabledException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageNotEnabledException.java new file mode 100644 index 00000000..1a26d5ea --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageNotEnabledException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class StorageNotEnabledException extends StorageException { + + private static final long serialVersionUID = 1L; + + public StorageNotEnabledException(String storageName) { + super(storageName); + } + + @Override + public String getMessage() { + return String.format("Storage [%s] not enabled", this.storageName); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageNotFoundException.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageNotFoundException.java new file mode 100644 index 00000000..a82bc27f --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/exceptions/StorageNotFoundException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.exceptions; + +public class StorageNotFoundException extends StorageException { + + private static final long serialVersionUID = 1L; + + public StorageNotFoundException(String storageName) { + super(storageName); + } + + @Override + public String getMessage() { + return String.format("Storage [%s] not found", this.storageName); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyBundleItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyBundleItem.java new file mode 100644 index 00000000..476d6c84 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyBundleItem.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.item.project; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; + +public interface EntaxyBundleItem extends ApplicationProjectItem { + long getBundleId(); + + String getBundleSymbolicName(); +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyConfigItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyConfigItem.java new file mode 100644 index 00000000..4073cbca --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyConfigItem.java @@ -0,0 +1,30 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.item.project; + +public interface EntaxyConfigItem extends EntaxyObjectItem { + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyObjectItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyObjectItem.java new file mode 100644 index 00000000..80f75ce8 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyObjectItem.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.item.project; + +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +public interface EntaxyObjectItem extends EntaxyBundleItem { + + EntaxyRuntimeObject getObject(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyResourceItem.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyResourceItem.java new file mode 100644 index 00000000..727117c2 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/item/project/EntaxyResourceItem.java @@ -0,0 +1,35 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.item.project; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; + +public interface EntaxyResourceItem extends ApplicationProjectItem { + + EntaxyResource getResource(); + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/storage/AbstractApplicationStorage.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/storage/AbstractApplicationStorage.java new file mode 100644 index 00000000..32ced5e9 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/storage/AbstractApplicationStorage.java @@ -0,0 +1,96 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import ru.entaxy.platform.integration.applications.ApplicationStorage; + +public abstract class AbstractApplicationStorage implements ApplicationStorage { + + protected String name; + + protected String type = "unknown"; + + protected boolean isEnabled = true; + + protected Map storageInfo = new HashMap<>(); + + protected AbstractApplicationStorage() { + super(); + if (this.getClass().isAnnotationPresent(ApplicationStorageInfo.class)) { + ApplicationStorageInfo anno = this.getClass().getAnnotation(ApplicationStorageInfo.class); + setName(anno.name()); + setEnabled(anno.defaultEnabled()); + type = anno.type(); + } + } + + public void setName(String name) { + this.name = name; + } + + public void setEnabled(boolean isEnabled) { + this.isEnabled = isEnabled; + } + + protected void setInfo(String key, Object value) { + this.storageInfo.put(key, value); + } + + @Override + public String getName() { + return name; + } + + @Override + public String getType() { + return type; + } + + @Override + public Map getInfo() { + return Collections.unmodifiableMap(storageInfo); + } + + @Override + public boolean isEnabled() { + return isEnabled; + } + + @Override + public void enable() { + setEnabled(true); + } + + @Override + public void disable() { + setEnabled(false); + } + +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/storage/ApplicationStorageInfo.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/storage/ApplicationStorageInfo.java new file mode 100644 index 00000000..e70ee539 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/storage/ApplicationStorageInfo.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface ApplicationStorageInfo { + String name(); + + String type() default "unknown"; + + boolean defaultEnabled() default true; +} diff --git a/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/utils/JarArtifact.java b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/utils/JarArtifact.java new file mode 100644 index 00000000..053a39b8 --- /dev/null +++ b/platform/integration/applications/application-api/src/main/java/ru/entaxy/platform/integration/applications/utils/JarArtifact.java @@ -0,0 +1,30 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.utils; + +public class JarArtifact { + +} diff --git a/platform/integration/applications/application-impl/LICENSE.txt b/platform/integration/applications/application-impl/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/applications/application-impl/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/application-impl/pom.xml b/platform/integration/applications/application-impl/pom.xml new file mode 100644 index 00000000..a956e4dd --- /dev/null +++ b/platform/integration/applications/application-impl/pom.xml @@ -0,0 +1,142 @@ + + + 4.0.0 + + ru.entaxy.platform.integration + applications + 1.10.0 + + ru.entaxy.platform.integration.applications + application-impl + bundle + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: IMPL + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: IMPL + + + ru.entaxy.platform.integration.applications.impl, + ru.entaxy.platform.integration.applications.impl.* + + + + + + org.apache.felix + maven-bundle-plugin + true + + + true + + + + + + + + + + ru.entaxy.platform.integration.applications + application-api + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + + + ru.entaxy.esb.platform.runtime.core + artifact-management + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + org.apache.karaf + org.apache.karaf.util + + + + + ru.entaxy.esb.platform.runtime.core + artifact-management-extensions + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + org.apache.karaf + org.apache.karaf.util + + + + + commons-io + commons-io + ${commons-io.version} + + + ru.entaxy.esb.platform.runtime.base.connecting.generator + generator-api + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + org.apache.karaf + org.apache.karaf.util + + + + + ru.entaxy.esb.platform.runtime.base.connecting.generator + generator-factory + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + + + ru.entaxy.esb.platform.runtime.base + cellar-extensions + ${project.version} + + + org.apache.felix + org.apache.felix.scr + + + org.apache.karaf + org.apache.karaf.util + + + + + ru.entaxy.esb.platform.runtime.core.objects-implementations.config-implementation + config-runtime + ${project.version} + + + + diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ApplicationManagerImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ApplicationManagerImpl.java new file mode 100644 index 00000000..3d2c186d --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ApplicationManagerImpl.java @@ -0,0 +1,175 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.platform.integration.applications.ApplicationManager; +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportContent; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationImportCausedException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.exceptions.StorageNotEnabledException; +import ru.entaxy.platform.integration.applications.exceptions.StorageNotFoundException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionBuildNotAvailable; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionCausedException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; + +@Component(service = ApplicationManager.class, immediate = true) +public class ApplicationManagerImpl implements ApplicationManager { + + protected Map storages = new HashMap<>(); + protected Object storagesLock = new Object(); + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile ExportImportHelper exportImportHelper; + + @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY, unbind = "unregisterStorage") + public void registerStorage(ApplicationStorage storage) { + synchronized (storagesLock) { + storages.put(storage.getName(), storage); + } + } + + public void unregisterStorage(ApplicationStorage storage) { + synchronized (storagesLock) { + storages.remove(storage.getName()); + } + } + + protected ApplicationStorage getStorageUnsafe(String storageName) throws StorageException { + ApplicationStorage storage = storages.get(storageName); + if (storage == null) + throw new StorageNotFoundException(storageName); + if (!storage.isEnabled()) + throw new StorageNotEnabledException(storageName); + return storage; + } + + /* ApplicationManager implementation */ + + @Override + public ApplicationStorage getStorage(String storageName) { + return storages.get(storageName); + } + + @Override + public List getAllStorages() { + return new ArrayList<>(storages.values()); + } + + @Override + public void addStorage(ApplicationStorage applicationStorage) { + // TODO Auto-generated method stub + + } + + @Override + public void removeStorage(ApplicationStorage applicationStorage) { + // TODO Auto-generated method stub + + } + + @Override + public void exportToFile(EntaxyApplicationProjectVersion version, String filePath) throws ProjectVersionException { + if (!version.isBuildAvailable()) + throw new ProjectVersionBuildNotAvailable(version.getApplication().getName(), version.getVersionNumber()); + Map props = new HashMap<>(); + props.put("filePath", filePath); + try { + exportImportHelper.doExport(version, "file", props); + } catch (ProjectVersionException ve) { + throw ve; + } catch (Exception e) { + throw new ProjectVersionCausedException(version.getApplication().getName(), version.getVersionNumber(), e); + } + } + + @Override + public void exportToRepository(EntaxyApplicationProjectVersion version, String repositoryName) + throws ProjectVersionException { + if (!version.isBuildAvailable()) + throw new ProjectVersionBuildNotAvailable(version.getApplication().getName(), version.getVersionNumber()); + Map props = new HashMap<>(); + props.put("repositoryName", repositoryName); + try { + exportImportHelper.doExport(version, "repository", props); + } catch (ProjectVersionException ve) { + throw ve; + } catch (Exception e) { + throw new ProjectVersionCausedException(version.getApplication().getName(), version.getVersionNumber(), e); + } + } + + @Override + public EntaxyApplication importApplicationFromFile(String storageName, String filePath) + throws ApplicationException, StorageException { + Map props = new HashMap<>(); + props.put("filePath", filePath); + try { + ApplicationImportContent result = exportImportHelper.doImport("file", props); + return createApplicationFromImport(storageName, result); + } catch (Exception e) { + throw new ApplicationImportCausedException(filePath, e); + } + } + + @Override + public EntaxyApplication importApplicationFromRepository(String storageName, String mavenUrl) + throws ApplicationException, StorageException { + Map props = new HashMap<>(); + props.put("mavenUrl", mavenUrl); + try { + ApplicationImportContent result = exportImportHelper.doImport("repository", props); + return createApplicationFromImport(storageName, result); + } catch (Exception e) { + throw new ApplicationImportCausedException(mavenUrl, e); + } + } + + protected EntaxyApplication createApplicationFromImport(String storageName, ApplicationImportContent importContent) + throws Exception { + ApplicationStorage storage = getStorageUnsafe(storageName); + EntaxyApplication result = storage.createApplication(importContent); + importContent.clear(); + return result; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ApplicationObjectExtendedDataProvider.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ApplicationObjectExtendedDataProvider.java new file mode 100644 index 00000000..d38b4b33 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ApplicationObjectExtendedDataProvider.java @@ -0,0 +1,121 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.karaf.features.Feature; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptor; +import ru.entaxy.platform.base.support.osgi.feature.FeatureCapabilityHelper; +import ru.entaxy.platform.base.support.osgi.feature.FeaturesUtils; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectExtendedDataProvider; + +@Component(service = EntaxyRuntimeObjectExtendedDataProvider.class, immediate = true) +public class ApplicationObjectExtendedDataProvider implements EntaxyRuntimeObjectExtendedDataProvider { + + private static final Logger LOG = LoggerFactory.getLogger(ApplicationObjectExtendedDataProvider.class); + + private static final String APPLICATIONS_PROVIDER_ID = "applications"; + + protected final static String APP_NAMESPACE = "entaxy.application"; + + protected BundleContext bundleContext; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + } + + @Override + public String getProviderId() { + return APPLICATIONS_PROVIDER_ID; + } + + @Override + public Map getExtendedData(EntaxyRuntimeObject runtimeObject) { + Map result = new HashMap<>(); + try { + Bundle b = bundleContext.getBundle(runtimeObject.getBundleInfo().getBundleId()); + List features = FeaturesUtils.FeaturesHelper.create(bundleContext) + .withCapabilityNamespace(APP_NAMESPACE).containingBundle(b).find(); + if (features.isEmpty()) + return null; + + List> applicationData = new ArrayList<>(); + for (Feature feature : features) { + List> featureApplications = getApplicationData(feature); + if (!featureApplications.isEmpty()) + applicationData.addAll(featureApplications); + } + + if (applicationData.isEmpty()) + return null; + + result.put("application", applicationData); + result.put("managed", true); + + } catch (Exception e) { + result.put("error", String.format("[%s:%s]", e.getClass().getName(), e.getMessage())); + LOG.error(String.format("Error getting extended data for [$s]", runtimeObject.getObjectFullId()), e); + } + return result; + } + + protected List> getApplicationData(Feature feature) { + List> result = new ArrayList<>(); + + FeatureCapabilityHelper capabilityHelper = new FeatureCapabilityHelper(feature); + List descriptors = capabilityHelper.getProvidedCapabilities(APP_NAMESPACE); + for (CapabilityDescriptor descriptor : descriptors) { + String name = descriptor.getAttributes().getOrDefault("name", "").toString(); + if (!CommonUtils.isValid(name)) + continue; + String version = descriptor.getAttributes().getOrDefault("version", "").toString(); + String revision = descriptor.getAttributes().getOrDefault("revision", "").toString(); + + Map data = new HashMap<>(); + data.put("name", name); + data.put("version", version); + data.put("revision", revision); + result.add(data); + } + return result; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ExportImportHelper.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ExportImportHelper.java new file mode 100644 index 00000000..121d26e3 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ExportImportHelper.java @@ -0,0 +1,440 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.osgi.framework.ServiceException; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.base.support.osgi.OSGIUtils; +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.core.artifact.Artifacts; +import ru.entaxy.platform.core.artifact.repository.ArtifactRepository; +import ru.entaxy.platform.core.artifact.service.ArtifactService; +import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportContent; +import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationDescriptorIsInvalid; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationDescriptorNotFound; + +@Component(service = ExportImportHelper.class, immediate = true) +public class ExportImportHelper { + + private static final Logger LOG = LoggerFactory.getLogger(ExportImportHelper.class); + + public final Map exporters = new HashMap<>(); + + public final Map importers = new HashMap<>(); + + protected static ExportImportHelper INSTANCE = null; + + @Activate + public void activate() { + exporters.put("file", new FileExporter()); + exporters.put("repository", new RepositoryExporter()); + importers.put("file", new FileImporter()); + importers.put("repository", new RepositoryImporter()); + ExportImportHelper.INSTANCE = this; + } + + public void doExport(EntaxyApplicationProjectVersion version, String exporterType, Map properties) + throws Exception { + if (!exporters.containsKey(exporterType)) + return; + Exporter exporter = exporters.get(exporterType); + exporter.execute(version, properties); + } + + public ApplicationImportContent doImport(String importerType, Map properties) + throws Exception { + if (!importers.containsKey(importerType)) + return null; + Importer importer = importers.get(importerType); + return importer.execute(properties); + } + + // importers + + + protected static class JarFileImportContent implements ApplicationImportContent { + + protected interface Cleaner { + void clean() throws Exception; + } + + protected static class FileCleaner implements Cleaner { + + protected File file; + + public FileCleaner(File file) { + this.file = file; + } + + @Override + public void clean() throws Exception { + file.delete(); + } + + } + + protected JarFile jarFile; + + protected Map items; + + protected Cleaner cleaner; + + public JarFileImportContent(JarFile jarFile) { + super(); + items = new HashMap<>(); + this.jarFile = jarFile; + Iterator entries = jarFile.entries().asIterator(); + while (entries.hasNext()) { + JarEntryImportItem item = new JarEntryImportItem(jarFile, entries.next()); + items.put(item.getPath(), item); + } + } + + public void setCleaner(Cleaner cleaner) { + this.cleaner = cleaner; + } + + @Override + public Map getItems() { + return items; + } + + @Override + public void clear() { + try { + jarFile.close(); + } catch (IOException ignore) { + // NOOP + } + if (cleaner != null) + try { + cleaner.clean(); + } catch (Exception ignore) { + // NOOP + } + } + + } + + protected static class JarEntryImportItem implements ApplicationImportItem { + + protected JarFile jarFile; + protected JarEntry jarEntry; + + protected String name; + protected String path; + protected String location; + + public JarEntryImportItem(JarFile jarFile, JarEntry jarEntry) { + super(); + this.jarEntry = jarEntry; + this.jarFile = jarFile; + init(); + } + + protected void init() { + path = jarEntry.getName(); + int index = path.lastIndexOf('/'); + if (index > 0) { + name = path.substring(index + 1); + location = path.substring(0, index); + } else { + name = path; + location = ""; + } + } + + @Override + public String getName() { + return name; + } + + @Override + public String getLocation() { + return location; + } + + @Override + public String getPath() { + return path; + } + + @Override + public InputStream getInputStream() throws IOException { + return jarFile.getInputStream(jarEntry); + } + + } + + protected abstract static class Importer { + + public abstract ApplicationImportContent execute(Map properties) + throws Exception; + + } + + protected static class FileImporter extends Importer { + + @Override + public ApplicationImportContent execute(Map properties) throws Exception { + String filePath = properties.getOrDefault("filePath", "").toString(); + if (!CommonUtils.isValid(filePath)) + throw new IllegalArgumentException("Invalid filePath: " + filePath); + File targetFile = new File(filePath); + if (!targetFile.exists()) + throw new IllegalArgumentException("File not exists: " + filePath); + if (targetFile.isDirectory()) + throw new IllegalArgumentException("File is directory: " + filePath); + JarFile jarFile = new JarFile(targetFile); + return new JarFileImportContent(jarFile); + } + + } + + protected static class RepositoryImporter extends Importer { + + @Override + public ApplicationImportContent execute(Map properties) throws Exception { + String mavenUrl = properties.getOrDefault("mavenUrl", "").toString(); + if (!CommonUtils.isValid(mavenUrl)) + throw new IllegalArgumentException("mavenUrl not set"); + if (!mavenUrl.startsWith("mvn:")) + mavenUrl = "mvn:" + mavenUrl; + + URL url = new URL(mavenUrl); + File tempFile = File.createTempFile("app-import-", Calendar.getInstance().getTimeInMillis() + ""); + try (InputStream is = url.openStream()) { + Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + + Map props = new HashMap<>(); + props.put("filePath", tempFile.getAbsolutePath()); + + ApplicationImportContent result = ExportImportHelper.INSTANCE.doImport("file", props); + ((JarFileImportContent) result).setCleaner(new JarFileImportContent.FileCleaner(tempFile)); + + return result; + } + + } + + // exporters + + protected abstract static class Exporter { + + public abstract void execute(EntaxyApplicationProjectVersion version, Map properties) + throws Exception; + + } + + protected static class FileExporter extends Exporter { + + @Override + public void execute(EntaxyApplicationProjectVersion version, Map properties) throws Exception { + String filePath = properties.getOrDefault("filePath", "").toString(); + if (filePath.endsWith("/")) { + // it's directory + String url = version.getBuildUrl().toString(); + String fileName = url.substring(url.lastIndexOf('/')); + filePath = filePath.concat(fileName); + } + if (!CommonUtils.isValid(filePath)) + return; + File targetFile = new File(filePath); + targetFile.getAbsoluteFile().getParentFile().mkdirs(); + try (FileOutputStream fos = new FileOutputStream(targetFile); + InputStream is = version.getBuild();) { + fos.write(is.readAllBytes()); + } + } + + } + + protected static class RepositoryExporter extends Exporter { + + @Override + public void execute(EntaxyApplicationProjectVersion version, Map properties) throws Exception { + ArtifactService artifactService = + OSGIUtils.services().ofClass(ArtifactService.class).waitService(20000).get(); + if (artifactService == null) + throw new ServiceException("Service not found: ArtifactService.class"); + + String repositoryName = properties.getOrDefault("repositoryName", "").toString(); + if (!CommonUtils.isValid(repositoryName)) + throw new IllegalArgumentException("repositoryName not set"); + + ArtifactRepository repo = artifactService.getRepository(repositoryName); + if (repo == null) + throw new IllegalArgumentException("Repository not found: " + repositoryName); + if (repo.isReadOnly()) { + throw new IllegalArgumentException("Repository " + repositoryName + " is read only."); + } + + Artifact artifact = Artifacts.create(Artifact.ARTIFACT_CATEGORY_JAR); + String mavenCoordinates = version.getBuildInfo().mavenUrl; + artifact.getCoordinates().update(ArtifactCoordinates.fromUrl(mavenCoordinates)); + try (InputStream is = version.getBuild()) { + artifact.setContent(is); + repo.deploy(artifact); + } + + } + + } + public static class ApplicationImporter { + + static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + protected StorageImportAdapter storageAdapter; + + protected ApplicationDescriptor applicationDescriptor = null; + + public ApplicationImporter(StorageImportAdapter storageAdapter) { + super(); + this.storageAdapter = storageAdapter; + } + + public void executeImport(ApplicationImportContent importContent) throws Exception { + // check descriptor + String applicationName = "unknown"; + ApplicationImportItem descriptorItem = importContent.getItems().get(EntaxyApplication.DESCRIPTOR_NAME); + + if (descriptorItem == null) + throw new ApplicationDescriptorNotFound(applicationName); + try (InputStream is = descriptorItem.getInputStream()) { + String descriptorData = new String(is.readAllBytes()); + applicationDescriptor = + GSON.fromJson(JSONUtils.getJsonRootObject(descriptorData), ApplicationDescriptor.class); + } catch (Exception e1) { + throw new ApplicationDescriptorIsInvalid(applicationName); + } + if (applicationDescriptor == null) + throw new ApplicationDescriptorIsInvalid(applicationName); + + // if something's wrong with descriptor, exception is thrown + storageAdapter.checkDescriptor(applicationDescriptor); + applicationName = applicationDescriptor.name; + + // if something's wrong, exception is thrown + StorageApplicationContentAdapter contentAdapter = + storageAdapter.getContentAdapter(applicationName, applicationDescriptor); + fillContent(applicationDescriptor, importContent, contentAdapter); + EntaxyApplicationVersion createdVersion = + storageAdapter.getVersion(applicationName, applicationDescriptor.version); + if (createdVersion == null) { + throw new java.lang.InstantiationException("Version not created"); + } + EntaxyApplicationRevision revision = createdVersion.createRevision(); + if (revision == null) { + throw new java.lang.InstantiationException("Revision not created"); + } + + } + + public ApplicationDescriptor getApplicationDescriptor() { + return applicationDescriptor; + } + + protected void fillContent(ApplicationDescriptor descriptor, ApplicationImportContent source, + StorageApplicationContentAdapter target) throws Exception { + + List locationsToProcess = new ArrayList<>(source.getItems().keySet()); + + // we skip descriptor 'cause it's already there + locationsToProcess.remove(EntaxyApplication.DESCRIPTOR_NAME); + + // we ignore manifest + locationsToProcess.remove("META-INF/MANIFEST.MF"); + + + // load features + if (descriptor.features == null) + throw new IllegalArgumentException("Features not found in descriptor"); + StorageItemAdapter item = target.createItem(descriptor.features); + try (InputStream is = source.getItems().get(descriptor.features.internalLocation).getInputStream()) { + item.write(is); + } catch (Exception e) { + LOG.error("Error writing [" + descriptor.features.internalLocation + "]", e); + } + locationsToProcess.remove(descriptor.features.internalLocation); + + // load components + for (ApplicationComponent comp : descriptor.getComponents()) { + item = target.createItem(comp); + try (InputStream is = source.getItems().get(comp.getInternalLocation()).getInputStream()) { + item.write(is); + } catch (Exception e) { + LOG.error("Error writing [" + comp.getInternalLocation() + "]", e); + } + locationsToProcess.remove(comp.getInternalLocation()); + } + + // left only resources + for (String location : locationsToProcess) { + try (InputStream is = source.getItems().get(location).getInputStream()) { + target.createResource(location, is); + } catch (Exception e) { + LOG.error("Error writing [" + location + "]", e); + } + } + + } + + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ServiceHelper.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ServiceHelper.java new file mode 100644 index 00000000..36144c68 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/ServiceHelper.java @@ -0,0 +1,94 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import org.apache.karaf.bundle.core.BundleService; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.base.generator.template.TemplateService; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +@Component(service = ServiceHelper.class, immediate = true) +public class ServiceHelper { + + private static ServiceHelper INSTANCE; + + public static ServiceHelper getInstance() { + return INSTANCE; + } + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile EntaxyResourceService entaxyResourceService; + + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile TemplateService templateService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile BundleService bundleService; + + @Activate + public void activate() { + INSTANCE = this; + } + + public EntaxyRuntimeObjectService getEntaxyRuntimeObjectService() { + return entaxyRuntimeObjectService; + } + + public EntaxyResourceService getEntaxyResourceService() { + return entaxyResourceService; + } + + public TemplateService getTemplateService() { + return templateService; + } + + public BundleService getBundleService() { + return bundleService; + } + + public boolean objectExists(String objectFullId) { + return entaxyRuntimeObjectService.getRuntimeObject(objectFullId) != null; + } + + public boolean resourceExists(String resourceUrl) { + return entaxyResourceService.getResource(resourceUrl).exists(); + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageApplicationContentAdapter.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageApplicationContentAdapter.java new file mode 100644 index 00000000..fd8d71a5 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageApplicationContentAdapter.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import java.io.InputStream; + +import ru.entaxy.platform.integration.applications.ApplicationResource; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; + +public interface StorageApplicationContentAdapter { + + StorageItemAdapter createItem(ApplicationComponent applicationComponent) throws Exception; + + ApplicationResource createResource(String location, InputStream inputStream) throws Exception; + + StorageItemAdapter getItemAdapter(String location) throws Exception; + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageImportAdapter.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageImportAdapter.java new file mode 100644 index 00000000..c2f8b51f --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageImportAdapter.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; + +public interface StorageImportAdapter { + + void checkDescriptor(ApplicationDescriptor applicationDescriptor) throws ApplicationException, StorageException; + + StorageApplicationContentAdapter getContentAdapter(String applicationName, + ApplicationDescriptor applicationDescriptor) throws ApplicationException, StorageException; + + EntaxyApplicationVersion getVersion(String applicationName, String version) + throws ApplicationException, StorageException; +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageItemAdapter.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageItemAdapter.java new file mode 100644 index 00000000..7512ea8e --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/StorageItemAdapter.java @@ -0,0 +1,36 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl; + +import java.io.InputStream; + +public interface StorageItemAdapter { + + InputStream getInputStream(); + + void write(InputStream source) throws Exception; + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationContentImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationContentImpl.java new file mode 100644 index 00000000..401812e2 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationContentImpl.java @@ -0,0 +1,70 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.application; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import ru.entaxy.platform.integration.applications.ApplicationContent; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.ApplicationResource; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; + +public class ApplicationContentImpl implements ApplicationContent { + + protected ApplicationDescriptor descriptor; + + protected Map items = new HashMap<>(); + + protected Map resources = new HashMap<>(); + + public ApplicationContentImpl(ApplicationDescriptor descriptor) { + super(); + this.descriptor = descriptor; + } + + public void setDescriptor(ApplicationDescriptor descriptor) { + this.descriptor = descriptor; + } + + @Override + public ApplicationDescriptor getDescriptor() { + return descriptor; + } + + @Override + public List getItems() { + return items.values().stream().collect(Collectors.toList()); + } + + @Override + public List getResources() { + return resources.values().stream().collect(Collectors.toList()); + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationItemImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationItemImpl.java new file mode 100644 index 00000000..a4b02eab --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationItemImpl.java @@ -0,0 +1,95 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.application; + +import java.io.InputStream; + +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.impl.StorageItemAdapter; + +public class ApplicationItemImpl implements ApplicationItem { + + protected String id; + protected EntaxyApplication.ITEM_TYPE type; + protected String location; + + protected boolean isRevisionable = true; + protected boolean isEditable = true; + + protected transient StorageItemAdapter itemAdapter; + + public ApplicationItemImpl(ApplicationComponent applicationComponent, StorageItemAdapter itemAdapter) { + super(); + this.itemAdapter = itemAdapter; + id = applicationComponent.id; + type = applicationComponent.type; + location = applicationComponent.internalLocation; + isRevisionable = ITEM_TYPE.CONFIG.equals(type) || ITEM_TYPE.FEATURES.equals(type); + isEditable = ITEM_TYPE.CONFIG.equals(type); + } + + + + @Override + public InputStream getInputStream() { + return itemAdapter.getInputStream(); + } + + @Override + public void update(InputStream inputStream) throws Exception { + this.itemAdapter.write(inputStream); + } + + @Override + public String getId() { + return id; + } + + @Override + public EntaxyApplication.ITEM_TYPE getType() { + return type; + } + + @Override + public String getLocation() { + return location; + } + + @Override + public boolean isRevisionable() { + return isRevisionable; + } + + @Override + public boolean isEditable() { + return isEditable; + } + + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationResourceImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationResourceImpl.java new file mode 100644 index 00000000..b21fb5d2 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/ApplicationResourceImpl.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.application; + +import java.io.InputStream; + +import ru.entaxy.platform.integration.applications.ApplicationResource; + +public class ApplicationResourceImpl implements ApplicationResource { + + @Override + public InputStream getInputStream() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/RevisionHelper.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/RevisionHelper.java new file mode 100644 index 00000000..f213621d --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/application/RevisionHelper.java @@ -0,0 +1,443 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.application; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.base.generator.template.Template; +import ru.entaxy.base.generator.template.TemplateAwareGenerator; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.factory.GeneratorFactory; +import ru.entaxy.platform.base.support.osgi.OSGIUtils; +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.core.artifact.Artifacts; +import ru.entaxy.platform.core.artifact.ext.ArtifactExtended; +import ru.entaxy.platform.core.artifact.ext.features.FeatureInstaller; +import ru.entaxy.platform.core.artifact.ext.features.FeaturesInstaller; +import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult; +import ru.entaxy.platform.core.artifact.service.ArtifactService; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision.REVISION_STATUS; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationFeatures; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; +import ru.entaxy.platform.integration.applications.exceptions.RevisionCausedException; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.exceptions.RevisionIllegalTransition; +import ru.entaxy.platform.integration.applications.exceptions.RevisionNotConfigurable; +import ru.entaxy.platform.integration.applications.exceptions.RevisionRequirementsNotSatisfied; +import ru.entaxy.platform.integration.applications.impl.ServiceHelper; +import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceManager; + +public class RevisionHelper { + + private static final Logger LOG = LoggerFactory.getLogger(RevisionHelper.class); + + public static interface RevisionHelperAdapter { + REVISION_STATUS getCurrentStatus(); + + void updateStatus(REVISION_STATUS newStatus); + + int getRevisionNumber(); + + void writeItem(String location, InputStream inputStream) throws Exception; + } + + protected ApplicationContentImpl applicationContent; + protected RevisionHelperAdapter adapter; + + protected int revisionNumber; + + protected REVISION_STATUS currentStatus; + + protected String applicationName; + + protected String version; + + public RevisionHelper(ApplicationContentImpl applicationContent, RevisionHelperAdapter adapter) { + super(); + this.applicationContent = applicationContent; + this.adapter = adapter; + this.revisionNumber = this.adapter.getRevisionNumber(); + this.currentStatus = this.adapter.getCurrentStatus(); + this.applicationName = applicationContent.getDescriptor().name; + this.version = applicationContent.getDescriptor().version; + } + + public void configure() throws RevisionException { + if (applicationContent.getEditables().isEmpty()) + throw new RevisionNotConfigurable(applicationName, + version, revisionNumber); + // revision 0 is not configured !!! + if (revisionNumber == 0) { + throw new RevisionNotConfigurable(applicationName, + version, revisionNumber); + } + if (!REVISION_STATUS.NEW.equals(currentStatus) && !REVISION_STATUS.CONFIGURED.equals(currentStatus) + && !REVISION_STATUS.DEPLOYED.equals(currentStatus)) + throw new RevisionIllegalTransition(applicationName, version, revisionNumber, currentStatus, + REVISION_STATUS.CONFIGURED); + currentStatus = REVISION_STATUS.CONFIGURED; + adapter.updateStatus(currentStatus); + } + + public void deploy() throws RevisionException { + if (REVISION_STATUS.INSTALLED.equals(currentStatus) || REVISION_STATUS.UNINSTALLED.equals(currentStatus) + || REVISION_STATUS.DEPLOYED.equals(currentStatus)) + throw new RevisionIllegalTransition(applicationName, version, revisionNumber, currentStatus, + REVISION_STATUS.DEPLOYED); + + try { + ArtifactService artifactService = + OSGIUtils.services().ofClass(ArtifactService.class).waitService(2000).get(); + + if (artifactService == null) + throw new IllegalArgumentException("ArtifactService not available"); + + Map componentMap = new HashMap<>(); + componentMap.put(applicationContent.getDescriptor().getFeatures().internalLocation, + applicationContent.getDescriptor().getFeatures()); + for (ApplicationComponent comp : applicationContent.getDescriptor().getComponents()) + componentMap.put(comp.internalLocation, comp); + + for (ApplicationItem item : applicationContent.getItems()) { + + ApplicationComponent comp = componentMap.get(item.getLocation()); + if (comp == null) + continue; + + Artifact artifact = Artifacts.create(ArtifactExtended.ARTIFACT_CATEGORY_UNTYPED_BINARY); + artifact.getCoordinates().set(ArtifactCoordinates.fromUrl(comp.mavenLocation)); + try (InputStream is = item.getInputStream()) { + artifact.setContent(is); + artifactService.deployShared(artifact); + } + } + + } catch (RevisionException rethrow) { + throw rethrow; + } catch (Exception e) { + throw new RevisionCausedException(applicationName, e, version, revisionNumber); + } + + + currentStatus = REVISION_STATUS.DEPLOYED; + adapter.updateStatus(currentStatus); + + } + + public void install() throws RevisionException { + if (!REVISION_STATUS.DEPLOYED.equals(currentStatus) && !REVISION_STATUS.UNINSTALLED.equals(currentStatus)) + throw new RevisionIllegalTransition(applicationName, version, revisionNumber, currentStatus, + REVISION_STATUS.INSTALLED); + List failed = checkRequirements(); + if (!failed.isEmpty()) + throw new RevisionRequirementsNotSatisfied(applicationName, version, revisionNumber, failed); + + try { + ArtifactService artifactService = + OSGIUtils.services().ofClass(ArtifactService.class).waitService(2000).get(); + + if (artifactService == null) + throw new IllegalArgumentException("ArtifactService not available"); + + CellarSequenceManager sequenceManager = + OSGIUtils.services().ofClass(CellarSequenceManager.class).waitService(2000).get(); + + if (sequenceManager == null) + throw new IllegalArgumentException("CellarSequenceManager not available"); + + + String sequenceId = applicationContent.getDescriptor().getFeatures().mavenLocation; + + FeaturesInstaller installer = + artifactService.installers().cluster().typed(FeaturesInstaller.class).refresh() + .inSequence(sequenceId); + installer.setSourceLocation(applicationContent.getDescriptor().getFeatures().getFullTargetLocation()); + InstallationResult result = installer.install(); + + if (!result.isSuccessful()) { + if (result.getError() != null) + throw new Exception(result.getMessage(), result.getError()); + } + + FeatureInstaller featureInstaller = artifactService.installers().cluster().typed(FeatureInstaller.class); + String featureVersion = ArtifactCoordinates + .fromUrl(applicationContent.getDescriptor().getFeatures().mavenLocation).getVersion(); + InstallationResult featureResult = featureInstaller + .inSequence(sequenceId) + .feature(applicationContent.getDescriptor().getFeatures().getId()) + .version(featureVersion) + .noRefresh() + .upgrade() + .install(); + + // set up sequence + + sequenceManager.getSequence(sequenceId).getEvent().setWaitLast(false); + + // process sequence + + sequenceManager.produceSequence(sequenceId); + sequenceManager.releaseSequence(sequenceId); + + if (!featureResult.isSuccessful()) { + InstallationResult firstFailedSubresult = null; + for (InstallationResult res : featureResult.getSubResults()) + if (!res.isSuccessful()) { + firstFailedSubresult = res; + break; + } + if (firstFailedSubresult == null) + throw new Exception("Feature installation failed"); + + if (firstFailedSubresult.getError() != null) + throw new Exception("Feature installation failed: [" + firstFailedSubresult.getObject() != null + ? firstFailedSubresult.getObject().toString() + : "unknown" + "]", firstFailedSubresult.getError()); + else + throw new Exception("Feature installation failed: [" + firstFailedSubresult.getObject() != null + ? firstFailedSubresult.getObject().toString() + : "unknown" + "]"); + } + + List failedfeatures = new ArrayList<>(); + for (InstallationResult res : featureResult.getSubResults()) + if (!res.isSuccessful()) { + // TODO implement rollback if we have failed subresults + if (res.getObject() != null) + failedfeatures.add(res.getObject().toString()); + else + failedfeatures.add("unknown_" + failedfeatures.size()); + } + + if (!failedfeatures.isEmpty()) + throw new Exception("Feature installation failed: [" + + failedfeatures.stream().collect(Collectors.joining(",")) + "]"); + } catch (RevisionException rethrow) { + throw rethrow; + } catch (Exception e) { + throw new RevisionCausedException(applicationName, e, version, revisionNumber); + } + + currentStatus = REVISION_STATUS.INSTALLED; + adapter.updateStatus(currentStatus); + + } + + public void uninstall() throws RevisionException { + if (!REVISION_STATUS.INSTALLED.equals(currentStatus)) + throw new RevisionIllegalTransition(applicationName, version, revisionNumber, currentStatus, + REVISION_STATUS.UNINSTALLED); + + try { + ArtifactService artifactService = + OSGIUtils.services().ofClass(ArtifactService.class).waitService(2000).get(); + + if (artifactService == null) + throw new IllegalArgumentException("ArtifactService not available"); + + CellarSequenceManager sequenceManager = + OSGIUtils.services().ofClass(CellarSequenceManager.class).waitService(2000).get(); + + if (sequenceManager == null) + throw new IllegalArgumentException("CellarSequenceManager not available"); + + + String sequenceId = applicationContent.getDescriptor().getFeatures().mavenLocation; + + FeaturesInstaller installer = + artifactService.installers().cluster().typed(FeaturesInstaller.class).refresh() + .inSequence(sequenceId); + installer.setSourceLocation(applicationContent.getDescriptor().getFeatures().getFullTargetLocation()); + InstallationResult result = installer.uninstall(); + + if (!result.isSuccessful()) { + if (result.getError() != null) + throw new Exception(result.getMessage(), result.getError()); + } + + FeatureInstaller featureInstaller = artifactService.installers().cluster().typed(FeatureInstaller.class); + String featureVersion = ArtifactCoordinates + .fromUrl(applicationContent.getDescriptor().getFeatures().mavenLocation).getVersion(); + InstallationResult featureResult = featureInstaller + .inSequence(sequenceId) + .feature(applicationContent.getDescriptor().getFeatures().getId()) + .version(featureVersion) + .noRefresh() + .uninstall(); + + // set up sequence + + sequenceManager.getSequence(sequenceId).getEvent().setWaitLast(false); + + // process sequence + + sequenceManager.produceSequence(sequenceId); + sequenceManager.releaseSequence(sequenceId); + + if (!featureResult.isSuccessful()) { + InstallationResult firstFailedSubresult = null; + for (InstallationResult res : featureResult.getSubResults()) + if (!res.isSuccessful()) { + firstFailedSubresult = res; + break; + } + if (firstFailedSubresult == null) + throw new Exception("Feature uninstallation failed"); + + if (firstFailedSubresult.getError() != null) + throw new Exception("Feature uninstallation failed: [" + firstFailedSubresult.getObject() != null + ? firstFailedSubresult.getObject().toString() + : "unknown" + "]", firstFailedSubresult.getError()); + else + throw new Exception("Feature uninstallation failed: [" + firstFailedSubresult.getObject() != null + ? firstFailedSubresult.getObject().toString() + : "unknown" + "]"); + } + + List failedfeatures = new ArrayList<>(); + for (InstallationResult res : featureResult.getSubResults()) + if (!res.isSuccessful()) { + // TODO implement rollback if we have failed subresults + if (res.getObject() != null) + failedfeatures.add(res.getObject().toString()); + else + failedfeatures.add("unknown_" + failedfeatures.size()); + } + + if (!failedfeatures.isEmpty()) + throw new Exception("Feature installation failed: [" + + failedfeatures.stream().collect(Collectors.joining(",")) + "]"); + } catch (RevisionException rethrow) { + throw rethrow; + } catch (Exception e) { + throw new RevisionCausedException(applicationName, e, version, revisionNumber); + } + + currentStatus = REVISION_STATUS.UNINSTALLED; + adapter.updateStatus(currentStatus); + + } + + protected List checkRequirements() { + List result = new ArrayList<>(); + for (ApplicationRequirement req : applicationContent.getDescriptor().getRequirements()) { + if (!checkRequirement(req)) + result.add(req); + } + return result; + } + + protected boolean checkRequirement(ApplicationRequirement req) { + if (EntaxyApplication.ITEM_TYPE.OBJECT.equals(req.getType())) { + return ServiceHelper.getInstance().objectExists(req.getId()); + } + if (EntaxyApplication.ITEM_TYPE.RESOURCE.equals(req.getType())) { + return ServiceHelper.getInstance().resourceExists(req.getId()); + } + return true; + } + + public void update() throws Exception { + updateComponentVersions(); + updateFeatures(); + } + + protected void updateComponentVersions() throws Exception { + List components = new ArrayList<>(); + components.add(applicationContent.getDescriptor().features); + + components.addAll(applicationContent.getDescriptor().getComponents()); + + List revisionableIds = applicationContent.getItems().stream().filter(item -> item.isRevisionable()) + .map(item -> item.getId()).collect(Collectors.toList()); + + for (ApplicationComponent component : components) { + + if (!revisionableIds.contains(component.id)) + continue; + + ArtifactCoordinates coordinates = ArtifactCoordinates.fromUrl(component.mavenLocation); + coordinates.qualifier(String.format("REV_%03d", revisionNumber)); + component.mavenLocation = coordinates.toMavenString(); + coordinates = ArtifactCoordinates.fromUrl(component.targetLocation); + // coordinates may be null for configs + if (coordinates == null) + continue; + coordinates.qualifier(String.format("REV_%03d", revisionNumber)); + component.targetLocation = coordinates.toMavenString(); + } + } + + protected void updateFeatures() throws Exception { + + Template template = + ServiceHelper.getInstance().getTemplateService().getTemplateById("applications.builder.features"); + TemplateAwareGenerator generator = GeneratorFactory.createGenerator(template); + + if (generator != null) { + ApplicationFeatures features = applicationContent.getDescriptor().getFeatures(); + ArtifactCoordinates coord = ArtifactCoordinates.fromUrl(features.mavenLocation); + String repoName = String.format("%s.%s-%s", coord.getGroupId(), coord.getArtifactId(), coord.getVersion()); + String featureName = String.format("%s.%s", coord.getGroupId(), coord.getArtifactId()); + + // convert to OSGI-style version + String featureVersion = coord.getVersion().replace('-', '.'); + + Map params = new HashMap<>(); + params.put("descriptor", applicationContent.getDescriptor()); + params.put("repoName", repoName); + params.put("featureName", featureName); + params.put("featureVersion", featureVersion); + params.put("revisionNumber", revisionNumber + ""); + Generated generated; + generated = generator.generate(template, params); + if ((generated == null) || (generated.getObject() == null)) { + throw new IllegalArgumentException("Generated features is null"); + } + + try (ByteArrayInputStream bis = new ByteArrayInputStream(generated.getObject().toString().getBytes())) { + adapter.writeItem(features.internalLocation, bis); + } + + } else { + throw new IllegalArgumentException("Generator not defined for 'applications.builder.features'"); + } + + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/AbstractDescriptor.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/AbstractDescriptor.java new file mode 100644 index 00000000..28956cbe --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/AbstractDescriptor.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +public abstract class AbstractDescriptor { + + public enum TYPE { + BUNDLE, + RESOURCE, + CONFIG + } + + TYPE type; + + // location within application bundle + String finalLocation; + + // source location for final installation + String finalMavenLocation; + + int priority = 50; + + boolean consistent = true; + + protected AbstractDescriptor() { + super(); + type = getDescriptorType(); + } + + abstract public String getDescriptorId(); + + abstract protected TYPE getDescriptorType(); +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/AbstractStorage.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/AbstractStorage.java new file mode 100644 index 00000000..109c9c50 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/AbstractStorage.java @@ -0,0 +1,74 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import java.io.File; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; + +public abstract class AbstractStorage { + + public static class BuildResult { + + Map newDescriptors = new HashMap<>(); + Map changes = new HashMap<>(); + } + + File parentDir; + + File tempDir; + + File rootDirectory; + + List descriptors = new ArrayList<>(); + + protected AbstractStorage(File parentDir, File tempDir) { + super(); + this.parentDir = parentDir; + this.tempDir = tempDir; + this.rootDirectory = new File(Paths.get(parentDir.getAbsolutePath(), getStorageDir()).toAbsolutePath().toUri()); + this.rootDirectory.mkdirs(); + } + + + public void addDescriptor(T descriptor) { + this.descriptors.add(descriptor); + } + + protected abstract String getStorageDir(); + + public abstract void prepare(); + + public abstract void prepareDescriptor(T descriptor); + + public abstract BuildResult build(ArtifactCoordinates applicationCoordinates); + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ApplicationBuilder.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ApplicationBuilder.java new file mode 100644 index 00000000..15155087 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ApplicationBuilder.java @@ -0,0 +1,558 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.UUID; +import java.util.stream.Collectors; + +import org.apache.commons.io.FileUtils; +import org.osgi.framework.Bundle; +import org.osgi.framework.FrameworkUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + +import ru.entaxy.base.generator.template.Template; +import ru.entaxy.base.generator.template.TemplateAwareGenerator; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated; +import ru.entaxy.esb.platform.runtime.base.connecting.generator.factory.GeneratorFactory; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.integration.applications.ApplicationProjectContent.STANDARD_PROPERTIES; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationContentItem; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationFeatures; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; +import ru.entaxy.platform.integration.applications.impl.ServiceHelper; +import ru.entaxy.platform.integration.applications.impl.build.AbstractStorage.BuildResult; +import ru.entaxy.platform.integration.applications.impl.jar.FolderBasedJarBuilder; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectContentImpl; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectItemImpl; +import ru.entaxy.platform.integration.applications.impl.project.item.BundleItemImpl; +import ru.entaxy.platform.integration.applications.impl.project.item.ConfigItemImpl; +import ru.entaxy.platform.integration.applications.impl.project.item.ObjectItemImpl; +import ru.entaxy.platform.integration.applications.impl.project.item.ResourceItemImpl; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +public class ApplicationBuilder { + + private static final Logger LOG = LoggerFactory.getLogger(ApplicationBuilder.class); + + protected static Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static final String DEFAULT_VERSION = "1.0.0"; + + public static final String DEFAULT_APP_NAME = "app-0"; + + protected static final String CONTENT_ROOT_NAME = "content"; + + protected static final String TEMP_ROOT_NAME = "temp"; + + protected static final URI ROOT_FILE_URI = + Paths.get(System.getProperty("karaf.home"), "data/tmp/.appbuilder").toAbsolutePath().toUri(); + + protected static File ROOT_FILE; + + protected static boolean IS_INITED = false; + + protected static void initRootFile() { + if (IS_INITED) + return; + ROOT_FILE = new File(ROOT_FILE_URI); + ROOT_FILE.mkdirs(); + IS_INITED = true; + } + + final protected ArtifactCoordinates coordinates = new ArtifactCoordinates(); + + protected ApplicationProjectContentImpl applicationContent; + + protected String buildRootName = UUID.randomUUID().toString(); + + protected File buildRoot; + + protected File buildContentRoot; + + protected File buildTempRoot; + + protected Map bundleDescriptors = new HashMap<>(); + + protected Map resourceDescriptors = new HashMap<>(); + + protected Map configDescriptors = new HashMap<>(); + + protected Map itemToDescriptorMap = new HashMap<>(); + + protected BundleStorage bundleStorage; + + protected ResourceStorage resourceStorage; + + protected ConfigStorage configStorage; + + protected ApplicationDescriptor descriptor; + + protected File buildResult; + + public ApplicationBuilder(ApplicationProjectContentImpl applicationContent) { + super(); + initRootFile(); + this.applicationContent = applicationContent; + coordinates.groupId(applicationContent.getProperties().getOrDefault(STANDARD_PROPERTIES.GROUP, + EntaxyApplication.DEFAULT_GROUP_ID).toString()) + .version(applicationContent.getProperties().getOrDefault(STANDARD_PROPERTIES.VERSION, + DEFAULT_VERSION).toString()) + .artifactId(applicationContent.getProperties().getOrDefault(STANDARD_PROPERTIES.APPLICATION, + DEFAULT_APP_NAME).toString()); + buildRoot = new File(Paths.get(ROOT_FILE.getAbsolutePath(), buildRootName).toAbsolutePath().toUri()); + buildRoot.mkdirs(); + + buildContentRoot = new File(Paths.get(buildRoot.getAbsolutePath(), CONTENT_ROOT_NAME).toAbsolutePath().toUri()); + buildContentRoot.mkdirs(); + + buildTempRoot = new File(Paths.get(buildRoot.getAbsolutePath(), TEMP_ROOT_NAME).toAbsolutePath().toUri()); + buildTempRoot.mkdirs(); + + bundleStorage = new BundleStorage(buildContentRoot, buildTempRoot); + + resourceStorage = new ResourceStorage(buildContentRoot, buildTempRoot); + + configStorage = new ConfigStorage(buildContentRoot, buildTempRoot); + } + + public ArtifactCoordinates getCoordinates() { + return coordinates; + } + + public void prepareContent() { + + // get only included items + List includedItems = applicationContent.getItemsMap().values().stream() + .filter(item -> !item.isRequired()).collect(Collectors.toList()); + + // get by type + List includedBundles = new ArrayList<>(); + List includedObjects = new ArrayList<>(); + List includedConfigs = new ArrayList<>(); + List includedResources = new ArrayList<>(); + + for (ApplicationProjectItemImpl item : includedItems) + if (item instanceof ConfigItemImpl) + includedConfigs.add((ConfigItemImpl) item); + else if (item instanceof ObjectItemImpl) + includedObjects.add((ObjectItemImpl) item); + else if (item instanceof BundleItemImpl) + includedBundles.add((BundleItemImpl) item); + else if (item instanceof ResourceItemImpl) + includedResources.add((ResourceItemImpl) item); + else + continue; + + // collect bundles for objects + for (ObjectItemImpl item : includedObjects) { + // actualize object info + EntaxyRuntimeObject runtimeObject = + ServiceHelper.getInstance().getEntaxyRuntimeObjectService().getRuntimeObject( + item.getObject().getObjectFullId()); + String containerId = runtimeObject.getContainer().getId(); + BundleDescriptor desc; + if (!bundleDescriptors.containsKey(containerId)) { + long bundleId = Long.parseLong(containerId); + Bundle bundle = FrameworkUtil.getBundle(getClass()).getBundleContext().getBundle(bundleId); + desc = BundleDescriptor.forBundle(bundle); + if (!desc.consistent) { + LOG.error(String.format("Descritor is inconcistent for bundle [%s]", containerId)); + continue; + } + bundleDescriptors.put(containerId, desc); + bundleStorage.addDescriptor(desc); + } else { + desc = bundleDescriptors.get(containerId); + } + itemToDescriptorMap.put(item.getId(), desc); + } + + // collect other bundles + for (BundleItemImpl item : includedBundles) { + // TODO implement + } + + // collect resources + for (ResourceItemImpl item : includedResources) { + ResourceDescriptor desc; + if (!resourceDescriptors.containsKey(item.getId())) { + desc = ResourceDescriptor.forResource(item.getResource()); + resourceStorage.addDescriptor(desc); + } else { + desc = resourceDescriptors.get(item.getId()); + } + itemToDescriptorMap.put(item.getId(), desc); + } + + // collect configs + for (ConfigItemImpl item : includedConfigs) { + ConfigDescriptor desc = null; + EntaxyRuntimeObject configObject = + ServiceHelper.getInstance().getEntaxyRuntimeObjectService().getRuntimeObject( + item.getObject().getObjectFullId()); + if (!configDescriptors.containsKey(item.getId())) { + + /* + + + if (!configObject.getIncomiingSubordRelations().isEmpty()) { + // this is object config + Optional rel = configObject.getIncomiingSubordRelations().stream() + .filter(r -> "config".equals(r.getName())).findFirst(); + if (rel.isPresent()) { + EntaxyRuntimeObject configuredObject = rel.get().getMain(); + + // check data consistency + if (configuredObject.getObjectFullId() + .equals(ObjectConfig.getConfiguredObjectId(configObject.getId()))) { + + + } + + } + } + if (desc == null) { + // this is custom config + desc = ConfigDescriptor.forConfig(item.getId()); + } + */ + + desc = ConfigDescriptor.forConfig(item.getId(), getCoordinates()); + + configStorage.addDescriptor(desc); + } else { + desc = configDescriptors.get(item.getId()); + } + itemToDescriptorMap.put(item.getObject().getObjectFullId(), desc); + } + + bundleStorage.prepare(); + configStorage.prepare(); + resourceStorage.prepare(); + + BuildResult result = resourceStorage.build(coordinates); + for (Entry entry : result.changes.entrySet()) { + itemToDescriptorMap.put(entry.getKey(), entry.getValue()); + } + for (Entry entry : result.newDescriptors.entrySet()) { + if (entry.getValue() instanceof BundleDescriptor) { + // register descriptor + bundleDescriptors.put(entry.getKey(), (BundleDescriptor) entry.getValue()); + + + + // add descriptor to storage + bundleStorage.prepareDescriptor((BundleDescriptor) entry.getValue()); + } + } + + result = bundleStorage.build(coordinates); + // process result + // NOOP + + } + + public void generateDescriptor() { + descriptor = new ApplicationDescriptor(); + + descriptor.name = coordinates.getArtifactId(); + descriptor.group = coordinates.getGroupId(); + descriptor.version = coordinates.getVersion(); + descriptor.buildBy = ""; + descriptor.buildOn = Calendar.getInstance().getTimeInMillis() + ""; + + descriptor.mavenUrl = coordinates.toMavenString(); + descriptor.mavenAsset = coordinates.toAssetName(); + + // get requirements + List reqs = applicationContent.getItemsMap().values().stream() + .filter(item -> item.isRequired()).collect(Collectors.toList()); + Map requirementsMap = new LinkedHashMap<>(); + for (ApplicationProjectItemImpl req : reqs) { + ApplicationRequirement appReq = convertToRequirement(req); + requirementsMap.put(appReq.id, appReq); + } + for (ApplicationRequirement appReq : requirementsMap.values()) + descriptor.requirements.add(appReq); + + Map contentItems = new LinkedHashMap<>(); + Map components = new LinkedHashMap<>(); + for (Entry entry : itemToDescriptorMap.entrySet()) { + String itemId = entry.getKey(); + ApplicationProjectItemImpl itemImpl = applicationContent.getItemsMap().get(itemId); + ApplicationContentItem contentItem = new ApplicationContentItem(); + contentItem.id = itemImpl.getId(); + contentItem.type = itemImpl.getType(); + contentItem.componentId = entry.getValue().getDescriptorId(); + contentItems.put(contentItem.id, contentItem); + ApplicationComponent component = convertToComponent(entry.getValue()); + if (component == null) { + LOG.error("Failed converting descriptor [{}]/[{}] to component", entry.getValue().getDescriptorId(), + entry.getValue().type.name()); + continue; + } else { + // components.put(entry.getKey(), component); + // exclude duplicates + components.putIfAbsent(component.getId(), component); + } + } + + for (ApplicationContentItem item : contentItems.values()) + descriptor.items.add(item); + + List componentList = new ArrayList<>(components.values()); + Collections.sort(componentList, new Comparator() { + + @Override + public int compare(ApplicationComponent o1, ApplicationComponent o2) { + if (o1.priority > o2.priority) + return 1; + if (o1.priority < o2.priority) + return -1; + return 0; + } + }); + + descriptor.components.addAll(componentList); + + } + + public void saveDescriptor() { + File descriptorFile = + new File(Paths.get(buildContentRoot.getAbsolutePath(), EntaxyApplication.DESCRIPTOR_NAME) + .toAbsolutePath().toUri()); + try (OutputStream bos = new FileOutputStream(descriptorFile)) { + JsonElement je = GSON.toJsonTree(descriptor); + String jsonData = je.toString(); + bos.write(jsonData.getBytes()); + } catch (Exception e) { + LOG.error("Error saving descriptor file", e); + } + } + + protected ApplicationComponent convertToComponent(AbstractDescriptor descriptor) { + switch (descriptor.type) { + case BUNDLE: + return convertToComponent((BundleDescriptor) descriptor); + case RESOURCE: + return convertToComponent((ResourceDescriptor) descriptor); + case CONFIG: + return convertToComponent((ConfigDescriptor) descriptor); + default: + return null; + } + } + + protected ApplicationComponent convertToComponent(BundleDescriptor descriptor) { + ApplicationComponent result = new ApplicationComponent(); + + result.id = descriptor.getDescriptorId(); + result.internalLocation = descriptor.finalLocation; + result.mavenLocation = descriptor.finalMavenLocation; + result.priority = descriptor.priority; + result.type = ITEM_TYPE.BUNDLE; + + String temp = descriptor.installLocation; + int index1 = temp.lastIndexOf(':'); + if (index1 > 0) { + result.targetProtocol = temp.substring(0, index1); + temp = temp.substring(index1 + 1); + } + int index2 = temp.indexOf('?'); + if (index2 > 0) { + result.targetQueryString = temp.substring(index2 + 1); + temp = temp.substring(0, index2); + } + result.targetLocation = temp; + + return result; + } + + protected ApplicationComponent convertToComponent(ResourceDescriptor descriptor) { + ApplicationComponent result = new ApplicationComponent(); + + result.id = descriptor.getDescriptorId(); + result.internalLocation = descriptor.finalLocation; + result.mavenLocation = ""; + result.targetLocation = descriptor.resourceUrl; + result.priority = 25; + result.type = ITEM_TYPE.RESOURCE; + result.targetLocation = descriptor.resourceUrl; + + return result; + } + + protected ApplicationComponent convertToComponent(ConfigDescriptor descriptor) { + ApplicationComponent result = new ApplicationComponent(); + + result.id = descriptor.getDescriptorId(); + result.internalLocation = descriptor.finalLocation; + result.mavenLocation = descriptor.finalMavenLocation; + result.targetLocation = descriptor.pid + ".cfg"; + result.priority = 25; + result.type = ITEM_TYPE.CONFIG; + + return result; + } + + protected ApplicationRequirement convertToRequirement(ApplicationProjectItemImpl sourceItem) { + ApplicationRequirement result = new ApplicationRequirement(); + result.id = sourceItem.getId(); + result.type = sourceItem.getType(); + result.scope = sourceItem.getScope(); + return result; + } + + public void generateFeatures() { + Template template = + ServiceHelper.getInstance().getTemplateService().getTemplateById("applications.builder.features"); + TemplateAwareGenerator generator = GeneratorFactory.createGenerator(template); + if (generator != null) { + String repoName = String.format("%s.%s-%s", coordinates.getGroupId(), coordinates.getArtifactId(), + coordinates.getVersion()); + String featureName = coordinates.getGroupId().concat(".").concat(coordinates.getArtifactId()); + Map params = new HashMap<>(); + params.put("descriptor", descriptor); + params.put("repoName", repoName); + params.put("featureName", featureName); + params.put("featureVersion", coordinates.getVersion()); + Generated generated; + try { + generated = generator.generate(template, params); + } catch (Exception e) { + LOG.error("Error generating features", e); + return; + } + if ((generated == null) || (generated.getObject() == null)) { + LOG.error("Generated NULL"); + } + ArtifactCoordinates featuresCoordinates = + ArtifactCoordinates.fromUrl(coordinates.toMavenString()).classifier("features").type("xml"); + String path = featuresCoordinates.toRepositoryPath(); + File featuresFile = new File(Paths.get(bundleStorage.rootDirectory.getAbsolutePath(), path).toUri()); + featuresFile.getAbsoluteFile().getParentFile().mkdirs(); + + try (OutputStream fos = new FileOutputStream(featuresFile)) { + fos.write(generated.getObject().toString().getBytes()); + } catch (Exception e) { + LOG.error("Error writing features file", e); + } + + descriptor.features = new ApplicationFeatures(); + descriptor.features.id = featureName; + descriptor.features.internalLocation = + buildContentRoot.toPath().relativize(featuresFile.toPath()).toString().replace('\\', '/'); + descriptor.features.mavenLocation = featuresCoordinates.toMavenString(); + descriptor.features.targetProtocol = "mvn"; + descriptor.features.targetLocation = descriptor.features.mavenLocation; + + } + } + + public void pack() { + File targetFile = + new File(Paths.get(buildRoot.getAbsolutePath(), "result", coordinates.toRepositoryPath()).toUri()); + targetFile.getAbsoluteFile().getParentFile().mkdirs(); + FolderBasedJarBuilder builder = new FolderBasedJarBuilder(targetFile, buildContentRoot); + builder.putAttribute("Entaxy-Application", coordinates.getArtifactId()); + builder.putAttribute("Entaxy-ApplicationGroup", coordinates.getGroupId()); + builder.putAttribute("Entaxy-ApplicationVersion", coordinates.getVersion()); + try { + builder.loadFiles(); + } catch (IllegalStateException | IOException e) { + LOG.error("Error building application file", e); + } + try { + builder.close(); + } catch (IOException e) { + LOG.error("Error building application file", e); + return; + } + buildResult = targetFile; + } + + public void clear() { + try { + FileUtils.deleteDirectory(buildRoot); + } catch (IOException e) { + LOG.error("Error clearing ApplicationBuilder", e); + } + } + + public URL build() { + + prepareContent(); + generateDescriptor(); + generateFeatures(); + saveDescriptor(); + pack(); + + if (buildResult == null) + return null; + + try { + return buildResult.toURI().toURL(); + } catch (MalformedURLException e) { + LOG.error("Error creating URL for [" + buildResult.getAbsolutePath() + "]", e); + return null; + } + } + + public ApplicationDescriptor getDescriptor() { + return descriptor; + } + + public File getBuildResult() { + return buildResult; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/BundleDescriptor.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/BundleDescriptor.java new file mode 100644 index 00000000..0aeddfc2 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/BundleDescriptor.java @@ -0,0 +1,101 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import org.apache.karaf.bundle.core.BundleInfo; +import org.apache.karaf.bundle.core.BundleService; +import org.osgi.framework.Bundle; +import org.osgi.framework.startlevel.BundleStartLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.integration.applications.impl.ServiceHelper; + +public class BundleDescriptor extends AbstractDescriptor { + + private static final Logger LOG = LoggerFactory.getLogger(BundleDescriptor.class); + + public static BundleDescriptor forBundle(Bundle bundle) { + BundleDescriptor result = new BundleDescriptor(); + result.readBundle(bundle); + return result; + } + + @Override + protected TYPE getDescriptorType() { + return TYPE.BUNDLE; + } + + String symbolicName; + long id; + + // origin install location + String installLocation; + + // origin maven artifact location + String mavenLocation; + + // location from where we can download the artifact + String sourceLocation; + + public void readBundle(Bundle bundle) { + symbolicName = bundle.getSymbolicName(); + id = bundle.getBundleId(); + + priority = ((BundleStartLevel) bundle.adapt(BundleStartLevel.class)).getStartLevel(); + + // installLocation = bundle.getLocation(); + + try { + BundleService bundleService = ServiceHelper.getInstance().getBundleService(); + BundleInfo bundleInfo = bundleService.getInfo(bundle); + installLocation = bundleInfo.getUpdateLocation(); + } catch (Exception e) { + LOG.error("Error reading bundle info", e); + consistent = false; + return; + } + + int index = installLocation.indexOf("mvn:"); + if (index < 0) { + consistent = false; + return; + } + + int index2 = installLocation.indexOf('?'); + if (index2 > index) + mavenLocation = installLocation.substring(index + 4, index2); + else + mavenLocation = installLocation.substring(index + 4); + + sourceLocation = installLocation.substring(index); + } + + @Override + public String getDescriptorId() { + return symbolicName + "~" + getDescriptorType(); + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/BundleStorage.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/BundleStorage.java new file mode 100644 index 00000000..3e182ea2 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/BundleStorage.java @@ -0,0 +1,118 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Paths; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; + +public class BundleStorage extends AbstractStorage { + + private static final Logger LOG = LoggerFactory.getLogger(BundleStorage.class); + + final String dirName = "repository"; + + public BundleStorage(File parentDir, File tempDir) { + super(parentDir, tempDir); + } + + @Override + protected String getStorageDir() { + return dirName; + } + + @Override + public void prepare() { + for (BundleDescriptor descriptor : descriptors) + prepareDescriptor(descriptor); + } + + @Override + public void prepareDescriptor(BundleDescriptor descriptor) { + + ArtifactCoordinates bundleCoordinates = ArtifactCoordinates.fromUrl(descriptor.mavenLocation); + + if (!CommonUtils.isValid(bundleCoordinates.getType())) + bundleCoordinates.type("jar"); + + File targetDir = new File( + Paths.get(rootDirectory.getAbsolutePath(), + bundleCoordinates.getGroupId().replace('.', '/'), + bundleCoordinates.getArtifactId(), + bundleCoordinates.getVersion()).toAbsolutePath().toUri()); + targetDir.mkdirs(); + + String fileName = bundleCoordinates.getArtifactId().concat("-").concat(bundleCoordinates.getVersion()) + .concat(CommonUtils.isValid(bundleCoordinates.getClassifier()) + ? "-".concat(bundleCoordinates.getClassifier()) + : "") + .concat(".".concat(bundleCoordinates.getType())); + File targetFile = new File(Paths.get(targetDir.getAbsolutePath(), fileName).toAbsolutePath().toUri()); + + URL sourceUrl; + try { + sourceUrl = new URL(descriptor.sourceLocation); + } catch (MalformedURLException e) { + LOG.error("Error creating URL for [" + descriptor.mavenLocation + "]", e); + return; + } + + try ( + InputStream is = sourceUrl.openStream(); + OutputStream os = new FileOutputStream(targetFile)) { + + os.write(is.readAllBytes()); + + String targetLocation = + dirName.concat(targetFile.getAbsolutePath().replace(rootDirectory.getAbsolutePath(), "")) + .replace('\\', '/'); + + descriptor.finalLocation = targetLocation; + + descriptor.finalMavenLocation = descriptor.mavenLocation; + + } catch (IOException e) { + LOG.error("Error reading from URL [" + sourceUrl.toString() + "]", e); + return; + } + } + + @Override + public BuildResult build(ArtifactCoordinates applicationCoordinates) { + return new BuildResult(); + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ConfigDescriptor.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ConfigDescriptor.java new file mode 100644 index 00000000..675c8df7 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ConfigDescriptor.java @@ -0,0 +1,87 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +public class ConfigDescriptor extends AbstractDescriptor { + + public static ConfigDescriptor forConfig(String configId) { + ConfigDescriptor result = new ConfigDescriptor(); + result.pid = configId.split(":")[0]; + return result; + } + + public static ConfigDescriptor forConfig(String configId, ArtifactCoordinates applicationCoordinates) { + ConfigDescriptor result = new ConfigDescriptor(); + result.pid = configId.split(":")[0]; + result.init(applicationCoordinates); + return result; + } + + + public static ConfigDescriptor forObjectConfig(EntaxyRuntimeObject configObject, + EntaxyRuntimeObject configuredObject) { + ConfigDescriptor result = new ConfigDescriptor(); + result.pid = configObject.getId(); + return result; + } + + String pid; + + // origin install location + String installLocation; + + // origin maven artifact location + String mavenLocation; + + // location from where we can download the artifact + String sourceLocation; + + @Override + public String getDescriptorId() { + return pid + "~" + getDescriptorType(); + } + + @Override + protected TYPE getDescriptorType() { + return TYPE.CONFIG; + } + + public void init(ArtifactCoordinates applicationCoordinates) { + ArtifactCoordinates localCoordinates = ArtifactCoordinates.fromUrl(applicationCoordinates.toMavenString()); + localCoordinates.type("cfg").classifier(pid); + + mavenLocation = localCoordinates.toMavenString(); + + sourceLocation = "mvn:" + mavenLocation; + + installLocation = pid + ".cfg"; + + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ConfigStorage.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ConfigStorage.java new file mode 100644 index 00000000..02e6cc01 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ConfigStorage.java @@ -0,0 +1,118 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Paths; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; + +public class ConfigStorage extends AbstractStorage { + + private static final Logger LOG = LoggerFactory.getLogger(ConfigStorage.class); + + final String dirName = "repository"; + + protected ConfigStorage(File parentDir, File tempDir) { + super(parentDir, tempDir); + } + + @Override + protected String getStorageDir() { + return dirName; + } + + @Override + public void prepare() { + for (ConfigDescriptor desc : descriptors) + prepareDescriptor(desc); + + } + + @Override + public void prepareDescriptor(ConfigDescriptor descriptor) { + ArtifactCoordinates configCoordinates = ArtifactCoordinates.fromUrl(descriptor.mavenLocation); + + if (!CommonUtils.isValid(configCoordinates.getType())) + configCoordinates.type("cfg"); + + String fileName = configCoordinates.toAssetName(); + String repositoryPath = configCoordinates.toRepositoryPath(); + String subfolder = + repositoryPath.substring(0, repositoryPath.length() - fileName.length()); + + File targetDir = new File( + Paths.get(rootDirectory.getAbsolutePath(), + subfolder).toAbsolutePath().toUri()); + targetDir.mkdirs(); + + File targetFile = new File(Paths.get(targetDir.getAbsolutePath(), fileName).toAbsolutePath().toUri()); + + URL sourceUrl; + try { + sourceUrl = Paths.get(System.getProperty("karaf.etc"), descriptor.pid + ".cfg").toAbsolutePath().toUri() + .toURL(); + } catch (MalformedURLException e) { + LOG.error("Error creating URL for [" + descriptor.mavenLocation + "]", e); + return; + } + + try ( + InputStream is = sourceUrl.openStream(); + OutputStream os = new FileOutputStream(targetFile)) { + + os.write(is.readAllBytes()); + + String targetLocation = + dirName.concat(targetFile.getAbsolutePath().replace(rootDirectory.getAbsolutePath(), "")) + .replace('\\', '/'); + + descriptor.finalLocation = targetLocation; + + descriptor.finalMavenLocation = descriptor.mavenLocation; + + } catch (IOException e) { + LOG.error("Error reading from URL [" + sourceUrl.toString() + "]", e); + return; + } + } + + @Override + public BuildResult build(ArtifactCoordinates applicationCoordinates) { + return new BuildResult(); + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ResourceDescriptor.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ResourceDescriptor.java new file mode 100644 index 00000000..5b13765a --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ResourceDescriptor.java @@ -0,0 +1,54 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import ru.entaxy.esb.resources.EntaxyResource; + +public class ResourceDescriptor extends AbstractDescriptor { + + public static ResourceDescriptor forResource(EntaxyResource entaxyResource) { + ResourceDescriptor result = new ResourceDescriptor(); + result.readResource(entaxyResource); + return result; + } + + public String resourceUrl; + + public void readResource(EntaxyResource entaxyResource) { + resourceUrl = entaxyResource.getURL(); + } + + @Override + protected TYPE getDescriptorType() { + return TYPE.RESOURCE; + } + + @Override + public String getDescriptorId() { + return resourceUrl + "~" + getDescriptorType(); + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ResourceStorage.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ResourceStorage.java new file mode 100644 index 00000000..275cce42 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/build/ResourceStorage.java @@ -0,0 +1,188 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.build; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.MalformedURLException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.stream.Stream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.integration.applications.impl.ServiceHelper; +import ru.entaxy.platform.integration.applications.impl.jar.FolderBasedJarBuilder; + +public class ResourceStorage extends AbstractStorage { + + private static final Logger LOG = LoggerFactory.getLogger(ResourceStorage.class); + + static final String startDirName = "resources/resources"; + + static final String subDirName = "ru/entaxy/resource"; + + static final String storageDirName = startDirName + "/" + subDirName; + + protected File startDir; + + public ResourceStorage(File parentDir, File tempDir) { + super(parentDir, tempDir); + this.startDir = new File(Paths.get(parentDir.getAbsolutePath(), startDirName).toAbsolutePath().toUri()); + + } + + @Override + protected String getStorageDir() { + return storageDirName; + } + + @Override + public void prepare() { + for (ResourceDescriptor descriptor : descriptors) + prepareDescriptor(descriptor); + + } + + @Override + public void prepareDescriptor(ResourceDescriptor descriptor) { + EntaxyResource entaxyResource = + ServiceHelper.getInstance().getEntaxyResourceService().getResource(descriptor.resourceUrl); + if (!entaxyResource.exists()) { + LOG.error("Resource doesn't exist: [{}]", descriptor.resourceUrl); + return; + } + String targetPath = descriptor.resourceUrl.replace(':', '/'); + File targetFile = new File(Paths.get(rootDirectory.getAbsolutePath(), targetPath).toAbsolutePath().toUri()); + targetFile.getParentFile().mkdirs(); + + try (InputStream is = entaxyResource.getInputStream(); + OutputStream os = new FileOutputStream(targetFile)) { + + os.write(is.readAllBytes()); + + String targetLocation = + storageDirName.concat(targetFile.getAbsolutePath().replace(rootDirectory.getAbsolutePath(), "")) + .replace('\\', '/'); + + descriptor.finalLocation = targetLocation; + + + } catch (Exception e) { + LOG.error("Error reading resource [" + descriptor.resourceUrl + "]", e); + return; + } + + } + + @Override + public BuildResult build(ArtifactCoordinates applicationCoordinates) { + + // first check if we have resources + try (Stream pathStream = Files.walk(startDir.getAbsoluteFile().toPath())) { + long count = pathStream + .parallel() + .filter(p -> !p.toFile().isDirectory()) + .count(); + if (count == 0) + return new BuildResult(); + } catch (IOException e) { + LOG.error("ERROR checking the directory [" + startDir.getAbsolutePath() + "]", e); + return new BuildResult(); + } + + ArtifactCoordinates jarCoordinates = ArtifactCoordinates.fromUrl(applicationCoordinates.toString()); + jarCoordinates.type("jar").classifier("resources"); + + File jarFile = new File(Paths + .get(tempDir.getAbsolutePath(), ".resources", jarCoordinates.getGroupId().replace('.', '/'), + jarCoordinates.getArtifactId(), + jarCoordinates.getVersion(), + jarCoordinates.getArtifactId().concat("-") + .concat(jarCoordinates.getVersion().concat("-") + .concat(jarCoordinates.getClassifier().concat(".") + .concat(jarCoordinates.getType())))) + .toAbsolutePath().toUri()); + + jarFile.getAbsoluteFile().getParentFile().mkdirs(); + + String bundleName = String.format("APPLICATION :: %s :: %s :: RESOURCES", jarCoordinates.getArtifactId(), + jarCoordinates.getVersion()); + String bundleDecription = bundleName; + String bundleSymboliName = + jarCoordinates.getGroupId().concat(".").concat(jarCoordinates.getArtifactId()).concat(".resources"); + + FolderBasedJarBuilder jarBuilder = new FolderBasedJarBuilder(jarFile, startDir); + jarBuilder.getOsgiInfo() + .name(bundleName) + .symbolicName(bundleSymboliName) + .description(bundleDecription) + .version(jarCoordinates.getVersion()) + .update(); + + jarBuilder.putAttribute("Entaxy-Resource-Provider", "true"); + + try { + jarBuilder.loadFiles(); + } catch (IllegalStateException | IOException e) { + LOG.error("Error loading files", e); + } + + try { + jarBuilder.close(); + } catch (IOException e) { + LOG.error("Error closing jar", e); + } + + BundleDescriptor bundleDesc = new BundleDescriptor(); + bundleDesc.id = -1; + bundleDesc.symbolicName = bundleSymboliName; + bundleDesc.mavenLocation = jarCoordinates.toString(); + bundleDesc.installLocation = "mvn:" + bundleDesc.mavenLocation; + try { + bundleDesc.sourceLocation = jarFile.getAbsoluteFile().toURI().toURL().toString(); + } catch (MalformedURLException e) { + bundleDesc.sourceLocation = "file:///" + jarFile.getAbsolutePath().replace('\\', '/'); + } + bundleDesc.priority = 90; + + BuildResult result = new BuildResult(); + result.newDescriptors.put(bundleSymboliName, bundleDesc); + + for (ResourceDescriptor desc : descriptors) + result.changes.put(desc.resourceUrl, bundleDesc); + + + return result; + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/jar/FolderBasedJarBuilder.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/jar/FolderBasedJarBuilder.java new file mode 100644 index 00000000..3c6078b5 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/jar/FolderBasedJarBuilder.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.jar; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Iterator; + +import org.apache.commons.io.FileUtils; + +public class FolderBasedJarBuilder extends JarBuilder { + + File rootFolder; + + public FolderBasedJarBuilder(File targetFile, File rootFolder) { + super(targetFile); + this.rootFolder = rootFolder; + } + + public void loadFiles() throws FileNotFoundException, IOException, IllegalStateException { + if (Status.FINALIZED.equals(status)) + throw new IllegalStateException("JarBuilder is finalized"); + if (Status.NEW.equals(status)) + open(); + + Iterator iterator = FileUtils.iterateFiles(rootFolder, null, true); + while (iterator.hasNext()) { + File file = iterator.next(); + String name = file.getAbsolutePath().replace(rootFolder.getAbsolutePath(), "").replace('\\', '/'); + if (name.startsWith("/")) + name = name.substring(1); + addFile(file, name); + } + + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/jar/JarBuilder.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/jar/JarBuilder.java new file mode 100644 index 00000000..869f9d11 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/jar/JarBuilder.java @@ -0,0 +1,186 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.jar; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.jar.Attributes; +import java.util.jar.Attributes.Name; +import java.util.jar.JarEntry; +import java.util.jar.JarOutputStream; +import java.util.jar.Manifest; + +public class JarBuilder { + + public enum Status { + NEW, + OPENED, + FINALIZED + } + + public static interface OsgiAttributes { + Name NAME = new Name("Bundle-Name"); + Name SYMBOLIC_NAME = new Name("Bundle-SymbolicName"); + Name DESCRIPTION = new Name("Bundle-Description"); + Name DOC_URL = new Name("Bundle-DocURL"); + Name MANIFEST_VERSION = new Name("Bundle-ManifestVersion"); + Name VENDOR = new Name("Bundle-Vendor"); + Name VERSION = new Name("Bundle-Version"); + } + + + protected Manifest manifest; + + protected Status status = Status.NEW; + + protected File targetFile; + + protected Map osgiInfo = new HashMap<>(); + + protected JarOutputStream jarOutputStream; + + public class OsgiInfo { + + public OsgiInfo() { + String fileName = targetFile.getName(); + if (fileName.lastIndexOf('.') > 0) + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + osgiInfo.put(OsgiAttributes.NAME, fileName); + osgiInfo.put(OsgiAttributes.SYMBOLIC_NAME, fileName); + osgiInfo.put(OsgiAttributes.DESCRIPTION, fileName); + osgiInfo.put(OsgiAttributes.DOC_URL, "https://entaxy.ru/"); + osgiInfo.put(OsgiAttributes.VENDOR, "Entaxy"); + osgiInfo.put(OsgiAttributes.VERSION, "1.0.0"); + } + + public OsgiInfo name(String name) { + osgiInfo.put(OsgiAttributes.NAME, name); + return this; + } + + public OsgiInfo symbolicName(String name) { + osgiInfo.put(OsgiAttributes.SYMBOLIC_NAME, name); + return this; + } + + public OsgiInfo description(String desc) { + osgiInfo.put(OsgiAttributes.DESCRIPTION, desc); + return this; + } + + public OsgiInfo docUrl(String url) { + osgiInfo.put(OsgiAttributes.DOC_URL, url); + return this; + } + + public OsgiInfo vendor(String vendor) { + osgiInfo.put(OsgiAttributes.VENDOR, vendor); + return this; + } + + public OsgiInfo version(String version) { + osgiInfo.put(OsgiAttributes.VERSION, version); + return this; + } + + public void update() { + updateOsgiInfo(); + } + + } + + public JarBuilder(File targetFile) { + this.targetFile = targetFile; + this.targetFile.getAbsoluteFile().getParentFile().mkdirs(); + this.manifest = new Manifest(); + initializeManifest(); + this.osgiInfo.put(OsgiAttributes.MANIFEST_VERSION, "2"); + } + + public boolean isReady() { + return Status.FINALIZED.equals(status); + } + + protected void initializeManifest() { + this.manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); + } + + public void updateOsgiInfo() { + if (Status.NEW.equals(status)) + for (Entry entry : osgiInfo.entrySet()) + this.manifest.getMainAttributes().put(entry.getKey(), entry.getValue()); + } + + public OsgiInfo getOsgiInfo() { + return new OsgiInfo(); + } + + public void putAttribute(String name, String value) { + if (status.equals(Status.NEW)) + this.manifest.getMainAttributes().putValue(name, value); + } + + public void open() throws FileNotFoundException, IOException { + status = Status.OPENED; + jarOutputStream = new JarOutputStream(new FileOutputStream(targetFile), this.manifest); + } + + public void addFile(File source, String targetLocation) throws IllegalStateException, IOException { + if (!Status.OPENED.equals(status)) + throw new IllegalStateException("JarBuilder is not in OPENED status"); + JarEntry entry = new JarEntry(targetLocation); + entry.setTime(source.lastModified()); + jarOutputStream.putNextEntry(entry); + + try ( + BufferedInputStream in = new BufferedInputStream(new FileInputStream(source))) { + byte[] buffer = new byte[1024]; + while (true) { + int count = in.read(buffer); + if (count == -1) { + break; + } + jarOutputStream.write(buffer, 0, count); + } + } finally { + jarOutputStream.closeEntry(); + } + } + + public File close() throws IOException { + jarOutputStream.close(); + status = Status.FINALIZED; + return targetFile; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/ApplicationProjectContentImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/ApplicationProjectContentImpl.java new file mode 100644 index 00000000..784a056b --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/ApplicationProjectContentImpl.java @@ -0,0 +1,305 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import com.google.gson.JsonObject; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.integration.applications.ApplicationProjectContent; +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.exceptions.ItemException; +import ru.entaxy.platform.integration.applications.exceptions.ItemIsGhostException; +import ru.entaxy.platform.integration.applications.exceptions.ItemIsPlatformException; +import ru.entaxy.platform.integration.applications.exceptions.ItemNotFoundException; +import ru.entaxy.platform.integration.applications.impl.ServiceHelper; +import ru.entaxy.platform.integration.applications.impl.project.item.ItemFactory; +import ru.entaxy.platform.integration.applications.impl.project.model.ContentModel; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ContentModelItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyObjectItem; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectResource; + +public class ApplicationProjectContentImpl implements ApplicationProjectContent { + + final protected Map properties = new HashMap<>(); + + final protected Map items = new HashMap<>(); + + final protected Object itemsLock = new Object(); + + protected ApplicationProjectItemImpl getItemImpl(String itemId) throws ItemException { + ApplicationProjectItemImpl result = items.get(itemId); + if (result == null) + throw new ItemNotFoundException(null, null, itemId); + return result; + } + + protected JsonObject getAsJson() { + ContentModel contentModel = new ContentModel(); + contentModel.update(this); + return contentModel.getAsJson(); + } + + public String marshall() { + return getAsJson().toString(); + } + + public void unmarshall(String data) { + + ContentModel contentModel = ContentModel.load(JSONUtils.getJsonRootObject(data)); + properties.put(STANDARD_PROPERTIES.APPLICATION, contentModel.getApplication()); + properties.put(STANDARD_PROPERTIES.GROUP, contentModel.getGroup()); + properties.put(STANDARD_PROPERTIES.VERSION, contentModel.getVersion()); + properties.put(STANDARD_PROPERTIES.CREATED_ON, contentModel.getCreatedOn()); + properties.put(STANDARD_PROPERTIES.CREATED_BY, contentModel.getCreatedBy()); + properties.put(STANDARD_PROPERTIES.MODIFIED_ON, contentModel.getModifiedOn()); + properties.put(STANDARD_PROPERTIES.MODIFIED_BY, contentModel.getModifiedBy()); + + for (ContentModelItem modelItem : contentModel.getIncludedItems()) { + ApplicationProjectItem item; + switch (modelItem.getItemType()) { + case BUNDLE: + continue; + case CONFIG: + case OBJECT: + EntaxyRuntimeObject runtimeObject = ServiceHelper.getInstance().getEntaxyRuntimeObjectService() + .getRuntimeObject(modelItem.getId()); + item = addObject(runtimeObject); + break; + case RESOURCE: + EntaxyResource entaxyResource = + ServiceHelper.getInstance().getEntaxyResourceService().getResource(modelItem.getId()); + item = addResource(entaxyResource); + break; + + default: + continue; + } + ApplicationProjectItemImpl itemImpl = items.get(item.getId()); + itemImpl.setScope(modelItem.getItemScope()); + } + + for (ContentModelItem modelItem : contentModel.getRequiredItems()) { + ApplicationProjectItem item; + switch (modelItem.getItemType()) { + case BUNDLE: + continue; + case CONFIG: + case OBJECT: + EntaxyRuntimeObject runtimeObject = ServiceHelper.getInstance().getEntaxyRuntimeObjectService() + .getRuntimeObject(modelItem.getId()); + item = addObject(runtimeObject); + break; + case RESOURCE: + EntaxyResource entaxyResource = + ServiceHelper.getInstance().getEntaxyResourceService().getResource(modelItem.getId()); + item = addResource(entaxyResource); + break; + + default: + continue; + } + ApplicationProjectItemImpl itemImpl = items.get(item.getId()); + itemImpl.setScope(modelItem.getItemScope()); + itemImpl.setRequired(modelItem.isRequired()); + itemImpl.setIgnored(modelItem.isIgnored()); + } + + + } + + public Map getItemsMap() { + return items; + } + + @Override + public List getItems() { + return new ArrayList<>(items.values()); + } + + @Override + public List getItems(Class itemClass) { + return getItems().stream().filter(item -> itemClass.isInstance(item)).map(item -> itemClass.cast(item)) + .collect(Collectors.toList()); + } + + @Override + public void addItem(ApplicationProjectItem item) throws ItemException { + ApplicationProjectItemImpl itemImpl = getItemImpl(item.getId()); + if (!item.isRequired()) + // already added + return; + if (item.isGhost()) + throw new ItemIsGhostException(null, null, item.getId()); + if (item.isPlatform()) + throw new ItemIsPlatformException(null, null, item.getId()); + itemImpl.setIgnored(false); + itemImpl.setRequired(false); + if (item.getType().equals(EntaxyApplication.ITEM_TYPE.OBJECT)) { + EntaxyRuntimeObject runtimeObject = ServiceHelper.getInstance().getEntaxyRuntimeObjectService() + .getRuntimeObject(((EntaxyObjectItem) item).getObject().getObjectFullId()); + Map linkedItems = new HashMap<>(); + ItemFactory.INSTANCE.processDependencies(itemImpl, runtimeObject, items, linkedItems); + processColocatedObjects(runtimeObject, linkedItems); + items.putAll(linkedItems); + } + } + + @Override + public void ignoreItem(ApplicationProjectItem item) throws ItemException { + ApplicationProjectItemImpl itemImpl = getItemImpl(item.getId()); + itemImpl.setIgnored(true); + itemImpl.setRequired(true); + for (ApplicationProjectItem req : itemImpl.getRequirements()) { + if (!req.isRequired()) + // that means it's added + continue; + if (req.getRequiredBy().size() > 1) + // required item is required by someone else + continue; + if (req.getRequiredBy().isEmpty()) { + // something strange + ignoreItem(req); + continue; + } + ApplicationProjectItem backRef = req.getRequiredBy().get(0); + if (backRef == null) { + // something strange + ignoreItem(req); + continue; + } + if (backRef.getId().equals(item.getId())) { + ignoreItem(req); + } + } + } + + @Override + public void removeItem(ApplicationProjectItem item) throws ItemException { + ApplicationProjectItemImpl itemImpl = getItemImpl(item.getId()); + if (itemImpl.getRequiredBy().isEmpty()) { + for (ApplicationProjectItem required : itemImpl.getRequirements()) { + // unlink required items + try { + ApplicationProjectItemImpl requiredImpl = getItemImpl(required.getId()); + itemImpl.removeRequired(requiredImpl); + } catch (Exception ignore) { + // NOOP + } + } + synchronized (itemsLock) { + items.remove(itemImpl.getId()); + } + } else if (!item.isPlatform()) { + // just mark as s requirement + itemImpl.setRequired(true); + itemImpl.setIgnored(false); + } + } + + @Override + public ApplicationProjectItem addObject(EntaxyRuntimeObject runtimeObject) { + synchronized (itemsLock) { + Map linked = new HashMap<>(); + ApplicationProjectItemImpl result = ItemFactory.INSTANCE.createItem(runtimeObject, items, linked); + + result.setScope(EntaxyApplication.ITEM_SCOPE.RUNTIME); + + items.put(result.getId(), result); + items.putAll(linked); + + processColocatedObjects(runtimeObject, linked); + + if (result.isPlatform()) { + result.setRequired(true); + result.setIgnored(true); + } else { + result.setRequired(false); + } + + return result; + } + } + + protected void processColocatedObjects(EntaxyRuntimeObject runtimeObject, + Map linked) { + List colocatedObjects = runtimeObject.getColocatedObjects(); + for (EntaxyRuntimeObject obj : colocatedObjects) { + ApplicationProjectItemImpl item; + if (items.containsKey(obj.getObjectFullId())) { + item = items.get(obj.getObjectFullId()); + } else { + linked = new HashMap<>(); + item = ItemFactory.INSTANCE.createItem(obj, items, linked); + if (!items.containsKey(item.getId())) + items.put(item.getId(), item); + items.putAll(linked); + } + + if (item.isPlatform()) { + item.setRequired(true); + item.setIgnored(true); + } else { + item.setRequired(false); + item.setIgnored(false); + } + + item.setScope(EntaxyApplication.ITEM_SCOPE.RUNTIME); + } + } + + @Override + public ApplicationProjectItem addResource(EntaxyRuntimeObjectResource runtimeObjectResource) { + synchronized (itemsLock) { + ApplicationProjectItemImpl result = ItemFactory.INSTANCE.createItem(runtimeObjectResource, items); + items.put(result.getId(), result); + return result; + } + } + + @Override + public ApplicationProjectItem addResource(EntaxyResource entaxyResource) { + synchronized (itemsLock) { + ApplicationProjectItemImpl result = ItemFactory.INSTANCE.createItem(entaxyResource, items); + result.setScope(EntaxyApplication.ITEM_SCOPE.RUNTIME); + items.put(result.getId(), result); + return result; + } + } + + @Override + public Map getProperties() { + return properties; + } +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/ApplicationProjectItemImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/ApplicationProjectItemImpl.java new file mode 100644 index 00000000..1e20d77b --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/ApplicationProjectItemImpl.java @@ -0,0 +1,175 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.impl.project.item.ColocationGroup; + +public abstract class ApplicationProjectItemImpl implements ApplicationProjectItem { + + boolean isRequired = false; + + boolean isIgnored = false; + + boolean isPlatform = false; + + EntaxyApplication.ITEM_SCOPE scope = EntaxyApplication.ITEM_SCOPE.DESIGN; + + EntaxyApplication.ITEM_TYPE type; + + Map required = new HashMap<>(); + + Map requiredBy = new HashMap<>(); + + ColocationGroup colocationGroup; + + public void setPlatform(Boolean platform) { + isPlatform = platform; + } + + public void setRequired(boolean isRequired) { + this.isRequired = isRequired; + } + + public void setIgnored(boolean isIgnored) { + this.isIgnored = isIgnored; + } + + public void addRequired(ApplicationProjectItemImpl item) { + required.put(item.getId(), item); + item.addRequiredBy(this); + } + + public void removeRequired(ApplicationProjectItemImpl item) { + item.removeRequiredBy(this); + required.remove(item.getId()); + } + + protected void addRequiredBy(ApplicationProjectItemImpl item) { + requiredBy.put(item.getId(), item); + } + + protected void removeRequiredBy(ApplicationProjectItemImpl item) { + requiredBy.remove(item.getId()); + } + + public ColocationGroup getColocationGroup() { + return colocationGroup; + } + + public void colocate(ColocationGroup colocationGroup) { + if (colocationGroup == null) { + if (this.colocationGroup != null) + this.colocationGroup.remove(this); + } + this.colocationGroup = colocationGroup; + if (this.colocationGroup != null) + this.colocationGroup.add(this); + } + + public void updateScope(EntaxyApplication.ITEM_SCOPE newScope) { + + // we'll leave most strict scope as a result + + // leave scope as is + if (EntaxyApplication.ITEM_SCOPE.DESIGN.equals(newScope)) + return; + scope = newScope; + } + + public void setScope(EntaxyApplication.ITEM_SCOPE scope) { + this.scope = scope; + } + + protected void setType(EntaxyApplication.ITEM_TYPE type) { + this.type = type; + } + + @Override + public EntaxyApplication.ITEM_SCOPE getScope() { + return scope; + } + + @Override + public EntaxyApplication.ITEM_TYPE getType() { + return type; + } + + @Override + public boolean isGhost() { + // TODO Auto-generated method stub + return false; + } + + @Override + public boolean isRequired() { + return isRequired; + } + + @Override + public boolean isPlatform() { + return isPlatform; + } + + @Override + public List getRequiredBy() { + return new ArrayList<>(this.requiredBy.values()); + } + + @Override + public List getRequirements() { + return new ArrayList<>(this.required.values()); + } + + @Override + public boolean isIgnored() { + return isIgnored; + } + + @Override + public void ignore() { + setIgnored(true); + } + + @Override + public List getColocated() { + if (this.colocationGroup == null) + return Collections.emptyList(); + return this.colocationGroup.getMembers().stream().filter(item -> !item.getId().equalsIgnoreCase(getId())) + .collect(Collectors.toList()); + } + + + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/BundleItemImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/BundleItemImpl.java new file mode 100644 index 00000000..7d6d7da1 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/BundleItemImpl.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.item; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectItemImpl; +import ru.entaxy.platform.integration.applications.item.project.EntaxyBundleItem; + +public class BundleItemImpl extends ApplicationProjectItemImpl implements EntaxyBundleItem { + + protected long bundleId; + + protected String bundleSymbolicName; + + public BundleItemImpl(long bundleId, String bundleSymbolicName) { + super(); + this.bundleId = bundleId; + this.bundleSymbolicName = bundleSymbolicName; + setType(EntaxyApplication.ITEM_TYPE.BUNDLE); + } + + + + @Override + public long getBundleId() { + return bundleId; + } + + @Override + public String getId() { + return bundleSymbolicName; + } + + @Override + public String getBundleSymbolicName() { + return bundleSymbolicName; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ColocationGroup.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ColocationGroup.java new file mode 100644 index 00000000..f21ce5e5 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ColocationGroup.java @@ -0,0 +1,66 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.item; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectItemImpl; + +public class ColocationGroup { + + Map members; + + Object membersLock = new Object(); + + String id; + + public ColocationGroup(String id) { + this.id = id; + } + + public String getId() { + return id; + } + + public void add(ApplicationProjectItemImpl item) { + synchronized (membersLock) { + members.put(item.getId(), item); + } + } + + public void remove(ApplicationProjectItemImpl item) { + synchronized (membersLock) { + members.remove(item.getId()); + } + } + + public List getMembers() { + return new ArrayList<>(this.members.values()); + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ConfigItemImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ConfigItemImpl.java new file mode 100644 index 00000000..b82ca901 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ConfigItemImpl.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.item; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.item.project.EntaxyConfigItem; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectContainer; + +public class ConfigItemImpl extends ObjectItemImpl implements EntaxyConfigItem { + + public static ConfigItemImpl create(EntaxyRuntimeObject runtimeObject) throws IllegalArgumentException { + EntaxyRuntimeObjectContainer container = runtimeObject.getContainer(); + if (!"bundle".equals(container.getType())) + throw new IllegalArgumentException("Object container is not a bundle: " + runtimeObject.getObjectFullId()); + String containerId = container.getId(); + long bundleId = -1; + String bundleSymbolicName = container.getName(); + try { + bundleId = Long.parseLong(containerId); + if (bundleId <= 0) + throw new Exception(); + } catch (Exception e) { + throw new IllegalArgumentException("Object container id is not a bundle id: [" + + runtimeObject.getObjectFullId() + "] [" + containerId + "]"); + } + return new ConfigItemImpl(bundleId, bundleSymbolicName, runtimeObject); + } + + public ConfigItemImpl(long bundleId, String bundleSymbolicName, EntaxyRuntimeObject runtimeObject) { + super(bundleId, bundleSymbolicName, runtimeObject); + setType(EntaxyApplication.ITEM_TYPE.CONFIG); + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ItemFactory.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ItemFactory.java new file mode 100644 index 00000000..59c5bfff --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ItemFactory.java @@ -0,0 +1,168 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.item; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.base.objects.EntaxyObject.OBJECT_RELATION; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectItemImpl; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectResource; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeRelation; + +public class ItemFactory { + + static public final ItemFactory INSTANCE = new ItemFactory(); + + static public final List CONFIG_TYPES = Arrays.asList(new String[] {"entaxy.runtime.config"}); + + private ItemFactory() { + + } + + public ApplicationProjectItemImpl createItem(EntaxyRuntimeObject runtimeObject, + Map currentStorage, + final Map linkedItems) { + return createItem(runtimeObject, currentStorage, linkedItems, false, false); + } + + public ApplicationProjectItemImpl createItem(EntaxyRuntimeObject runtimeObject, + Map currentStorage, + final Map linkedItems, boolean skipDependencies, boolean skipISR) { + + String fullId = runtimeObject.getObjectFullId(); + if (currentStorage.containsKey(fullId)) + return currentStorage.get(fullId); + + if (linkedItems.containsKey(fullId)) + return linkedItems.get(fullId); + + boolean isConfig = false; + for (String type : CONFIG_TYPES) + if (runtimeObject.getType().startsWith(type)) + isConfig = true; + + ApplicationProjectItemImpl result; + if (isConfig) { + result = ConfigItemImpl.create(runtimeObject); + } else { + result = ObjectItemImpl.create(runtimeObject); + } + + if (!skipDependencies) { + processDependencies(result, runtimeObject, currentStorage, linkedItems, skipISR, false); + } + + for (ApplicationProjectItemImpl item : linkedItems.values()) + if (!currentStorage.containsKey(item.getId())) + item.setRequired(true); + + return result; + } + + public void processDependencies(ApplicationProjectItemImpl targetItem, EntaxyRuntimeObject runtimeObject, + Map currentStorage, + final Map linkedItems) { + processDependencies(targetItem, runtimeObject, currentStorage, linkedItems, false, true); + } + + public void processDependencies(ApplicationProjectItemImpl targetItem, EntaxyRuntimeObject runtimeObject, + Map currentStorage, + final Map linkedItems, boolean skipISR, boolean skipComposition) { + + List relations; + if (!skipISR) { + // process object relations: incoming aggregations and compositions + relations = runtimeObject.getIncomiingSubordRelations(); + for (EntaxyRuntimeRelation rel : relations) { + EntaxyRuntimeObject object = rel.getMain(); + ApplicationProjectItemImpl item = createItem(object, currentStorage, linkedItems, false, false); + targetItem.addRequired(item); + item.updateScope(EntaxyApplication.ITEM_SCOPE.convert(rel.getScope())); + if (!currentStorage.containsKey(item.getId())) + item.setRequired(true); + if (!linkedItems.containsKey(item.getId())) + linkedItems.put(item.getId(), item); + } + } + + // process object relations: outgoing dependencies and uses + relations = runtimeObject.getRelations(OBJECT_RELATION.DEPENDENCY); + relations.addAll(runtimeObject.getRelations(OBJECT_RELATION.USE)); + for (EntaxyRuntimeRelation rel : relations) { + EntaxyRuntimeObject object = rel.getMain(); + ApplicationProjectItemImpl item = createItem(object, currentStorage, linkedItems); + item.updateScope(EntaxyApplication.ITEM_SCOPE.convert(rel.getScope())); + targetItem.addRequired(item); + if (!currentStorage.containsKey(item.getId())) + item.setRequired(true); + if (!linkedItems.containsKey(item.getId())) + linkedItems.put(item.getId(), item); + } + + if (!skipComposition) { + //add default route as mandatory + relations = runtimeObject.getRelations(OBJECT_RELATION.COMPOSITION); + for (EntaxyRuntimeRelation rel : relations) { + EntaxyRuntimeObject object = rel.getTarget(); + ApplicationProjectItemImpl item = createItem(object, currentStorage, linkedItems, false, true); + item.updateScope(EntaxyApplication.ITEM_SCOPE.convert(rel.getScope())); + item.addRequired(targetItem); + if (!currentStorage.containsKey(item.getId())) + item.setRequired(true); + if (!linkedItems.containsKey(item.getId())) + linkedItems.put(item.getId(), item); + } + } + + // process object resources + List resources = runtimeObject.getResources(); + for (EntaxyRuntimeObjectResource resource : resources) { + ApplicationProjectItemImpl item = createItem(resource, currentStorage); + item.updateScope(EntaxyApplication.ITEM_SCOPE.convert(resource.getScope())); + targetItem.addRequired(item); + if (!currentStorage.containsKey(item.getId())) + item.setRequired(true); + if (!linkedItems.containsKey(item.getId())) + linkedItems.put(item.getId(), item); + } + } + + public ApplicationProjectItemImpl createItem(EntaxyRuntimeObjectResource objectResource, + Map currentStorage) { + return new ResourceItemImpl(objectResource); + } + + public ApplicationProjectItemImpl createItem(EntaxyResource entaxyResource, + Map currentStorage) { + return new ResourceItemImpl(entaxyResource); + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ObjectItemImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ObjectItemImpl.java new file mode 100644 index 00000000..5d3affcc --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ObjectItemImpl.java @@ -0,0 +1,77 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.item; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.item.project.EntaxyObjectItem; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectContainer; + +public class ObjectItemImpl extends BundleItemImpl implements EntaxyObjectItem { + + public static ObjectItemImpl create(EntaxyRuntimeObject runtimeObject) throws IllegalArgumentException { + EntaxyRuntimeObjectContainer container = runtimeObject.getContainer(); + if (!"bundle".equals(container.getType())) + throw new IllegalArgumentException("Object container is not a bundle: " + runtimeObject.getObjectFullId()); + String containerId = container.getId(); + long bundleId = -1; + String bundleSymbolicName = container.getName(); + try { + bundleId = Long.parseLong(containerId); + if (bundleId <= 0) + throw new Exception(); + } catch (Exception e) { + throw new IllegalArgumentException("Object container id is not a bundle id: [" + + runtimeObject.getObjectFullId() + "] [" + containerId + "]"); + } + return new ObjectItemImpl(bundleId, bundleSymbolicName, runtimeObject); + } + + protected EntaxyRuntimeObject runtimeObject; + + public ObjectItemImpl(long bundleId, String bundleSymbolicName, EntaxyRuntimeObject runtimeObject) { + super(bundleId, bundleSymbolicName); + this.runtimeObject = runtimeObject; + Object isPlatform = runtimeObject.getAttribute("platform"); + if ("true".equals(isPlatform)) { + this.setPlatform(true); + this.setIgnored(true); + this.setRequired(true); + } + setType(EntaxyApplication.ITEM_TYPE.OBJECT); + } + + @Override + public String getId() { + return runtimeObject.getObjectFullId(); + } + + @Override + public EntaxyRuntimeObject getObject() { + return this.runtimeObject; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ResourceItemImpl.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ResourceItemImpl.java new file mode 100644 index 00000000..7340062b --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/item/ResourceItemImpl.java @@ -0,0 +1,60 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.item; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectItemImpl; +import ru.entaxy.platform.integration.applications.item.project.EntaxyResourceItem; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectResource; + +public class ResourceItemImpl extends ApplicationProjectItemImpl implements EntaxyResourceItem { + + protected EntaxyResource entaxyResource; + + public ResourceItemImpl(EntaxyRuntimeObjectResource objectResource) { + super(); + this.entaxyResource = objectResource.getResource(); + setType(EntaxyApplication.ITEM_TYPE.RESOURCE); + } + + public ResourceItemImpl(EntaxyResource entaxyResource) { + super(); + this.entaxyResource = entaxyResource; + setType(EntaxyApplication.ITEM_TYPE.RESOURCE); + } + + @Override + public String getId() { + return entaxyResource.getURL(); + } + + @Override + public EntaxyResource getResource() { + return entaxyResource; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentChecker.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentChecker.java new file mode 100644 index 00000000..6f50b265 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentChecker.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model; + +import com.google.gson.JsonObject; + +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.base.support.JSONUtils.ObjectWrapper; + +public class ContentChecker extends JSONUtils.ObjectChecker { + + public ContentModel contentModel; + + public ContentChecker(ContentModel contentModel) { + super(); + this.contentModel = contentModel; + } + + @Override + public ObjectWrapper checkObject(JsonObject object) { + if (ContentModelItemWrapper.isModelItem(object)) + return new ContentModelItemWrapper(this.contentModel); + return null; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentModel.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentModel.java new file mode 100644 index 00000000..b8692491 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentModel.java @@ -0,0 +1,248 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import ru.entaxy.platform.base.support.JSONUtils.JsonTraverse; +import ru.entaxy.platform.integration.applications.ApplicationProjectContent; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectContentImpl; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectItemImpl; +import ru.entaxy.platform.integration.applications.impl.project.model.item.BundleItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ConfigItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ContentModelItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ObjectItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ResourceItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyBundleItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyConfigItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyObjectItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyResourceItem; + +public class ContentModel { + + public static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + public static ContentModel load(JsonObject jsonObject) { + ContentModel result = GSON.fromJson(jsonObject, ContentModel.class); + JsonTraverse traverser = new JsonTraverse().checker(new ContentChecker(result)); + traverser.traverse(jsonObject); + return result; + } + + String application = ""; + String group = ""; + String version = ""; + String createdOn = Calendar.getInstance().getTimeInMillis() + ""; + String createdBy = ""; + String modifiedOn = ""; + String modifiedBy = ""; + + transient List requiredItems = new ArrayList<>(); + transient List includedItems = new ArrayList<>(); + + public void update(ApplicationProjectContentImpl applicationContentImpl) { + + application = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.APPLICATION, application).toString(); + group = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.GROUP, group).toString(); + version = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.VERSION, version).toString(); + createdOn = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.CREATED_ON, createdOn).toString(); + createdBy = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.CREATED_BY, createdBy).toString(); + modifiedOn = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.MODIFIED_ON, modifiedOn).toString(); + modifiedBy = applicationContentImpl.getProperties() + .getOrDefault(ApplicationProjectContent.STANDARD_PROPERTIES.MODIFIED_BY, modifiedBy).toString(); + + requiredItems.clear(); + includedItems.clear(); + for (ApplicationProjectItemImpl item : applicationContentImpl.getItemsMap().values()) { + List targetList; + if (item.isRequired()) + targetList = requiredItems; + else + targetList = includedItems; + ContentModelItem converted = convert(item); + targetList.add(converted); + } + } + + public JsonObject getAsJson() { + JsonElement je = GSON.toJsonTree(this, ContentModel.class); + if (!je.isJsonObject()) { + return new JsonObject(); + } + JsonObject result = je.getAsJsonObject(); + + // add requirements + JsonArray ja = new JsonArray(); + for (ContentModelItem item : requiredItems) { + JsonElement itemElement = GSON.toJsonTree(item, item.getClass()); + ja.add(itemElement); + } + result.add("requirements", ja); + + // add items + ja = new JsonArray(); + for (ContentModelItem item : includedItems) { + JsonElement itemElement = GSON.toJsonTree(item, item.getClass()); + ja.add(itemElement); + } + result.add("items", ja); + + return result; + } + + protected ContentModelItem convert(ApplicationProjectItemImpl item) { + ContentModelItem result = null; + switch (item.getType()) { + case BUNDLE: + result = new BundleItem(); + break; + case OBJECT: + result = new ObjectItem(); + break; + case CONFIG: + result = new ConfigItem(); + break; + case RESOURCE: + result = new ResourceItem(); + break; + default: + return null; + } + result.setContentModel(this); + result.setId(item.getId()); + result.setGhost(item.isGhost()); + result.setIgnored(item.isIgnored()); + result.setItemScope(item.getScope()); + result.setItemType(item.getType()); + result.setRequired(item.isRequired()); + + if (item.getColocationGroup() != null) + result.setColocationGroupId(item.getColocationGroup().getId()); + + if (item instanceof EntaxyBundleItem) { + BundleItem typedResult = (BundleItem) result; + EntaxyBundleItem typedOrigin = (EntaxyBundleItem) item; + typedResult.setBundleId(typedOrigin.getBundleId()); + typedResult.setBundleSymbolicName(typedOrigin.getBundleSymbolicName()); + } + + if (item instanceof EntaxyObjectItem) { + ObjectItem typedResult = (ObjectItem) result; + EntaxyObjectItem typedOrigin = (EntaxyObjectItem) item; + } + + if (item instanceof EntaxyConfigItem) { + ConfigItem typedResult = (ConfigItem) result; + EntaxyConfigItem typedOrigin = (EntaxyConfigItem) item; + } + + if (item instanceof EntaxyResourceItem) { + ResourceItem typedResult = (ResourceItem) result; + EntaxyResourceItem typedOrigin = (EntaxyResourceItem) item; + } + + return result; + } + + public String getApplication() { + return application; + } + + public void setApplication(String application) { + this.application = application; + } + + public String getGroup() { + return group; + } + + public void setGroup(String group) { + this.group = group; + } + + public String getVersion() { + return version; + } + + public void setVersion(String version) { + this.version = version; + } + + public String getCreatedOn() { + return createdOn; + } + + public void setCreatedOn(String createdOn) { + this.createdOn = createdOn; + } + + public String getCreatedBy() { + return createdBy; + } + + public void setCreatedBy(String createdBy) { + this.createdBy = createdBy; + } + + public String getModifiedOn() { + return modifiedOn; + } + + public void setModifiedOn(String modifiedOn) { + this.modifiedOn = modifiedOn; + } + + public String getModifiedBy() { + return modifiedBy; + } + + public void setModifiedBy(String modifiedBy) { + this.modifiedBy = modifiedBy; + } + + public List getRequiredItems() { + return requiredItems; + } + + public List getIncludedItems() { + return includedItems; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentModelItemWrapper.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentModelItemWrapper.java new file mode 100644 index 00000000..304221d5 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/ContentModelItemWrapper.java @@ -0,0 +1,101 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model; + +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonObject; + +import ru.entaxy.platform.base.support.JSONUtils.ObjectWrapper; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_SCOPE; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.impl.project.model.item.BundleItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ConfigItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ContentModelItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ObjectItem; +import ru.entaxy.platform.integration.applications.impl.project.model.item.ResourceItem; + +public class ContentModelItemWrapper extends ObjectWrapper { + + private static final Logger LOG = LoggerFactory.getLogger(ContentModelItemWrapper.class); + + public static boolean isModelItem(JsonObject object) { + return object.has("id") && object.has("scope") && object.has("type"); + } + + ContentModel contentModel; + + ContentModelItem contentModelItem; + + public ContentModelItemWrapper(ContentModel contentModel) { + super(); + this.contentModel = contentModel; + } + + @Override + public void wrap(JsonObject object, Map context, String path) { + try { + String type = object.get("type").getAsString(); + EntaxyApplication.ITEM_TYPE itemType = EntaxyApplication.ITEM_TYPE.valueOf(type.toUpperCase()); + switch (itemType) { + case BUNDLE: + contentModelItem = ContentModel.GSON.fromJson(object, BundleItem.class); + break; + case CONFIG: + contentModelItem = ContentModel.GSON.fromJson(object, ConfigItem.class); + break; + case OBJECT: + contentModelItem = ContentModel.GSON.fromJson(object, ObjectItem.class); + break; + case RESOURCE: + contentModelItem = ContentModel.GSON.fromJson(object, ResourceItem.class); + break; + default: + return; + } + contentModelItem.setItemType(itemType); + + try { + contentModelItem.setItemScope(EntaxyApplication.ITEM_SCOPE.valueOf(object.get("scope").getAsString().toUpperCase())); + } catch (Exception e) { + contentModelItem.setItemScope(EntaxyApplication.ITEM_SCOPE.UNKNOWN); + } + + if (contentModelItem.isRequired()) + contentModel.requiredItems.add(contentModelItem); + else + contentModel.includedItems.add(contentModelItem); + + } catch (Exception e) { + LOG.error("Error reading object", e); + } + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/BundleItem.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/BundleItem.java new file mode 100644 index 00000000..444a69e6 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/BundleItem.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model.item; + +public class BundleItem extends ContentModelItem { + + long bundleId; + String bundleSymbolicName; + + public long getBundleId() { + return bundleId; + } + + public void setBundleId(long bundleId) { + this.bundleId = bundleId; + } + + public String getBundleSymbolicName() { + return bundleSymbolicName; + } + + public void setBundleSymbolicName(String bundleSymbolicName) { + this.bundleSymbolicName = bundleSymbolicName; + } + + + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ConfigItem.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ConfigItem.java new file mode 100644 index 00000000..99720e42 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ConfigItem.java @@ -0,0 +1,30 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model.item; + +public class ConfigItem extends ObjectItem { + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ContentModelItem.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ContentModelItem.java new file mode 100644 index 00000000..faa25040 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ContentModelItem.java @@ -0,0 +1,109 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model.item; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.impl.project.model.ContentModel; + +public class ContentModelItem { + + transient ContentModel contentModel; + + String id; + boolean required = false; + boolean ignored = false; + boolean ghost = false; + + EntaxyApplication.ITEM_SCOPE scope; + EntaxyApplication.ITEM_TYPE type; + + String colocationGroupId; + + public ContentModel getContentModel() { + return contentModel; + } + + public void setContentModel(ContentModel contentModel) { + this.contentModel = contentModel; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public boolean isRequired() { + return required; + } + + public void setRequired(boolean required) { + this.required = required; + } + + public boolean isIgnored() { + return ignored; + } + + public void setIgnored(boolean ignored) { + this.ignored = ignored; + } + + public boolean isGhost() { + return ghost; + } + + public void setGhost(boolean ghost) { + this.ghost = ghost; + } + + public EntaxyApplication.ITEM_SCOPE getItemScope() { + return scope; + } + + public void setItemScope(EntaxyApplication.ITEM_SCOPE itemScope) { + this.scope = itemScope; + } + + public EntaxyApplication.ITEM_TYPE getItemType() { + return type; + } + + public void setItemType(EntaxyApplication.ITEM_TYPE itemType) { + this.type = itemType; + } + + public String getColocationGroupId() { + return colocationGroupId; + } + + public void setColocationGroupId(String colocationGroupId) { + this.colocationGroupId = colocationGroupId; + } + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ObjectItem.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ObjectItem.java new file mode 100644 index 00000000..5692b86c --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ObjectItem.java @@ -0,0 +1,30 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model.item; + +public class ObjectItem extends BundleItem { + +} diff --git a/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ResourceItem.java b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ResourceItem.java new file mode 100644 index 00000000..253c153d --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/java/ru/entaxy/platform/integration/applications/impl/project/model/item/ResourceItem.java @@ -0,0 +1,30 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.impl.project.model.item; + +public class ResourceItem extends ContentModelItem { + +} diff --git a/platform/integration/applications/application-impl/src/main/resources/ru/entaxy/templates/applications/builder/features.ftl b/platform/integration/applications/application-impl/src/main/resources/ru/entaxy/templates/applications/builder/features.ftl new file mode 100644 index 00000000..d88131f5 --- /dev/null +++ b/platform/integration/applications/application-impl/src/main/resources/ru/entaxy/templates/applications/builder/features.ftl @@ -0,0 +1,31 @@ +[#ftl attributes={"generated.type":"features"}] + + + + + [#list descriptor.getConfigComponents() as config] + + mvn:[=config.mavenLocation] + + [/#list] + [#list descriptor.getBundleComponents() as bundle] + [=bundle.fullTargetLocation] + [/#list] + + [#if revisionNumber??] + [#assign finalRevision=revisionNumber] + [#else] + [#assign finalRevision="0"] + [/#if] + + + entaxy.application;name=[=descriptor.name];version=[=descriptor.version];revision=[=finalRevision] + + + + + \ No newline at end of file diff --git a/platform/integration/applications/application-management/LICENSE.txt b/platform/integration/applications/application-management/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/applications/application-management/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/application-management/pom.xml b/platform/integration/applications/application-management/pom.xml new file mode 100644 index 00000000..bb971372 --- /dev/null +++ b/platform/integration/applications/application-management/pom.xml @@ -0,0 +1,67 @@ + + + 4.0.0 + + ru.entaxy.platform.integration + applications + 1.10.0 + + ru.entaxy.platform.integration.applications + application-management + bundle + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: MANAGEMENT + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: MANAGEMENT + + + ru.entaxy.platform.integration.applications.management + ru.entaxy.platform.integration.applications.management.impl + + + + + + ru.entaxy.esb.platform.runtime.core.management + object-management + ${project.version} + + + org.osgi + org.osgi.service.component.annotations + 1.4.0 + compile + + + org.apache.felix + org.apache.felix.scr + 2.1.20 + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + ru.entaxy.esb.platform.runtime.base + management-core + ${project.version} + + + ru.entaxy.platform.integration.applications + application-api + ${project.version} + + + ru.entaxy.platform.integration.applications + application-impl + ${project.version} + + + commons-io + commons-io + ${commons-io.version} + + + + diff --git a/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/ApplicationsMBean.java b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/ApplicationsMBean.java new file mode 100644 index 00000000..e7ed6d68 --- /dev/null +++ b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/ApplicationsMBean.java @@ -0,0 +1,198 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.management; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; + +import java.util.List; +import java.util.Map; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ApplicationsMBean { + + public static final String MODULE_JMX_DOMAIN = "ru.entaxy.cicd"; + + public static final String MAIN_MODULE_KEY = "module"; + + public static final String MAIN_MODULE_KEY_VALUE = "applications"; + + public static final Qualifier Q_MAIN_MODULE = new Qualifier(MAIN_MODULE_KEY, MAIN_MODULE_KEY_VALUE); + + public static final String Q_MAIN_MODULE_S = MODULE_JMX_DOMAIN + ":" + MAIN_MODULE_KEY + "=" + MAIN_MODULE_KEY_VALUE; + + @Operation(desc = "Gets tree") + String readAsTree() throws Exception; + + @Operation(desc = "Import project from repository") + void importFromRepository( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "mavenUrl", desc = "Maven URL of the application") String mavenUrl + ) throws Exception; + + @Operation(desc = "Import project from base64 string") + void importFromBase64String( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "fileContentBase64String", + desc = "The application file content encoded into base64 string") String fileContentBase64 + ) throws Exception; + + @Operation(desc = "Remove application") + void removeApplication( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName + ) throws Exception; + + @Operation(desc = "List application items") + List> listApplicationItems( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion + ) throws Exception; + + @Operation(desc = "List application requirements") + List> listApplicationRequirements( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion + ) throws Exception; + + @Operation(desc = "Read last and installed revision of the application version") + Map readApplicationVersionLastAndInstalledRevision( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion + ) throws Exception; + + @Operation(desc = "Read application item types") + List readApplicationItemTypes(); + + @Operation(desc = "Read project item scopes") + List readApplicationItemScopes(); + + @Operation(desc = "Remove application version") + void removeVersion(@Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "versionToRemove", desc = "Version to remove") String versionToRemove + ) throws Exception; + + @Operation(desc = "Create revision for application version") + void createRevision( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "prototypeRevision", desc = "Existent revision to base on") int prototypeRevision + ) throws Exception; + + @Operation(desc = "Configure application revision") + void configureRevision( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision + ) throws Exception; + + @Operation(desc = "Deploy application revision") + void deployRevision( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision + ) throws Exception; + + @Operation(desc = "Install application revision") + void installRevision( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision + ) throws Exception; + + @Operation(desc = "Uninstall application revision") + void uninstallRevision( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision + ) throws Exception; + + @Operation(desc = "Get application revision status") + String readRevisionStatus( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision + ) throws Exception; + + @Operation(desc = "List application revision configurations") + List> listRevisionConfigurations( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision + ) throws Exception; + + @Operation(desc = "Read application revision configuration") + Map readRevisionConfiguration( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision, + @Parameter(name = "configId", desc = "Configuration Id") String configId + ) throws Exception; + + @Operation(desc = "Fill in application revision configuration with local configuration values") + void fillInRevisionConfigurationWithLocalValues( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision, + @Parameter(name = "configId", desc = "Configuration Id") String configId + ) throws Exception; + + @Operation(desc = "Save application revision configuration changes") + void saveRevisionConfiguration( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "applicationName", desc = "Name of the application") String applicationName, + @Parameter(name = "applicationVersion", desc = "Version of the application") String applicationVersion, + @Parameter(name = "applicationVersionRevision", desc = "Revision of the application version") + String applicationVersionRevision, + @Parameter(name = "configId", desc = "Configuration Id") String configId, + @Parameter(name = "properties", desc = "Map of changed properties") Map properties + ) throws Exception; + +} diff --git a/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/ProjectsMBean.java b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/ProjectsMBean.java new file mode 100644 index 00000000..30ea670a --- /dev/null +++ b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/ProjectsMBean.java @@ -0,0 +1,198 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.management; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; + +import java.util.List; +import java.util.Map; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ProjectsMBean { + + public static final String MODULE_JMX_DOMAIN = "ru.entaxy.cicd"; + + public static final String MAIN_MODULE_KEY = "module"; + + public static final String MAIN_MODULE_KEY_VALUE = "projects"; + + public static final Qualifier Q_MAIN_MODULE = new Qualifier(MAIN_MODULE_KEY, MAIN_MODULE_KEY_VALUE); + + public static final String Q_MAIN_MODULE_S = MODULE_JMX_DOMAIN + ":" + MAIN_MODULE_KEY + "=" + MAIN_MODULE_KEY_VALUE; + + @Operation(desc = "Gets tree") + String readAsTree() throws Exception; + + @Operation(desc = "List project items") + List> listProjectItems( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "Read project item statuses") + List readProjectItemStatuses(); + + @Operation(desc = "Create project") + void createProject( + @Parameter(name = "projectName", desc = "Name of created project") String projectName, + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "initialVersion", desc = "Initial version for the created project") String initialVersion + ) throws Exception; + + @Operation(desc = "Remove project") + void removeProject( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName + ) throws Exception; + + @Operation(desc = "Add object to the project") + List> addObject( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion, + @Parameter(name = "objectId", desc = "Id of the object") String objectId + ) throws Exception; + + @Operation(desc = "List objects") + List> listObjects() throws Exception; + + @Operation(desc = "Get related objects") + List> getRelatedObjects( + @Parameter(name = "objectId", desc = "Id of the object") String objectId + ) throws Exception; + + @Operation(desc = "Add item to the project") + void addItem( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion, + @Parameter(name = "itemId", desc = "Id of the item") String itemId + ) throws Exception; + + @Operation(desc = "Ignore item from the project") + void ignoreItem( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion, + @Parameter(name = "itemId", desc = "Id of the item") String itemId + ) throws Exception; + + @Operation(desc = "Remove item from the project") + void removeItem( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion, + @Parameter(name = "itemId", desc = "Id of the item") String itemId + ) throws Exception; + + @Operation(desc = "Remove items from the project") + Map> removeItems( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion, + @Parameter(name = "itemIds", desc = "Ids of the items") List itemIds + ) throws Exception; + + @Operation(desc = "Create version") + void createVersion( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "createdVersion", desc = "Created version") String createdVersion, + @Parameter(name = "prototypeVersion", desc = "Existent version to base on") String prototypeVersion + ) throws Exception; + + @Operation(desc = "Remove version") + void removeVersion( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "versionToRemove", desc = "Version to remove") String versionToRemove + ) throws Exception; + + @Operation(desc = "Save project version") + void saveProjectVersion( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "Build project version") + void buildProjectVersion( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "List built project items") + List> listBuiltProjectItems( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "List built project requirements") + List> listBuiltProjectRequirements( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "List built project components") + List> listBuiltProjectComponents( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "Read build info") + String readMavenUrl( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; + + @Operation(desc = "List repositories") + List listRepositories() throws Exception; + + @Operation(desc = "Export project to repository") + void exportToRepository( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion, + @Parameter(name = "repositoryName", desc = "Name of the repository") String repositoryName + ) throws Exception; + + @Operation(desc = "Export project to file") + String exportToFile( + @Parameter(name = "storage", desc = "Name of the storage") String storage, + @Parameter(name = "projectName", desc = "Name of the project") String projectName, + @Parameter(name = "projectVersion", desc = "Version of the project") String projectVersion + ) throws Exception; +} diff --git a/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/impl/ApplicationsMBeanImpl.java b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/impl/ApplicationsMBeanImpl.java new file mode 100644 index 00000000..00f531f4 --- /dev/null +++ b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/impl/ApplicationsMBeanImpl.java @@ -0,0 +1,521 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.management.impl; + +import org.apache.commons.io.FileUtils; +import org.apache.karaf.features.FeaturesService; +import org.osgi.service.component.annotations.*; +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean; +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptor; +import ru.entaxy.platform.base.support.osgi.feature.FeatureCapabilityHelper; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; +import ru.entaxy.platform.integration.applications.*; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ItemNotFoundException; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.management.ApplicationsMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +import javax.management.DynamicMBean; +import javax.management.MBeanRegistration; +import javax.management.NotCompliantMBeanException; +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.*; +import java.util.stream.Collectors; + +@Component( + service = {DynamicMBean.class, MBeanRegistration.class, ApplicationsMBean.class}, + property = {ManagementCore.JMX_OBJECTNAME + "=" + ApplicationsMBean.Q_MAIN_MODULE_S}, + scope = ServiceScope.SINGLETON, + immediate = true +) +public class ApplicationsMBeanImpl extends AnnotatedMBean implements ApplicationsMBean { + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + public ApplicationManager applicationManager; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyResourceService entaxyResourceService; + + public ApplicationsMBeanImpl() throws NotCompliantMBeanException { + super(ApplicationsMBean.class); + } + + @Override + public String readAsTree() { + final String TITLE = "title"; + final String CHILDREN = "children"; + + List> applicationStorages = new ArrayList<>(); + applicationManager.getActiveStorages().forEach(storage -> { + + Map applicationStorage = new HashMap<>(); + applicationStorage.put(TITLE, storage.getName()); + applicationStorage.put(CHILDREN, storage.getApplications().stream().map(application -> { + Map applicationMap = new HashMap<>(); + applicationMap.put(TITLE, application.getName()); + applicationMap.put(CHILDREN, application.getVersions().stream().map(version -> { + Map versionMap = new HashMap<>(); + versionMap.put(TITLE, version.getVersionNumber()); + versionMap.put(CHILDREN, version.getRevisions().stream().map(revision -> { + Map revisionMap = new HashMap<>(); + String revisionTitle = revision.getRevisionNumber() + + " [" + revision.getStatus().toString() + "]"; + revisionMap.put(TITLE, revisionTitle); + return revisionMap; + }).collect(Collectors.toList())); + return versionMap; + }).collect(Collectors.toList())); + return applicationMap; + }).collect(Collectors.toList())); + + applicationStorages.add(applicationStorage); + }); + + return JSONUtils.GSON.toJson(applicationStorages); + } + + @Override + public void importFromRepository(String storage, String mavenUrl) throws Exception { + applicationManager.importApplicationFromRepository(storage, mavenUrl); + } + + @Override + public void importFromBase64String(String storage, String fileContentBase64) throws Exception { + byte[] byteArray = Base64.getDecoder().decode(fileContentBase64); + + Path temp; + try { + temp = Files.createTempFile("TEMP", null); + } catch (IOException e) { + throw e; + } + + File tempFile = temp.toFile().getAbsoluteFile(); + tempFile.getParentFile().mkdirs(); + + try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) { + fileOutputStream.write(byteArray); + + importFromFile(storage, tempFile.getPath()); + } catch (RuntimeException e) { + throw e; + } finally { + FileUtils.deleteQuietly(tempFile); + } + } + + private void importFromFile(String storage, String filePath) throws ApplicationException, StorageException { + applicationManager.importApplicationFromFile(storage, filePath); + } + + @Override + public void removeApplication(String storage, String applicationName) throws Exception { + applicationManager.getStorage(storage).removeApplication(getApplication(storage, applicationName)); + } + + @Override + public List> listApplicationItems(String storage, + String applicationName, + String applicationVersion) { + return getApplicationVersion(storage, applicationName, applicationVersion).getLastRevision() + .getItems().stream().map(item -> { + Map itemMap = new HashMap<>(); + itemMap.put("id", item.getId()); + itemMap.put("type", item.getType().toString()); + itemMap.put("revisionable", item.isRevisionable()); + itemMap.put("editable", item.isEditable()); + return itemMap; + }).collect(Collectors.toList()); + } + + @Override + public List> listApplicationRequirements(String storage, + String applicationName, + String applicationVersion) { + return getApplicationVersion(storage, applicationName, applicationVersion).getLastRevision() + .getDescriptor().getRequirements().stream().map(requirement -> { + Map requirementMap = new HashMap<>(); + requirementMap.put("id", requirement.getId()); + requirementMap.put("type", requirement.getType().toString()); + requirementMap.put("scope", requirement.getScope().toString()); + requirementMap.put("status", checkRequirement(requirement)); + return requirementMap; + }).collect(Collectors.toList()); + } + + // copied from application-shell + private boolean checkRequirement(ApplicationRequirement requirement) { + switch (requirement.type) { + case OBJECT: + EntaxyRuntimeObject runtimeObject = entaxyRuntimeObjectService.getRuntimeObject(requirement.id); + return runtimeObject != null && !runtimeObject.isGhost(); + case RESOURCE: + EntaxyResource entaxyResource = entaxyResourceService.getResource(requirement.id); + return entaxyResource.exists(); + case BUNDLE: + case CONFIG: + // TODO implement + return true; + default: + return true; + } + } + + @Override + public Map readApplicationVersionLastAndInstalledRevision(String storage, + String applicationName, + String applicationVersion) { + EntaxyApplicationVersion version = getApplicationVersion(storage, applicationName, applicationVersion); + Map revisions = new HashMap<>(2); + revisions.put("lastRevision", String.valueOf(version.getLastRevision().getRevisionNumber())); + revisions.put("installedRevision", getInstalledRevisionValue(version)); + return revisions; + } + + protected final static String APP_NAMESPACE = "entaxy.application"; + + @Reference + FeaturesService featuresService; + + // copied from application-shell + protected String getInstalledRevisionValue(EntaxyApplicationVersion version) { + try { + List helpers = Arrays.asList(featuresService.listInstalledFeatures()).stream() + .map(f -> new FeatureCapabilityHelper(f)) + .filter(h -> h.isCapabilityProvided(APP_NAMESPACE)) + .collect(Collectors.toList()); + + for (FeatureCapabilityHelper helper : helpers) { + List descriptors = helper.getProvidedCapabilities(APP_NAMESPACE); + for (CapabilityDescriptor descriptor : descriptors) { + String nameValue = descriptor.getAttributes() + .getOrDefault("name", "").toString(); + String versionValue = descriptor.getAttributes() + .getOrDefault("version", "").toString(); + if (version.getApplication().getName().equals(nameValue) + && version.getVersionNumber().equals(versionValue)) { + String revision = descriptor.getAttributes() + .getOrDefault("revision", "").toString(); + if (CommonUtils.isValid(revision)) + return revision; + } + } + } + } catch (Exception ignore) { + // NOOP +// ignore.printStackTrace(); + } + return "-"; + } + + @Override + public List readApplicationItemTypes() { + return Arrays.stream(EntaxyApplication.ITEM_TYPE.values()) + .map(itemType -> itemType.toString()).collect(Collectors.toList()); + } + + @Override + public List readApplicationItemScopes() { + return Arrays.stream(EntaxyApplication.ITEM_SCOPE.values()) + .map(scope -> scope.toString()).collect(Collectors.toList()); + } + + @Override + public void removeVersion(String storage, String applicationName, String versionToRemove) { + getApplication(storage, applicationName).removeVersion(versionToRemove); + } + + @Override + public void createRevision(String storage, + String applicationName, + String applicationVersion, + int prototypeRevision) throws Exception { + if (prototypeRevision > -1) { + getApplicationVersion(storage, applicationName, applicationVersion).createRevision(prototypeRevision); + } else { + getApplicationVersion(storage, applicationName, applicationVersion).createRevision(); + } + } + + @Override + public void configureRevision(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision).configure(); + } + + @Override + public void deployRevision(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision).deploy(); + } + + @Override + public void installRevision(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision).install(); + } + + @Override + public void uninstallRevision(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision).uninstall(); + } + + @Override + public String readRevisionStatus(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + return getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision) + .getStatus().toString(); + } + + @Override + public List> listRevisionConfigurations(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + return getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision) + .getItems().stream() + .filter(item -> EntaxyApplication.ITEM_TYPE.CONFIG.equals(item.getType())) + .map(item -> { + Map itemMap = new HashMap<>(); + itemMap.put("id", item.getId()); + itemMap.put("location", item.getLocation()); + return itemMap; + }).collect(Collectors.toList()); + } + + @Override + public Map readRevisionConfiguration(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision, + String configId) throws Exception { + + ApplicationItem configItem = getConfigItem(storage, applicationName, applicationVersion, + applicationVersionRevision, configId); + + ObjectConfigEditor editor = getEditor(configId, configItem); + + List> fields = new ArrayList<>(); + + String configuredType = null; + String configuredId = null; + + try { + for (String name : editor.getPropertiesNames()) { + ObjectConfigEditor.ConfigProperty property = editor.getAsConfigProperty(name); + + if (!property.hint.isInternal()) { + Map field = new HashMap<>(); + + field.put("name", name); + field.put("displayName", property.hint.getDisplayName()); + field.put("type", property.hint.getType()); + field.put("importedValue", property.configValue); + field.put("localValue", property.currentValue); + + fields.add(field); + } else { + if ("__entaxy_configuredId".equals(name)) { + configuredId = property.configValue.toString(); + } else if ("__entaxy_configuredType".equals(name)) { + configuredType = property.configValue.toString(); + } + } + } + } catch (Exception e) { + throw e; + } finally { + editor.clear(); + } + + Map configuration = new HashMap<>(); + configuration.put("id", configuredId); + configuration.put("type", configuredType); + configuration.put("fields", fields); + + return configuration; + } + + @Override + public void fillInRevisionConfigurationWithLocalValues(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision, + String configId) throws Exception { + + ApplicationItem configItem = getConfigItem(storage, applicationName, applicationVersion, + applicationVersionRevision, configId); + + ObjectConfigEditor editor = getEditor(configId, configItem); + + InputStream is = null; + try { + for (String propertyName : editor.getPropertiesNames()) { + ObjectConfigEditor.ConfigProperty property = editor.getAsConfigProperty(propertyName); + + if (property.currentValue != null) { + editor.setValue(propertyName, property.currentValue.toString()); + } else { + throw new RuntimeException("Cannot set local values to configuration [" + configId + "]"); + } + } + + editor.save(); + + is = new FileInputStream(editor.getConfigFile()); + configItem.update(is); + } catch (Exception e) { + throw e; + } finally { + editor.clear(); + if (is != null) { + is.close(); + } + } + } + + @Override + public void saveRevisionConfiguration(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision, + String configId, + Map properties) throws Exception { + + ApplicationItem configItem = getConfigItem(storage, applicationName, applicationVersion, + applicationVersionRevision, configId); + + ObjectConfigEditor editor = getEditor(configId, configItem); + + InputStream is = null; + try { + for (String propertyName : properties.keySet()) { + ObjectConfigEditor.ConfigProperty property = editor.getAsConfigProperty(propertyName); + + if (property == null) { + throw new RuntimeException("Property [" + propertyName + "] is not found"); + } + + Object propertyValue = properties.get(propertyName); + + editor.setValue(propertyName, propertyValue == null ? "" : propertyValue.toString()); + } + + editor.save(); + + is = new FileInputStream(editor.getConfigFile()); + configItem.update(is); + } catch (Exception e) { + throw e; + } finally { + editor.clear(); + if (is != null) { + is.close(); + } + } + } + + private ApplicationItem getConfigItem(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision, + String configId) throws Exception { + Optional configItemOpt = + getApplicationRevision(storage, applicationName, applicationVersion, applicationVersionRevision) + .getItems().stream().filter(item -> + EntaxyApplication.ITEM_TYPE.CONFIG.equals(item.getType()) && + configId.equals(item.getId())).findFirst(); + if (configItemOpt.isEmpty()) { + throw new ItemNotFoundException(applicationName, applicationVersion, configId); + } + + return configItemOpt.get(); + } + + private ObjectConfigEditor getEditor(String configId, ApplicationItem configItem) throws Exception { + + Path temp = Files.createTempFile(configId, null); + File tempFile = temp.toFile().getAbsoluteFile(); + tempFile.getParentFile().mkdirs(); + + ObjectConfigEditor editor; + try (InputStream is = configItem.getInputStream()) { + Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + + editor = ObjectConfigEditor.create(tempFile); + editor.loadCurrent(configItem.getId()); + editor.setPid(configId); + } catch (Exception e) { + FileUtils.deleteQuietly(tempFile); + throw e; + } + + return editor; + } + + private EntaxyApplication getApplication(String storage, String applicationName) { + return applicationManager.getStorage(storage).getApplication(applicationName); + } + + private EntaxyApplicationVersion getApplicationVersion(String storage, + String applicationName, + String applicationVersion) { + return getApplication(storage, applicationName).getVersion(applicationVersion); + } + + private EntaxyApplicationRevision getApplicationRevision(String storage, + String applicationName, + String applicationVersion, + String applicationVersionRevision) throws Exception { + return getApplicationVersion(storage, applicationName, applicationVersion) + .getRevision(applicationVersionRevision); + } +} diff --git a/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/impl/ProjectsMBeanImpl.java b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/impl/ProjectsMBeanImpl.java new file mode 100644 index 00000000..ddace70f --- /dev/null +++ b/platform/integration/applications/application-management/src/main/java/ru/entaxy/platform/integration/applications/management/impl/ProjectsMBeanImpl.java @@ -0,0 +1,437 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.management.impl; + +import org.apache.commons.io.IOUtils; +import org.osgi.service.component.annotations.*; +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean; +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.core.artifact.service.ArtifactService; +import ru.entaxy.platform.integration.applications.*; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; +import ru.entaxy.platform.integration.applications.item.project.EntaxyObjectItem; +import ru.entaxy.platform.integration.applications.management.ProjectsMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +import javax.management.DynamicMBean; +import javax.management.MBeanRegistration; +import javax.management.NotCompliantMBeanException; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; +import java.util.stream.Collectors; + +@Component( + service = {DynamicMBean.class, MBeanRegistration.class, ProjectsMBean.class}, + property = {ManagementCore.JMX_OBJECTNAME + "=" + ProjectsMBean.Q_MAIN_MODULE_S}, + scope = ServiceScope.SINGLETON, + immediate = true +) +public class ProjectsMBeanImpl extends AnnotatedMBean implements ProjectsMBean { + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + public ApplicationManager applicationManager; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyResourceService entaxyResourceService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ArtifactService artifactService; + + public ProjectsMBeanImpl() throws NotCompliantMBeanException { + super(ProjectsMBean.class); + } + + @Override + public String readAsTree() { + final String TITLE = "title"; + final String CHILDREN = "children"; + + List> projectStorages = new ArrayList<>(); + applicationManager.getActiveStorages().forEach(storage -> { + + Map projectStorage = new HashMap<>(); + projectStorage.put(TITLE, storage.getName()); + projectStorage.put(CHILDREN, storage.getProjects().stream().map(project -> { + Map projectMap = new HashMap<>(); + projectMap.put(TITLE, project.getName()); + projectMap.put(CHILDREN, project.getVersions().stream().map(version -> { + Map versionMap = new HashMap<>(); + versionMap.put(TITLE, version.getVersionNumber()); + + if (version.isBuildAvailable()) { + Map buildInfo = new HashMap<>(1); + List> buildInfoList = new ArrayList<>(1); + buildInfo.put(TITLE, "build info"); + buildInfoList.add(buildInfo); + versionMap.put(CHILDREN, buildInfoList); + } + return versionMap; + }).collect(Collectors.toList())); + return projectMap; + }).collect(Collectors.toList())); + + projectStorages.add(projectStorage); + }); + + return JSONUtils.GSON.toJson(projectStorages); + } + + @Override + public List> listProjectItems(String storage, String projectName, String projectVersion) { + + return getProjectVersion(storage, projectName, projectVersion) + .getItems().stream().map(item -> { + Map itemMap = new HashMap<>(); + itemMap.put("status", getStatus(item)); + itemMap.put("id", item.getId()); + itemMap.put("type", item.getType().toString()); + itemMap.put("scope", item.getScope().toString()); + itemMap.put("required", item.isRequired()); + itemMap.put("ignored", item.isIgnored()); + if (EntaxyApplication.ITEM_TYPE.OBJECT.equals(item.getType())) { + itemMap.put("displayName", ((EntaxyObjectItem) item).getObject().getDisplayName()); + itemMap.put("runtimeType", ((EntaxyObjectItem) item).getObject().getType()); + } + return itemMap; + }).collect(Collectors.toList()); + } + + private enum STATUS { + INCLUDED, + IGNORED, + REQUIRED, + GHOST + } + + @Override + public List readProjectItemStatuses() { + return Arrays.stream(STATUS.values()).map(status -> status.toString()).collect(Collectors.toList()); + } + + // copied from application-shell + private String getStatus(ApplicationProjectItem item) { + String status = STATUS.INCLUDED.toString(); + if (item.isGhost()) { + status = STATUS.GHOST.toString(); + } + if (item.isRequired()) { + if (item.isIgnored()) { + status = STATUS.IGNORED.toString(); + } else { + status = STATUS.REQUIRED.toString(); + } + } + return status; + } + + @Override + public void createProject(String projectName, String storage, String initialVersion) throws Exception { + String version = CommonUtils.isValid(initialVersion) ? initialVersion : "1.0.0"; + applicationManager.createProject(storage, projectName, version); + } + + @Override + public void removeProject(String storage, String projectName) throws Exception { + applicationManager.getStorage(storage).removeProject(getProject(storage, projectName)); + } + + @Override + public List> addObject(String storage, String projectName, String projectVersion, String objectId) { + EntaxyRuntimeObject object = entaxyRuntimeObjectService.getRuntimeObject(objectId); + + getProjectVersion(storage, projectName, projectVersion) + .addObject(object); + + return getRelatedObjects(object); + } + + @Override + public List> listObjects() { + return entaxyRuntimeObjectService.getObjects().stream().map(object -> { + return objectIntoMap(object); + }).collect(Collectors.toList()); + } + + @Override + public List> getRelatedObjects(String objectId) { + EntaxyRuntimeObject object = entaxyRuntimeObjectService.getRuntimeObject(objectId); + return getRelatedObjects(object); + } + + private List> getRelatedObjects(EntaxyRuntimeObject object) { + return object.getSubordRelations().stream().filter(relation -> { + return EntaxyObject.OBJECT_RELATION.AGGREGATION.equals(relation.getType()) && + !relation.getTarget().isColocatedWith(object); + }).map(relation -> { + EntaxyRuntimeObject relatedObject = relation.getTarget(); + return objectIntoMap(relatedObject); + }).collect(Collectors.toList()); + } + + private Map objectIntoMap(EntaxyRuntimeObject object) { + Map objectMap = new HashMap<>(); + objectMap.put("fullId", object.getObjectFullId()); + objectMap.put("displayName", object.getDisplayName()); + objectMap.put("type", object.getType()); + return objectMap; + } + + @Override + public void addItem(String storage, String projectName, String projectVersion, String itemId) throws Exception { + ApplicationProjectItem projectItem = getProjectItem(storage, projectName, projectVersion, itemId); + if (projectItem != null) { + getProjectVersion(storage, projectName, projectVersion).addItem(projectItem); + } + } + + @Override + public void ignoreItem(String storage, String projectName, String projectVersion, String itemId) throws Exception { + ApplicationProjectItem projectItem = getProjectItem(storage, projectName, projectVersion, itemId); + if (projectItem != null) { + getProjectVersion(storage, projectName, projectVersion).ignoreItem(projectItem); + } + } + + @Override + public void removeItem(String storage, String projectName, String projectVersion, String itemId) throws Exception { + ApplicationProjectItem projectItem = getProjectItem(storage, projectName, projectVersion, itemId); + if (projectItem != null) { + getProjectVersion(storage, projectName, projectVersion).removeItem(projectItem); + } + } + + @Override + public Map> removeItems(String storage, String projectName, String projectVersion, List itemIds) + throws Exception { + EntaxyApplicationProjectVersion version = getProjectVersion(storage, projectName, projectVersion); + + List items = version.getItems().stream() + .filter(item -> itemIds.contains(item.getId())).collect(Collectors.toList()); + + List itemsToRemove = new ArrayList<>(); + Map> itemsImpossibleToRemove = new HashMap<>(); + + for (ApplicationProjectItem item : items) { + List requiredBy = item.getRequiredBy(); + if (requiredBy.isEmpty()) { + itemsToRemove.add(item); + } else { + List requiredLeft = requiredBy.stream() + .filter(requiredByItem -> !itemIds.contains(requiredByItem.getId())) + .collect(Collectors.toList()); + if (requiredLeft.isEmpty()) { + itemsToRemove.add(item); + } else { + itemsImpossibleToRemove.put(item, requiredLeft); + } + } + } + + List itemIdsToRemove = itemsToRemove.stream() + .map(itemToRemove -> itemToRemove.getId()).collect(Collectors.toList()); + + do { + for (ApplicationProjectItem itemToRemove : itemsToRemove) { + version.removeItem(itemToRemove); + } + itemsToRemove = version.getItems().stream() + .filter(item -> itemIdsToRemove.contains(item.getId())).collect(Collectors.toList()); + } while (itemsToRemove.size() > 0); + + if (itemsImpossibleToRemove.size() > 0) { + Map> result = new HashMap<>(); + for (ApplicationProjectItem itemToRemove : itemsImpossibleToRemove.keySet()) { + if (itemIds.contains(itemToRemove.getId())) { + version.removeItem(itemToRemove); + } + result.put(getIdOrDisplayName(itemToRemove), + itemsImpossibleToRemove.get(itemToRemove).stream() + .map(item -> getIdOrDisplayName(item)).collect(Collectors.toList())); + } + return result; + } + + return new HashMap<>(); + } + + private String getIdOrDisplayName(ApplicationProjectItem item) { + String displayName = ""; + if (EntaxyApplication.ITEM_TYPE.OBJECT.equals(item.getType())) { + displayName = ((EntaxyObjectItem) item).getObject().getDisplayName(); + } + return CommonUtils.isValid(displayName) ? displayName : item.getId(); + } + + @Override + public void createVersion(String storage, String projectName, String createdVersion, String prototypeVersion) + throws Exception { + if (CommonUtils.isValid(prototypeVersion)) { + getProject(storage, projectName).createVersion(createdVersion, prototypeVersion); + } else { + getProject(storage, projectName).createVersion(createdVersion); + } + } + + @Override + public void removeVersion(String storage, String projectName, String versionToRemove) { + getProject(storage, projectName).removeVersion(versionToRemove); + } + + @Override + public void saveProjectVersion(String storage, String projectName, String projectVersion) { + getProjectVersion(storage, projectName, projectVersion).save(); + } + + @Override + public void buildProjectVersion(String storage, String projectName, String projectVersion) throws Exception { + getProjectVersion(storage, projectName, projectVersion).build(); + } + + @Override + public List> listBuiltProjectItems(String storage, String projectName, String projectVersion) { + return getProjectVersion(storage, projectName, projectVersion).getBuildInfo().getItems().stream().map(item -> { + Map itemMap = new HashMap<>(); + itemMap.put("id", item.getId()); + itemMap.put("type", item.getType().toString()); + itemMap.put("component", item.getComponentId()); + return itemMap; + }).collect(Collectors.toList()); + } + + @Override + public List> listBuiltProjectRequirements(String storage, + String projectName, + String projectVersion) { + return getProjectVersion(storage, projectName, projectVersion).getBuildInfo().getRequirements() + .stream().map(requirement -> { + Map requirementMap = new HashMap<>(); + requirementMap.put("id", requirement.getId()); + requirementMap.put("type", requirement.getType().toString()); + requirementMap.put("scope", requirement.getScope().toString()); + requirementMap.put("status", checkRequirement(requirement)); + return requirementMap; + }).collect(Collectors.toList()); + } + + // copied from application-shell + private boolean checkRequirement(ApplicationRequirement requirement) { + switch (requirement.type) { + case OBJECT: + EntaxyRuntimeObject runtimeObject = entaxyRuntimeObjectService.getRuntimeObject(requirement.id); + return runtimeObject != null && !runtimeObject.isGhost(); + case RESOURCE: + EntaxyResource entaxyResource = entaxyResourceService.getResource(requirement.id); + return entaxyResource.exists(); + case BUNDLE: + case CONFIG: + // TODO implement + return true; + default: + return true; + } + } + + @Override + public List> listBuiltProjectComponents(String storage, + String projectName, + String projectVersion) { + return getProjectVersion(storage, projectName, projectVersion).getBuildInfo().getComponents() + .stream().map(component -> { + Map componentMap = new HashMap<>(); + componentMap.put("id", component.getId()); + componentMap.put("type", component.getType().toString()); + componentMap.put("priority", String.valueOf(component.getPriority())); + return componentMap; + }).collect(Collectors.toList()); + } + + @Override + public String readMavenUrl(String storage, String projectName, String projectVersion) { + EntaxyApplicationProjectVersion version = getProjectVersion(storage, projectName, projectVersion); + if (version.isBuildAvailable()) { + return version.getBuildInfo().getMavenUrl(); + } else { + return null; + } + } + + @Override + public List listRepositories() { + return artifactService.getRepositories().stream() + .map(repository -> repository.getName()).collect(Collectors.toList()); + } + + @Override + public void exportToRepository(String storage, String projectName, String projectVersion, String repositoryName) + throws Exception { + applicationManager.exportToRepository(getProjectVersion(storage, projectName, projectVersion), repositoryName); + } + + @Override + public String exportToFile(String storage, String projectName, String projectVersion) throws Exception { + try (InputStream is = getProjectVersion(storage, projectName, projectVersion) + .getBuildUrl().openConnection().getInputStream()) { + return Base64.getEncoder().encodeToString(readFromStream(is)); + } + } + + private byte[] readFromStream(InputStream stream) throws IOException { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + IOUtils.copy(stream, baos); + return baos.toByteArray(); + } catch (IOException e) { + throw e; + } + } + + private EntaxyApplicationProject getProject(String storage, String projectName) { + return applicationManager.getStorage(storage).getProject(projectName); + } + + private EntaxyApplicationProjectVersion getProjectVersion(String storage, + String projectName, + String projectVersion) { + return getProject(storage, projectName).getVersion(projectVersion); + } + + private ApplicationProjectItem getProjectItem( + String storage, String projectName, String projectVersion, String itemId) { + + return getProjectVersion(storage, projectName, projectVersion).getItems() + .stream().filter(item -> item.getId().equals(itemId)).findFirst().orElse(null); + } +} diff --git a/platform/integration/applications/application-shell/LICENSE.txt b/platform/integration/applications/application-shell/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/applications/application-shell/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/application-shell/pom.xml b/platform/integration/applications/application-shell/pom.xml new file mode 100644 index 00000000..5487f3fd --- /dev/null +++ b/platform/integration/applications/application-shell/pom.xml @@ -0,0 +1,64 @@ + + 4.0.0 + + ru.entaxy.platform.integration + applications + 1.10.0 + + ru.entaxy.platform.integration.applications + application-shell + bundle + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: SHELL + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: SHELL + + + none + + ru.entaxy.platform.integration.applications.shell* + + + + + + org.apache.karaf.shell + org.apache.karaf.shell.core + ${karaf.version} + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + ru.entaxy.platform.integration.applications + application-api + ${project.version} + + + ru.entaxy.esb.platform.runtime.core + object-runtime-core + ${project.version} + + + org.apache.karaf.config + org.apache.karaf.config.core + ${karaf.version} + + + org.apache.felix + org.apache.felix.configadmin + ${felix.configadmin.version} + + + ru.entaxy.esb.platform.runtime.core.objects-implementations.config-implementation + config-runtime + ${project.version} + + + commons-io + commons-io + ${commons-io.version} + + + + diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/ApplicationManagerCommandSupport.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/ApplicationManagerCommandSupport.java new file mode 100644 index 00000000..c6718b4e --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/ApplicationManagerCommandSupport.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.ApplicationManager; + +public abstract class ApplicationManagerCommandSupport implements Action { + + @Reference + public ApplicationManager applicationManager; + + @Reference + public Session session; +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/ApplicationShell.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/ApplicationShell.java new file mode 100644 index 00000000..bdc606d5 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/ApplicationShell.java @@ -0,0 +1,122 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import java.util.function.Function; + +import org.apache.karaf.shell.support.ansi.SimpleAnsi; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; + +public class ApplicationShell { + + public static final String COMMAND_SCOPE = "entaxy"; + + public static final String COMMAND_APP_NAME_PREFIX = "app-"; + + public static final String COMMAND_PROJECT_NAME_PREFIX = "project-"; + + public static String projectCommandName(String name) { + return COMMAND_PROJECT_NAME_PREFIX.concat("-").concat(name); + } + + public static final String PROJECT_KEY = "ApplicationShell.project"; + + public static final String PROJECT_VERSION_KEY = "ApplicationShell.projectVersion"; + + public static final String APPLICATION_KEY = "ApplicationShell.application"; + + public static final String APPLICATION_VERSION_KEY = "ApplicationShell.applicationVersion"; + + public static final String APPLICATION_REVISION_KEY = "ApplicationShell.applicationRevision"; + + public static final String APPLICATION_CONFIG_KEY = "ApplicationShell.applicationConfig"; + + // Welocme color + public static String WLC = "\u001B[36m"; + // OK color: High Intensity Foreground Color: Green + public static String OKC = SimpleAnsi.COLOR_GREEN; + // WARN color: High Intensity Foreground Color: Yellow + public static String WARNC = SimpleAnsi.COLOR_YELLOW; + // CRITICAL color: High Intensity Foreground Color: Red + public static String CRT = SimpleAnsi.COLOR_RED + SimpleAnsi.INTENSITY_BOLD; + // reset colors + public static String NOR = "\33[0m"; + + public static String COLOR_REQUIRED = CRT; + public static String COLOR_INCLUDED = OKC + SimpleAnsi.INTENSITY_BOLD; + public static String COLOR_IGNORED = SimpleAnsi.COLOR_BLUE + SimpleAnsi.INTENSITY_BOLD; + public static String COLOR_GHOST = WARNC + SimpleAnsi.INTENSITY_BOLD; + + public static String COLOR_GRAY = "\33[38;2;100;100;100m" + SimpleAnsi.INTENSITY_BOLD; + + public static String COLOR_RESET = NOR + SimpleAnsi.INTENSITY_NORMAL; + + public static String colRequired(String data) { + return COLOR_REQUIRED + data + COLOR_RESET; + } + + public static String colIncluded(String data) { + return COLOR_INCLUDED + data + COLOR_RESET; + } + + public static String colIgnored(String data) { + return COLOR_IGNORED + data + COLOR_RESET; + } + + public static String colGhost(String data) { + return COLOR_GHOST + data + COLOR_RESET; + } + + public static Function normalColorProvider = + (str -> SimpleAnsi.RESET + SimpleAnsi.INTENSITY_NORMAL); + + public static Function normalColorProviderExt = + (cellData -> SimpleAnsi.RESET + SimpleAnsi.INTENSITY_NORMAL); + + public static Function itemStatusColorProvider = (str -> { + if ("+".equals(str)) + return COLOR_INCLUDED; + else if ("-".equals(str)) + return COLOR_IGNORED; + else if ("!".equals(str)) + return COLOR_REQUIRED; + else if ("?".equals(str)) + return COLOR_GHOST; + else + return ""; + }); + + public static Function requirementStatusColorProvider = (str -> { + if ("V".equals(str)) + return COLOR_INCLUDED; + else if ("X".equals(str)) + return COLOR_REQUIRED; + else + return ""; + }); + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/FeatureCapabilityHelper.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/FeatureCapabilityHelper.java new file mode 100644 index 00000000..983a572e --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/FeatureCapabilityHelper.java @@ -0,0 +1,69 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import java.util.List; + +import org.apache.karaf.features.Capability; +import org.apache.karaf.features.Feature; + +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptorImpl; +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityHelper; + +/** + * @deprecated use {@link ru.entaxy.platform.base.support.osgi.feature.FeatureCapabilityHelper} + * instead + */ +@Deprecated +public class FeatureCapabilityHelper extends CapabilityHelper { + + protected Feature feature; + + public FeatureCapabilityHelper(Feature feature) { + super(); + setMultipleNamespacesSupported(true); + this.feature = feature; + load(); + } + + @Override + protected void load() { + super.load(); + List featureCapabilities = feature.getCapabilities(); + for (Capability c : featureCapabilities) { + String[] caps = c.getValue().split(","); + for (String cap : caps) + try { + CapabilityDescriptorImpl descriptor = parseCapability(cap); + if (descriptor != null) + addProvidedCapability(descriptor); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageAwareCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageAwareCommand.java new file mode 100644 index 00000000..e6459dfb --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageAwareCommand.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Completion; + +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.shell.completers.StorageCompleter; + +public abstract class StorageAwareCommand extends ApplicationManagerCommandSupport { + + @Argument(name = "storage", required = true) + @Completion(caseSensitive = false, value = StorageCompleter.class) + public String storage; + + public ApplicationStorage applicationStorage; + + @Override + public Object execute() throws Exception { + applicationStorage = applicationManager.getStorage(storage); + if (applicationStorage == null) + throw new IllegalArgumentException("Storage not found: " + storage); + doExecute(); + return null; + } + + protected abstract void doExecute(); +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageDisableCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageDisableCommand.java new file mode 100644 index 00000000..3e1e22c5 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageDisableCommand.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +@Service +@Command(name = "app-storage-disable", scope = ApplicationShell.COMMAND_SCOPE) +public class StorageDisableCommand extends StorageAwareCommand { + + @Override + protected void doExecute() { + applicationStorage.disable(); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageEnableCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageEnableCommand.java new file mode 100644 index 00000000..bfa0767d --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageEnableCommand.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +@Service +@Command(name = "app-storage-enable", scope = ApplicationShell.COMMAND_SCOPE) +public class StorageEnableCommand extends StorageAwareCommand { + + @Override + protected void doExecute() { + applicationStorage.enable(); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageListCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageListCommand.java new file mode 100644 index 00000000..465726b8 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/StorageListCommand.java @@ -0,0 +1,80 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.ApplicationStorage; + +@Service +@Command(name = "app-storage-list", scope = ApplicationShell.COMMAND_SCOPE) +public class StorageListCommand extends ApplicationManagerCommandSupport { + + @Option(name = "-d", aliases = {"--show-disabled"}, required = false, description = "Show disabled storage also") + boolean showDisabled = false; + + @Override + public Object execute() throws Exception { + + List storages = + showDisabled ? applicationManager.getAllStorages() : applicationManager.getActiveStorages(); + + Collections.sort(storages, new Comparator() { + @Override + public int compare(ApplicationStorage o1, ApplicationStorage o2) { + return o1.getName().compareTo(o2.getName()); + } + }); + + ShellTableFixed table = new ShellTableFixed(); + table.column("Name"); + table.column("Type"); + table.column("Enabled"); + table.column("Info"); + + for (ApplicationStorage storage : storages) { + String storageInfo = storage.getInfo().entrySet().stream() + .map(entry -> entry.getKey().concat(": ") + .concat(entry.getValue() == null ? "" : entry.getValue().toString())) + .collect(Collectors.joining("\n")); + table.addRow().addContent(storage.getName(), storage.getType(), storage.isEnabled() ? "*" : "", + storageInfo); + } + + table.print(System.out); + + return null; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationCheckBundleCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationCheckBundleCommand.java new file mode 100644 index 00000000..41bd02c1 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationCheckBundleCommand.java @@ -0,0 +1,94 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.util.List; + +import org.apache.karaf.bundle.core.BundleService; +import org.apache.karaf.features.Feature; +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptor; +import ru.entaxy.platform.base.support.osgi.feature.FeatureCapabilityHelper; +import ru.entaxy.platform.base.support.osgi.feature.FeaturesUtils.FeaturesHelper; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-bundle-check", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationCheckBundleCommand extends ApplicationManagerCommandSupport { + + protected final static String APP_NAMESPACE = "entaxy.application"; + + @Reference + BundleContext bundleContext; + + @Argument(required = true) + long bundleId; + + @Reference + BundleService bundleService; + + @Override + public Object execute() throws Exception { + + Bundle b = bundleContext.getBundle(bundleId); + List features = FeaturesHelper.create(bundleContext).withCapabilityNamespace(APP_NAMESPACE) + .containingBundle(b).installedOnly().find(); + + ShellTableExt shellTable = new ShellTableExt(); + shellTable.column("Application"); + shellTable.column("Version"); + shellTable.column("Revision"); + + for (Feature feature : features) { + FeatureCapabilityHelper capabilityHelper = new FeatureCapabilityHelper(feature); + List descriptors = capabilityHelper.getProvidedCapabilities(APP_NAMESPACE); + for (CapabilityDescriptor descriptor : descriptors) { + String name = descriptor.getAttributes().getOrDefault("name", "").toString(); + if (!CommonUtils.isValid(name)) + continue; + String version = descriptor.getAttributes().getOrDefault("version", "").toString(); + String revision = descriptor.getAttributes().getOrDefault("revision", "").toString(); + + shellTable.addRow().addContent(name, version, revision); + } + } + + // print output + shellTable.print(System.out); + + return null; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationImportFromFile.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationImportFromFile.java new file mode 100644 index 00000000..96b65483 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationImportFromFile.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.StorageAwareCommand; + +@Service +@Command(name = "app-import-file", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationImportFromFile extends StorageAwareCommand { + + @Argument(required = true, index = 1) + String filePath; + + @Override + protected void doExecute() { + try { + applicationManager.importApplicationFromFile(storage, filePath); + } catch (Exception e) { + // print error + System.err.println("ERROR: " + e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationImportFromRepository.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationImportFromRepository.java new file mode 100644 index 00000000..3f32ec30 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationImportFromRepository.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.StorageAwareCommand; + +@Service +@Command(name = "app-import-repository", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationImportFromRepository extends StorageAwareCommand { + + @Argument(required = true, index = 1) + String mavenUrl; + + @Override + protected void doExecute() { + try { + applicationManager.importApplicationFromRepository(storage, mavenUrl); + } catch (Exception e) { + // print error + System.err.println("ERROR: " + e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationListCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationListCommand.java new file mode 100644 index 00000000..6263de8e --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationListCommand.java @@ -0,0 +1,137 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.features.FeaturesService; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptor; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.FeatureCapabilityHelper; + +@Service +@Command(name = "app-list", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationListCommand extends ApplicationManagerCommandSupport { + + protected final static String APP_NAMESPACE = "entaxy.application"; + + @Reference + FeaturesService featuresService; + + @Override + public Object execute() throws Exception { + ShellTableFixed table = new ShellTableFixed(); + table.column("Name"); + table.column("Storage"); + table.column("Versions"); + table.column("Last revision").alignCenter(); + table.column("Installed revision").alignCenter(); + + List apps = applicationManager.getApplications(); + Collections.sort(apps, new Comparator() { + + @Override + public int compare(EntaxyApplication o1, EntaxyApplication o2) { + String storage1 = o1.getStorage().getName(); + String storage2 = o2.getStorage().getName(); + if (!storage1.equals(storage2)) + return storage1.compareTo(storage2); + + return o1.getName().compareTo(o2.getName()); + } + + }); + + for (EntaxyApplication app : apps) { + List versions = app.getVersions(); + Collections.sort(versions, new Comparator() { + + @Override + public int compare(EntaxyApplicationVersion o1, EntaxyApplicationVersion o2) { + return o1.compareTo(o2); + } + + }); + String versionsValue = versions.stream().map(v -> v.getVersionNumber()).collect(Collectors.joining("\n")); + String lastRevisionsValue = versions.stream().map(v -> v.getLastRevision().getRevisionNumber() + "") + .collect(Collectors.joining("\n")); + String installedRevisionsValue = versions.stream().map(v -> getInstalledRevisionValue(v)) + .collect(Collectors.joining("\n"));; + + table.addRow().addContent(app.getName(), app.getStorage() == null ? "" : app.getStorage().getName(), + versionsValue, lastRevisionsValue, installedRevisionsValue); + } + + // print output + table.print(System.out); + + return null; + } + + protected String getInstalledRevisionValue(EntaxyApplicationVersion version) { + try { + List helpers = Arrays.asList(featuresService.listInstalledFeatures()).stream() + .map(f -> new FeatureCapabilityHelper(f)) + .filter(h -> h.isCapabilityProvided(APP_NAMESPACE)) + .collect(Collectors.toList()); + + for (FeatureCapabilityHelper helper : helpers) { + List descriptors = helper.getProvidedCapabilities(APP_NAMESPACE); + for (CapabilityDescriptor descriptor : descriptors) { + String nameValue = descriptor.getAttributes().getOrDefault("name", "").toString(); + String versionValue = descriptor.getAttributes().getOrDefault("version", "").toString(); + if (version.getApplication().getName().equals(nameValue) + && version.getVersionNumber().equals(versionValue)) { + String revision = descriptor.getAttributes().getOrDefault("revision", "").toString(); + if (CommonUtils.isValid(revision)) + return revision; + } + + } + + } + + } catch (Exception ignore) { + // NOOP + ignore.printStackTrace(); + } + return ""; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationManageCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationManageCommand.java new file mode 100644 index 00000000..d6250eaf --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationManageCommand.java @@ -0,0 +1,114 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.completers.ApplicationCompleter; + +@Service +@Command(name = "app-manage", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationManageCommand extends ApplicationManagerCommandSupport { + + @Argument + @Completion(value = ApplicationCompleter.class) + String application; + + @Option(name = "-f", aliases = {"--force-cancel"}) + boolean forceCancel = false; + + @Override + public Object execute() throws Exception { + if (session.get(ApplicationShell.APPLICATION_KEY) != null) { + if (forceCancel) { + try { + EntaxyApplicationVersion version = + (EntaxyApplicationVersion) session.get(ApplicationShell.APPLICATION_VERSION_KEY); + } catch (Exception ignore) { + + } + try { + EntaxyApplication application = + (EntaxyApplication) session.get(ApplicationShell.APPLICATION_KEY); + } catch (Exception ignore) { + + } + session.put(ApplicationShell.APPLICATION_KEY, null); + session.put(ApplicationShell.APPLICATION_VERSION_KEY, null); + } else { + // print error + System.err.println("Other application is being managed, please commit or cancel"); + return null; + } + } + + String[] data = application.split("@"); + + if (data.length < 2) { + // print error + System.err.println("Incorrect application specified"); + return null; + } + + String storageName = data[1]; + ApplicationStorage storage = applicationManager.getStorage(storageName); + if (storage == null) { + // print error + System.err.println("Incorrect storage specified: [" + storageName + "]"); + return null; + } + + if (!storage.isEnabled()) { + // print error + System.err.println("Storage is disabled: [" + storageName + "]"); + return null; + } + + String appName = data[0]; + EntaxyApplication app = storage.getApplication(appName); + if (app == null) { + // print error + System.err.println(String.format("Application [%s] not found in storage [%s]", appName, storageName)); + return null; + } + + session.put(ApplicationShell.APPLICATION_KEY, app); + session.put(ApplicationShell.APPLICATION_VERSION_KEY, null); + session.put(ApplicationShell.APPLICATION_REVISION_KEY, null); + + return null; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationRemoveCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationRemoveCommand.java new file mode 100644 index 00000000..92a2da8e --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationRemoveCommand.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.exceptions.ProjectNotFoundException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.StorageAwareCommand; + +@Service +@Command(name = "app-remove", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationRemoveCommand extends StorageAwareCommand { + + @Argument(name = "applicationName", required = true, index = 1) + String applicationName; + + @Override + protected void doExecute() { + try { + EntaxyApplication app = applicationStorage.getApplication(applicationName); + if (app != null) { + applicationStorage.removeApplication(app); + System.out.println("Removed successfully"); + } else { + throw new ProjectNotFoundException(applicationName); + } + } catch (Exception e) { + // output error + System.err.println("ERROR: " + e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionManageCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionManageCommand.java new file mode 100644 index 00000000..b1cf8a0d --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionManageCommand.java @@ -0,0 +1,57 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-version-manage", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationVersionManageCommand extends ApplicationVersionSupport { + + @Override + protected void doExecute(EntaxyApplication application) { + if (session.get(ApplicationShell.APPLICATION_VERSION_KEY) != null) { + // print error + System.err.println("Another version is being managed, please cancel or commit"); + return; + } + + EntaxyApplicationVersion version = application.getVersion(versionNumber); + if (version == null) { + System.err.println("Version not found"); + return; + } + + session.put(ApplicationShell.APPLICATION_VERSION_KEY, version); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionRemoveCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionRemoveCommand.java new file mode 100644 index 00000000..7fd48b35 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionRemoveCommand.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-version-remove", scope = ApplicationShell.COMMAND_SCOPE) +public class ApplicationVersionRemoveCommand extends ApplicationVersionSupport { + + @Override + protected void doExecute(EntaxyApplication application) { + application.removeVersion(versionNumber); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionSupport.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionSupport.java new file mode 100644 index 00000000..f72f731a --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ApplicationVersionSupport.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Completion; + +import ru.entaxy.platform.integration.applications.shell.completers.ApplicationVersionCompleter; + +public abstract class ApplicationVersionSupport extends ManagedApplicationCommand { + + @Argument(required = true) + @Completion(value = ApplicationVersionCompleter.class) + String versionNumber; + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigCancelCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigCancelCommand.java new file mode 100644 index 00000000..a1775f33 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigCancelCommand.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; + +@Service +@Command(name = "app-revision-config-cancel", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigCancelCommand extends ManagedApplicationConfigCommand { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision, ObjectConfigEditor editor) { + + editor.clear(); + session.put(ApplicationShell.APPLICATION_CONFIG_KEY, null); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigCommitCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigCommitCommand.java new file mode 100644 index 00000000..75228798 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigCommitCommand.java @@ -0,0 +1,85 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.util.Optional; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; + +@Service +@Command(name = "app-revision-config-commit", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigCommitCommand extends ManagedApplicationConfigCommand { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision, ObjectConfigEditor editor) { + + Optional configItemOpt = revision.getItems().stream() + .filter(item -> item.getType().equals(ITEM_TYPE.CONFIG) && editor.getPid().equals(item.getId())) + .findFirst(); + if (configItemOpt.isEmpty()) { + // output error + System.err.println("ERROR: config [" + editor.getPid() + "] not found"); + return; + } + + ApplicationItem configItem = configItemOpt.get(); + + try { + editor.save(); + } catch (Exception e) { + // output error + System.err.println("ERROR: failed saving config [" + editor.getPid() + "], see exception below"); + e.printStackTrace(); + return; + } + + try (InputStream is = new FileInputStream(editor.getConfigFile())) { + configItem.update(is); + } catch (Exception e) { + // output error + System.err.println("ERROR: failed saving config [" + editor.getPid() + "], see exception below"); + e.printStackTrace(); + return; + } + + editor.clear(); + session.put(ApplicationShell.APPLICATION_CONFIG_KEY, null); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigEditCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigEditCommand.java new file mode 100644 index 00000000..33e6919f --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigEditCommand.java @@ -0,0 +1,122 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Optional; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; +import ru.entaxy.platform.integration.applications.shell.completers.ConfigCompleter; + +@Service +@Command(name = "app-revision-config-edit", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigEditCommand extends ManagedApplicationRevisionCommand { + + @Argument(required = true) + @Completion(value = ConfigCompleter.class) + String configId; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + + ObjectConfigEditor editor = (ObjectConfigEditor) session.get(ApplicationShell.APPLICATION_CONFIG_KEY); + + if (editor != null) { + // print error + System.err.println("ERROR: another config is being edited, please commit or cancel it first"); + return; + } + + Optional configItemOpt = revision.getItems().stream() + .filter(item -> item.getType().equals(ITEM_TYPE.CONFIG) && configId.equals(item.getId())).findFirst(); + if (configItemOpt.isEmpty()) { + // output error + System.err.println("ERROR: config [" + configId + "] not found"); + return; + } + + ApplicationItem configItem = configItemOpt.get(); + + File tempFile = null; + + try { + Path temp = Files.createTempFile(configId, null); + tempFile = temp.toFile().getAbsoluteFile(); + tempFile.getParentFile().mkdirs(); + } catch (IOException e) { + // output error + System.err.println("ERROR: can't create temp file, see exception below:\n"); + e.printStackTrace(); + return; + } + + try (InputStream is = configItem.getInputStream()) { + Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + // output error + System.err.println("ERROR: can't write to temp file, see exception below:\n"); + e.printStackTrace(); + return; + } + + try { + editor = ObjectConfigEditor.create(tempFile); + } catch (IOException e) { + System.err.println("ERROR: can't create config editor, see exception below:\n"); + e.printStackTrace(); + return; + } + + try { + editor.loadCurrent(configItem.getId()); + } catch (Exception e) { + System.err.println("WARN: can't create config editor, see exception below:\n"); + e.printStackTrace(); + } + + editor.setPid(configId); + + session.put(ApplicationShell.APPLICATION_CONFIG_KEY, editor); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigListCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigListCommand.java new file mode 100644 index 00000000..925b0999 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigListCommand.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-config-list", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigListCommand extends RevisionSupport { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + + ShellTableFixed table = new ShellTableFixed(); + table.column("Id"); + table.column("Location"); + + for (ApplicationItem item : revision.getItems().stream().filter(it -> it.getType().equals(ITEM_TYPE.CONFIG)) + .collect(Collectors.toList())) { + table.addRow().addContent(item.getId(), item.getLocation()); + } + + table.print(System.out); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigPrintCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigPrintCommand.java new file mode 100644 index 00000000..b865864e --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigPrintCommand.java @@ -0,0 +1,139 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.util.Optional; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor.ConfigProperty; + +@Service +@Command(name = "app-revision-config-print", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigPrintCommand extends RevisionSupport { + + @Argument(required = true) + String configId; + + @Option(name = "-s", aliases = {"--show-system-properties"}) + boolean showSystemProperties = false; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + + Optional configItemOpt = revision.getItems().stream() + .filter(item -> item.getType().equals(ITEM_TYPE.CONFIG) && configId.equals(item.getId())).findFirst(); + if (configItemOpt.isEmpty()) { + // output error + System.err.println("ERROR: config [" + configId + "] not found"); + return; + } + + ApplicationItem configItem = configItemOpt.get(); + + File tempFile = null; + + try { + Path temp = Files.createTempFile(configId, null); + tempFile = temp.toFile().getAbsoluteFile(); + tempFile.getParentFile().mkdirs(); + } catch (IOException e) { + // output error + System.err.println("ERROR: can't create temp file, see exception below:\n"); + e.printStackTrace(); + return; + } + + try (InputStream is = configItem.getInputStream()) { + Files.copy(is, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + // output error + System.err.println("ERROR: can't write to temp file, see exception below:\n"); + e.printStackTrace(); + return; + } + + ObjectConfigEditor editor = null; + + try { + editor = ObjectConfigEditor.create(tempFile); + } catch (IOException e) { + System.err.println("ERROR: can't create config editor, see exception below:\n"); + e.printStackTrace(); + return; + } + + try { + editor.loadCurrent(configItem.getId()); + } catch (Exception e) { + System.err.println("WARN: can't create config editor, see exception below:\n"); + e.printStackTrace(); + } + + ShellTableFixed table = new ShellTableFixed(); + table.column("Name"); + table.column("Display Name"); + table.column("Is system"); + table.column("Type"); + table.column("Value"); + table.column("Current Value"); + + for (String name : editor.getPropertiesNames()) { + ConfigProperty property = editor.getAsConfigProperty(name); + if (property.hint.isInternal() && !showSystemProperties) + continue; + table.addRow().addContent( + name, + property.hint.getDisplayName(), + property.hint.isInternal(), + property.hint.getType(), + property.configValue == null ? "" : property.configValue.toString(), + property.currentValue == null ? "" : property.currentValue.toString()); + + } + + table.print(System.out); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigSetPropertyCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigSetPropertyCommand.java new file mode 100644 index 00000000..201e7201 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigSetPropertyCommand.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor.ConfigProperty; + +@Service +@Command(name = "app-revision-config-set", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigSetPropertyCommand extends ManagedApplicationConfigCommand { + + @Argument(required = true, index = 0) + String propertyName; + + @Argument(required = true, index = 1) + String propertyValue; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision, ObjectConfigEditor editor) { + + ConfigProperty property = editor.getAsConfigProperty(propertyName); + if (property == null) { + // output error + System.err.println("ERROR: property [" + propertyName + "] not found"); + return; + } + + if (property.hint.isInternal()) { + // output error + System.err.println("ERROR: property [" + propertyName + "] is system, it can't be updated"); + return; + } + + try { + editor.setValue(propertyName, propertyValue); + } catch (Exception e) { + // output error + System.err.println("ERROR: setting property [" + propertyName + "], see exception below"); + e.printStackTrace(); + return; + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigStatusCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigStatusCommand.java new file mode 100644 index 00000000..70aaa6d6 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ConfigStatusCommand.java @@ -0,0 +1,151 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.util.function.Function; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.config.runtime.ObjectConfig.ConfigFieldHint; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor.ConfigProperty; + +@Service +@Command(name = "app-revision-config-status", scope = ApplicationShell.COMMAND_SCOPE) +public class ConfigStatusCommand extends ManagedApplicationConfigCommand { + + @Option(name = "-s", aliases = {"--show-system-properties"}) + boolean showSystemProperties = false; + + ConfigFieldHint currentHint = null; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision, ObjectConfigEditor editor) { + + Function isSystemColorProvider = (str -> { + if (currentHint == null) + return ApplicationShell.COLOR_RESET; + if (currentHint.isInternal()) + return ApplicationShell.COLOR_GRAY; + return ApplicationShell.COLOR_RESET; + }); + + Function isSystemColorProviderExt = (cellData -> { + + if (cellData.dataObject == null) + return ApplicationShell.COLOR_RESET; + + if (!(cellData.dataObject instanceof ConfigProperty)) + return ApplicationShell.COLOR_RESET; + + ConfigProperty configProperty = (ConfigProperty) cellData.dataObject; + + if (configProperty.hint == null) + return ApplicationShell.COLOR_RESET; + if (configProperty.hint.isInternal()) + return ApplicationShell.COLOR_GRAY; + return ApplicationShell.COLOR_RESET; + }); + + Function isNewValueProviderExt = (cellData -> { + + if (cellData.dataObject == null) + return ApplicationShell.COLOR_RESET; + + if (!(cellData.dataObject instanceof ConfigProperty)) + return ApplicationShell.COLOR_RESET; + + ConfigProperty configProperty = (ConfigProperty) cellData.dataObject; + + if (configProperty.currentValue == null) + return ApplicationShell.COLOR_INCLUDED; + return ApplicationShell.COLOR_RESET; + }); + + Function isAbsentValueProviderExt = (cellData -> { + + if (cellData.dataObject == null) + return ApplicationShell.COLOR_RESET; + + if (!(cellData.dataObject instanceof ConfigProperty)) + return ApplicationShell.COLOR_RESET; + + ConfigProperty configProperty = (ConfigProperty) cellData.dataObject; + + if (configProperty.configValue == null) + return ApplicationShell.COLOR_REQUIRED; + return ApplicationShell.COLOR_RESET; + }); + + Function isModifiedColorProvider = (cellData -> { + if (cellData.dataObject == null) + return ApplicationShell.COLOR_RESET; + return ApplicationShell.COLOR_IGNORED; + }); + + ShellTableExt table = new ShellTableExt(); + table.column("Name").colorProviderExt(isSystemColorProviderExt); + table.column("Display Name").colorProvider(ApplicationShell.normalColorProvider); + table.column("Is system"); + table.column("Type"); + table.column("Imported Value").colorProviderExt(isNewValueProviderExt); + table.column("Modified Value").colorProviderExt(isModifiedColorProvider); + table.column("Local Value").colorProviderExt(isAbsentValueProviderExt); + + for (String name : editor.getPropertiesNames()) { + ConfigProperty property = editor.getAsConfigProperty(name); + currentHint = property.hint; + if (property.hint.isInternal() && !showSystemProperties) + continue; + table.addRow(property).addContent( + name, + property.hint.getDisplayName(), + property.hint.isInternal(), + property.hint.getType(), + property.configValue == null ? "" : property.configValue.toString(), + property.modifiedValue == null ? "" : property.modifiedValue.toString(), + property.currentValue == null ? "" : property.currentValue.toString()); + + } + + // output data + System.out.println("PID:\t" + editor.getPid()); + System.out.println("Modified:\t" + editor.isDirty()); + System.out.println("Temp file:\t" + editor.getConfigFile().getAbsolutePath()); + System.out.println("\n\tPROPERTIES:"); + table.print(System.out); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationCommand.java new file mode 100644 index 00000000..210d9f2a --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationCommand.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +public abstract class ManagedApplicationCommand extends ApplicationManagerCommandSupport { + + @Override + public Object execute() throws Exception { + if (session.get(ApplicationShell.APPLICATION_KEY) == null) { + // print error + System.err.println("No application is being managed"); + return null; + } + EntaxyApplication app = (EntaxyApplication) session.get(ApplicationShell.APPLICATION_KEY); + doExecute(app); + return null; + } + + protected abstract void doExecute(EntaxyApplication application); + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationConfigCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationConfigCommand.java new file mode 100644 index 00000000..f9e413cf --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationConfigCommand.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.config.runtime.ObjectConfigEditor; + +public abstract class ManagedApplicationConfigCommand extends ManagedApplicationRevisionCommand { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + ObjectConfigEditor editor = + (ObjectConfigEditor) session.get(ApplicationShell.APPLICATION_CONFIG_KEY); + if (editor == null) { + // print error + System.err.println("No config is being edited"); + return; + } + doExecute(application, version, revision, editor); + } + + protected abstract void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision, ObjectConfigEditor editor); +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationRevisionCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationRevisionCommand.java new file mode 100644 index 00000000..201b69a8 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationRevisionCommand.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +public abstract class ManagedApplicationRevisionCommand extends ManagedApplicationVersionCommand { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version) { + EntaxyApplicationRevision revision = + (EntaxyApplicationRevision) session.get(ApplicationShell.APPLICATION_REVISION_KEY); + if (revision == null) { + // print error + System.err.println("No revision is being managed"); + return; + } + doExecute(application, version, revision); + } + + protected abstract void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision); +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationVersionCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationVersionCommand.java new file mode 100644 index 00000000..4a20c7b1 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/ManagedApplicationVersionCommand.java @@ -0,0 +1,47 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +public abstract class ManagedApplicationVersionCommand extends ManagedApplicationCommand { + + @Override + protected void doExecute(EntaxyApplication application) { + EntaxyApplicationVersion version = + (EntaxyApplicationVersion) session.get(ApplicationShell.APPLICATION_VERSION_KEY); + if (version == null) { + // print error + System.err.println("No version is being managed"); + return; + } + doExecute(application, version); + } + + protected abstract void doExecute(EntaxyApplication application, EntaxyApplicationVersion version); +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionConfigureCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionConfigureCommand.java new file mode 100644 index 00000000..29f79843 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionConfigureCommand.java @@ -0,0 +1,54 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-configure", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionConfigureCommand extends RevisionSupport { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + try { + revision.configure(); + session.put(ApplicationShell.APPLICATION_REVISION_KEY, revision); + printRevision(revision); + } catch (RevisionException e) { + // output error + System.err.println("ERROR: " + e.getMessage()); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionCreateCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionCreateCommand.java new file mode 100644 index 00000000..5d32074d --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionCreateCommand.java @@ -0,0 +1,85 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-create", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionCreateCommand extends ManagedApplicationVersionCommand { + + @Option(name = "-r", aliases = {"--from-revision"}, required = false) + String fromRevision; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version) { + + int sourceRevision = -1; + + if (CommonUtils.isValid(fromRevision)) + try { + sourceRevision = Integer.parseInt(fromRevision); + } catch (Exception e) { + // print error + System.err.println("Invalid source revision number: " + fromRevision); + return; + } + + EntaxyApplicationRevision revision = null; + + try { + if (sourceRevision < 0) + revision = version.createRevision(); + else + revision = version.createRevision(sourceRevision); + } catch (ApplicationVersionException e) { + // print error + System.err.println("Error creating revision: " + e.getMessage()); + e.printStackTrace(); + } + + if (revision == null) { + // print error + System.err.println("Error creating revision: revision is null"); + return; + } + + // print result + System.out.println(String.format("Created revision %d with status %s", revision.getRevisionNumber(), + revision.getStatus())); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionDeployCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionDeployCommand.java new file mode 100644 index 00000000..9ae1564d --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionDeployCommand.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-deploy", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionDeployCommand extends RevisionSupport { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + try { + revision.deploy(); + printRevision(revision); + } catch (RevisionException e) { + // output error + System.err.println("ERROR: " + e.getMessage()); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionDoneCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionDoneCommand.java new file mode 100644 index 00000000..30de88a9 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionDoneCommand.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-done", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionDoneCommand extends ManagedApplicationRevisionCommand { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + + + session.put(ApplicationShell.APPLICATION_REVISION_KEY, null); + session.put(ApplicationShell.APPLICATION_CONFIG_KEY, null); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionInfoCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionInfoCommand.java new file mode 100644 index 00000000..8935565b --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionInfoCommand.java @@ -0,0 +1,138 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.util.Comparator; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +@Service +@Command(name = "app-revision-info", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionInfoCommand extends RevisionSupport { + + @Reference + EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Reference + EntaxyResourceService entaxyResourceService; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + + System.out.println(""); + // output main revision info + String data = "Application : ".concat(application.getName()).concat("\n") + .concat("Group : ").concat(version.getDescriptor().group).concat("\n") + .concat("Version : ").concat(version.getVersionNumber()).concat("\n") + .concat("Revision : ").concat(revision.getRevisionNumber() + "").concat("\n") + .concat("Status : ").concat(revision.getStatus().name()).concat("\n") + .concat("Revisionable : ") + .concat(revision.getItems().stream().filter(item -> item.isRevisionable()).count() > 0 ? "true" + : "false") + .concat("\n") + .concat("Editable : ") + .concat(revision.getItems().stream().filter(item -> item.isEditable()).count() > 0 ? "true" : "false"); + System.out.println(data); + + // output items + System.out.println("\n\tITEMS"); + ShellTableFixed itemsTable = new ShellTableFixed(); + itemsTable.column("Id"); + itemsTable.column("Type"); + itemsTable.column("Revisionable").alignCenter(); + itemsTable.column("Editable").alignCenter(); + + for (ApplicationItem item : revision.getItems().stream().sorted(new Comparator() { + + @Override + public int compare(ApplicationItem o1, ApplicationItem o2) { + return o1.getType().name().compareTo(o2.getType().name()); + } + }).collect(Collectors.toList())) { + + itemsTable.addRow().addContent(item.getId(), item.getType().name(), item.isRevisionable() ? "*" : "", + item.isEditable() ? "*" : ""); + + } + + itemsTable.print(System.out); + + // output requirements + ApplicationDescriptor applicationDescriptor = revision.getDescriptor(); + System.out.println("\n\tREQUIREMENTS"); + ShellTableFixed requirementsTable = new ShellTableFixed(); + requirementsTable.column("Id").colorProvider(ApplicationShell.normalColorProvider); + requirementsTable.column("Type").colorProvider(ApplicationShell.normalColorProvider); + requirementsTable.column("Scope").colorProvider(ApplicationShell.normalColorProvider); + requirementsTable.column("Status").colorProvider(ApplicationShell.requirementStatusColorProvider).alignCenter(); + + for (ApplicationRequirement req : applicationDescriptor.requirements) { + requirementsTable.addRow().addContent( + req.id, + req.type.name(), + req.scope.name(), + checkRequirement(req) ? "V" : "X"); + } + + requirementsTable.print(System.out); + + System.out.println(""); + } + + protected boolean checkRequirement(ApplicationRequirement requirement) { + switch (requirement.type) { + case OBJECT: + EntaxyRuntimeObject runtimeObject = entaxyRuntimeObjectService.getRuntimeObject(requirement.id); + return runtimeObject != null && !runtimeObject.isGhost(); + case RESOURCE: + EntaxyResource entaxyResource = entaxyResourceService.getResource(requirement.id); + return entaxyResource.exists(); + case BUNDLE: + case CONFIG: + // TODO implement + return true; + default: + return true; + } + } +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionInstallCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionInstallCommand.java new file mode 100644 index 00000000..12e1cdcc --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionInstallCommand.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-install", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionInstallCommand extends RevisionSupport { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + try { + revision.install(); + printRevision(revision); + } catch (RevisionException e) { + // output error + System.err.println("ERROR: " + e.getMessage()); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionListCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionListCommand.java new file mode 100644 index 00000000..e298186b --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionListCommand.java @@ -0,0 +1,73 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-list", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionListCommand extends ManagedApplicationVersionCommand { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version) { + + ShellTableFixed table = new ShellTableFixed(); + table.column("Number").alignCenter(); + table.column("Status"); + + List revisions = + version.getRevisions().stream().sorted(new Comparator() { + + @Override + public int compare(EntaxyApplicationRevision o1, EntaxyApplicationRevision o2) { + if (o1.getRevisionNumber() > o2.getRevisionNumber()) + return 1; + return -1; + } + }) + .collect(Collectors.toList()); + + for (EntaxyApplicationRevision revision : revisions) { + table.addRow().addContent(revision.getRevisionNumber(), revision.getStatus()); + } + + // output + table.print(System.out); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionSupport.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionSupport.java new file mode 100644 index 00000000..aa1436c9 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionSupport.java @@ -0,0 +1,66 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Option; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; + +public abstract class RevisionSupport extends ManagedApplicationVersionCommand { + + @Option(name = "-r", aliases = {"--revision"}) + public String revisionNumber; + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version) { + int revisionNum = version.getLastRevision().getRevisionNumber(); + if (CommonUtils.isValid(revisionNumber)) + try { + revisionNum = Integer.parseInt(revisionNumber); + } catch (Exception e) { + + // print error + System.err.println("Invalid revision number: " + revisionNumber); + return; + } + + EntaxyApplicationRevision revision = version.getRevision(revisionNum); + doExecute(application, version, revision); + } + + protected void printRevision(EntaxyApplicationRevision revision) { + // output + System.out.println( + String.format("Revision: %d; status: %s", revision.getRevisionNumber(), revision.getStatus().name())); + } + + protected abstract void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision); + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionUninstallCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionUninstallCommand.java new file mode 100644 index 00000000..a1305e04 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/application/RevisionUninstallCommand.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.application; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "app-revision-uninstall", scope = ApplicationShell.COMMAND_SCOPE) +public class RevisionUninstallCommand extends RevisionSupport { + + @Override + protected void doExecute(EntaxyApplication application, EntaxyApplicationVersion version, + EntaxyApplicationRevision revision) { + try { + revision.uninstall(); + printRevision(revision); + } catch (RevisionException e) { + // output error + System.err.println("ERROR: " + e.getMessage()); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ApplicationCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ApplicationCompleter.java new file mode 100644 index 00000000..17760308 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ApplicationCompleter.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.ApplicationManager; + +@Service +public class ApplicationCompleter implements Completer { + + @Reference + ApplicationManager applicationManager; + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + candidates.addAll( + applicationManager.getApplications().stream() + .filter(app -> app.getStorage() != null) + .map(app -> app.getName().concat("@") + .concat(app.getStorage().getName())) + .collect(Collectors.toList())); + return 0; + } + + + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ApplicationVersionCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ApplicationVersionCompleter.java new file mode 100644 index 00000000..a3ba84a1 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ApplicationVersionCompleter.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +public class ApplicationVersionCompleter implements Completer { + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + EntaxyApplication app = (EntaxyApplication) session.get(ApplicationShell.APPLICATION_KEY); + if (app == null) + return 0; + candidates.addAll(app.getVersions().stream().map(v -> v.getVersionNumber()).collect(Collectors.toList())); + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ConfigCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ConfigCompleter.java new file mode 100644 index 00000000..5894eef1 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ConfigCompleter.java @@ -0,0 +1,57 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.EntaxyApplication.ITEM_TYPE; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +public class ConfigCompleter implements Completer { + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + EntaxyApplicationRevision revision = + (EntaxyApplicationRevision) session.get(ApplicationShell.APPLICATION_REVISION_KEY); + if (revision == null) + return 0; + + candidates.addAll( + revision.getItems().stream().filter(item -> item.getType().equals(ITEM_TYPE.CONFIG)) + .map(item -> item.getId()).collect(Collectors.toList())); + + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/EntaxyRuntimeObjectCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/EntaxyRuntimeObjectCompleter.java new file mode 100644 index 00000000..b660ec54 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/EntaxyRuntimeObjectCompleter.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +@Service +public class EntaxyRuntimeObjectCompleter implements Completer { + + @Reference + EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + candidates.addAll(entaxyRuntimeObjectService.getObjects().stream() + .filter(obj -> !obj.isGhost()) + .map(obj -> obj.getObjectFullId()) + .collect(Collectors.toList())); + + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectCompleter.java new file mode 100644 index 00000000..e8709b26 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectCompleter.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.ApplicationManager; + +@Service +public class ProjectCompleter implements Completer { + + @Reference + ApplicationManager applicationManager; + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + candidates.addAll( + applicationManager.getProjects().stream() + .filter(app -> app.getStorage() != null) + .map(app -> app.getName().concat("@") + .concat(app.getStorage().getName())) + .collect(Collectors.toList())); + return 0; + } + + + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectItemCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectItemCompleter.java new file mode 100644 index 00000000..23b7744d --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectItemCompleter.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +public class ProjectItemCompleter implements Completer { + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + EntaxyApplicationProjectVersion version = (EntaxyApplicationProjectVersion) session.get(ApplicationShell.PROJECT_VERSION_KEY); + if (version == null) + return 0; + + candidates.addAll(version.getItems().stream().map(item -> item.getId()).collect(Collectors.toList())); + + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectVersionCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectVersionCompleter.java new file mode 100644 index 00000000..e275b93f --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/ProjectVersionCompleter.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +public class ProjectVersionCompleter implements Completer { + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + EntaxyApplicationProject app = (EntaxyApplicationProject) session.get(ApplicationShell.PROJECT_KEY); + if (app == null) + return 0; + candidates.addAll(app.getVersions().stream().map(v -> v.getVersionNumber()).collect(Collectors.toList())); + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/RepositoryNameCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/RepositoryNameCompleter.java new file mode 100644 index 00000000..aedb1f6b --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/RepositoryNameCompleter.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.core.artifact.service.ArtifactService; + +@Service +public class RepositoryNameCompleter implements Completer { + + @Reference + ArtifactService artifactService; + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + candidates.addAll( + artifactService.getRepositories().stream().map(repo -> repo.getName()).collect(Collectors.toList())); + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/RevisionCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/RevisionCompleter.java new file mode 100644 index 00000000..f73a50aa --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/RevisionCompleter.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +public class RevisionCompleter implements Completer { + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + EntaxyApplicationVersion version = + (EntaxyApplicationVersion) session.get(ApplicationShell.APPLICATION_VERSION_KEY); + if (version == null) + return 0; + + candidates.addAll( + version.getRevisions().stream().map(rev -> rev.getRevisionNumber() + "").collect(Collectors.toList())); + + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/StorageCompleter.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/StorageCompleter.java new file mode 100644 index 00000000..6c76d47a --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/completers/StorageCompleter.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.completers; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.ApplicationManager; + +@Service +public class StorageCompleter implements Completer { + + @Reference + ApplicationManager applicationManager; + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + candidates.addAll( + applicationManager.getAllStorages().stream().map(s -> s.getName()).collect(Collectors.toList())); + return 0; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemAddCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemAddCommand.java new file mode 100644 index 00000000..8df50c84 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemAddCommand.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-item-add", scope = ApplicationShell.COMMAND_SCOPE) +public class ItemAddCommand extends ItemAwareCommand { + + @Override + protected void processItem(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version, + ApplicationProjectItem item) + throws ProjectException { + version.addItem(item); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemAwareCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemAwareCommand.java new file mode 100644 index 00000000..76f018c5 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemAwareCommand.java @@ -0,0 +1,67 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import java.util.Optional; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Completion; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.shell.completers.ProjectItemCompleter; + +public abstract class ItemAwareCommand extends ManagedVersionCommand { + + @Argument(index = 0, required = true) + @Completion(value = ProjectItemCompleter.class) + String itemId; + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + + Optional optItem = + version.getItems().stream().filter(item -> item.getId().equals(itemId)).findFirst(); + if (!optItem.isPresent()) { + // print error + System.err.println(String.format("Item [%s] not found in managed version", itemId)); + return; + } + try { + processItem(application, version, optItem.get()); + } catch (ProjectException e) { + // output exception + e.printStackTrace(); + } + + } + + protected abstract void processItem(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version, + ApplicationProjectItem item) throws ProjectException; + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemIgnoreCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemIgnoreCommand.java new file mode 100644 index 00000000..0b046a39 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemIgnoreCommand.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-item-ignore", scope = ApplicationShell.COMMAND_SCOPE) +public class ItemIgnoreCommand extends ItemAwareCommand { + + @Override + protected void processItem(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version, + ApplicationProjectItem item) + throws ProjectException { + version.ignoreItem(item); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemRemoveCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemRemoveCommand.java new file mode 100644 index 00000000..787ebcbe --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ItemRemoveCommand.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-item-remove", scope = ApplicationShell.COMMAND_SCOPE) +public class ItemRemoveCommand extends ItemAwareCommand { + + @Override + protected void processItem(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version, + ApplicationProjectItem item) + throws ProjectException { + version.removeItem(item); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ManagedProjectCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ManagedProjectCommand.java new file mode 100644 index 00000000..93e72f84 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ManagedProjectCommand.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +public abstract class ManagedProjectCommand extends ApplicationManagerCommandSupport { + + @Override + public Object execute() throws Exception { + if (session.get(ApplicationShell.PROJECT_KEY) == null) { + // print error + System.err.println("No application is being managed"); + return null; + } + EntaxyApplicationProject app = (EntaxyApplicationProject) session.get(ApplicationShell.PROJECT_KEY); + doExecute(app); + return null; + } + + protected abstract void doExecute(EntaxyApplicationProject application); + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ManagedVersionCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ManagedVersionCommand.java new file mode 100644 index 00000000..d032736c --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ManagedVersionCommand.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +public abstract class ManagedVersionCommand extends ManagedProjectCommand { + + @Override + protected void doExecute(EntaxyApplicationProject application) { + EntaxyApplicationProjectVersion version = (EntaxyApplicationProjectVersion) session.get(ApplicationShell.PROJECT_VERSION_KEY); + if (version == null) { + // print error + System.err.println("No version is being managed"); + return; + } + doExecute(application, version); + } + + protected abstract void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version); +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCancelCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCancelCommand.java new file mode 100644 index 00000000..b9d452e7 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCancelCommand.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-cancel", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectCancelCommand extends ManagedProjectCommand { + + @Option(name = "-f", aliases = {"--force-version-cancel"}) + boolean forceVersionCancel = true; + + @Override + protected void doExecute(EntaxyApplicationProject application) { + session.put(ApplicationShell.PROJECT_KEY, null); + session.put(ApplicationShell.PROJECT_VERSION_KEY, null); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCommitCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCommitCommand.java new file mode 100644 index 00000000..196ee972 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCommitCommand.java @@ -0,0 +1,63 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-commit", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectCommitCommand extends ManagedProjectCommand { + + @Option(name = "-f", aliases = {"--force-version-commit"}) + boolean forceVersionCommit = true; + + @Option(name = "-s", aliases = {"--stop-managing"}) + boolean stopManaging = true; + + @Override + protected void doExecute(EntaxyApplicationProject application) { + application.save(); + EntaxyApplicationProjectVersion version = + (EntaxyApplicationProjectVersion) session.get(ApplicationShell.PROJECT_VERSION_KEY); + if (version != null) { + if (forceVersionCommit) + version.save(); + else + version.disgard(); + } + if (stopManaging) { + session.put(ApplicationShell.PROJECT_KEY, null); + session.put(ApplicationShell.PROJECT_VERSION_KEY, null); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCreateCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCreateCommand.java new file mode 100644 index 00000000..48e65f46 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCreateCommand.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.StorageAwareCommand; + +@Service +@Command(name = "project-create", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectCreateCommand extends StorageAwareCommand { + + @Option(name = "-v", aliases = {"--version"}, description = "Initial version for new application") + String initialVersion = "1.0.0"; + + @Argument(name = "applicationName", required = true, index = 1) + String applicationName; + + @Override + protected void doExecute() { + try { + EntaxyApplicationProject app = applicationManager.createProject(storage, applicationName, initialVersion); + if (app != null) { + // output + System.out.println("Created successfully"); + } + } catch (Exception e) { + // output to console + e.printStackTrace(); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCurrentCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCurrentCommand.java new file mode 100644 index 00000000..df817a1a --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectCurrentCommand.java @@ -0,0 +1,73 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.Session; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-current", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectCurrentCommand implements Action { + + @Reference + Session session; + + @Override + public Object execute() throws Exception { + if (session.get(ApplicationShell.PROJECT_KEY) == null) { + // output + System.out.println("No application is being managed"); + return null; + } + + String application = ""; + String storage = "unknown"; + String version = "none"; + + EntaxyApplicationProject app = (EntaxyApplicationProject) session.get(ApplicationShell.PROJECT_KEY); + application = app.getName(); + storage = app.getStorage().getName(); + + EntaxyApplicationProjectVersion vers = (EntaxyApplicationProjectVersion) session.get(ApplicationShell.PROJECT_VERSION_KEY); + if (vers != null) + version = vers.getVersionNumber(); + + // output + + System.out.println( + String.format("Application: [%s]\nStorage: [%s]\nVersion: [%s]", application, storage, version)); + + return null; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectListCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectListCommand.java new file mode 100644 index 00000000..d3128e0d --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectListCommand.java @@ -0,0 +1,90 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-list", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectListCommand extends ApplicationManagerCommandSupport { + + @Override + public Object execute() throws Exception { + ShellTableFixed table = new ShellTableFixed(); + table.column("Name"); + table.column("Storage"); + table.column("Versions"); + + List apps = applicationManager.getProjects(); + Collections.sort(apps, new Comparator() { + + @Override + public int compare(EntaxyApplicationProject o1, EntaxyApplicationProject o2) { + String storage1 = o1.getStorage().getName(); + String storage2 = o2.getStorage().getName(); + if (!storage1.equals(storage2)) + return storage1.compareTo(storage2); + + return o1.getName().compareTo(o2.getName()); + } + + }); + + for (EntaxyApplicationProject app : apps) { + List versions = app.getVersions(); + Collections.sort(versions, new Comparator() { + + @Override + public int compare(EntaxyApplicationProjectVersion o1, EntaxyApplicationProjectVersion o2) { + return o1.compareTo(o2); + } + + }); + String versionsValue = versions.stream().map(v -> v.getVersionNumber()).collect(Collectors.joining("\n")); + + table.addRow().addContent(app.getName(), app.getStorage() == null ? "" : app.getStorage().getName(), + versionsValue); + } + + // print output + table.print(System.out); + + return null; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectManageCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectManageCommand.java new file mode 100644 index 00000000..70e7b337 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectManageCommand.java @@ -0,0 +1,116 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationManagerCommandSupport; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.completers.ProjectCompleter; + +@Service +@Command(name = "project-manage", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectManageCommand extends ApplicationManagerCommandSupport { + + @Argument + @Completion(value = ProjectCompleter.class) + String application; + + @Option(name = "-f", aliases = {"--force-cancel"}) + boolean forceCancel = false; + + @Override + public Object execute() throws Exception { + if (session.get(ApplicationShell.PROJECT_KEY) != null) { + if (forceCancel) { + try { + EntaxyApplicationProjectVersion version = + (EntaxyApplicationProjectVersion) session.get(ApplicationShell.PROJECT_VERSION_KEY); + if (version != null) + version.disgard(); + } catch (Exception ignore) { + + } + try { + EntaxyApplicationProject application = + (EntaxyApplicationProject) session.get(ApplicationShell.PROJECT_KEY); + if (application != null) + application.disgard(); + } catch (Exception ignore) { + + } + session.put(ApplicationShell.PROJECT_KEY, null); + session.put(ApplicationShell.PROJECT_VERSION_KEY, null); + } else { + // print error + System.err.println("Other application is being managed, please commit or cancel"); + return null; + } + } + + String[] data = application.split("@"); + + if (data.length < 2) { + // print error + System.err.println("Incorrect application specified"); + return null; + } + + String storageName = data[1]; + ApplicationStorage storage = applicationManager.getStorage(storageName); + if (storage == null) { + // print error + System.err.println("Incorrect storage specified: [" + storageName + "]"); + return null; + } + + if (!storage.isEnabled()) { + // print error + System.err.println("Storage is disabled: [" + storageName + "]"); + return null; + } + + String appName = data[0]; + EntaxyApplicationProject app = storage.getProject(appName); + if (app == null) { + // print error + System.err.println(String.format("Application [%s] not found in storage [%s]", appName, storageName)); + return null; + } + + session.put(ApplicationShell.PROJECT_KEY, app); + + return null; + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectRemoveCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectRemoveCommand.java new file mode 100644 index 00000000..9e81a5ed --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/ProjectRemoveCommand.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.exceptions.ProjectNotFoundException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.StorageAwareCommand; + +@Service +@Command(name = "project-remove", scope = ApplicationShell.COMMAND_SCOPE) +public class ProjectRemoveCommand extends StorageAwareCommand { + + @Argument(name = "projectName", required = true, index = 1) + String projectName; + + @Override + protected void doExecute() { + try { + EntaxyApplicationProject project = applicationStorage.getProject(projectName); + if (project != null) { + applicationStorage.removeProject(project); + System.out.println("Removed successfully"); + } else { + throw new ProjectNotFoundException(projectName); + } + } catch (Exception e) { + // output error + System.err.println("ERROR: " + e.getMessage()); + e.printStackTrace(); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionAddObject.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionAddObject.java new file mode 100644 index 00000000..099528b5 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionAddObject.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.completers.EntaxyRuntimeObjectCompleter; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +@Service +@Command(name = "project-version-add-object", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionAddObject extends ManagedVersionCommand { + + @Argument(required = true) + @Completion(value = EntaxyRuntimeObjectCompleter.class) + String objectId; + + @Reference + EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + + ApplicationProjectItem item = version.addObject(entaxyRuntimeObjectService.getRuntimeObject(objectId)); + if (item != null) + // print output + System.out.println("Item is added"); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionBuildCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionBuildCommand.java new file mode 100644 index 00000000..92344876 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionBuildCommand.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import java.net.URL; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-version-build", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionBuildCommand extends ManagedVersionCommand { + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + try { + URL result = version.build(); + // print output + System.out.println("Result URL: ".concat(result == null ? "" : result.toString())); + } catch (ProjectVersionException e) { + // print error + System.err.println("ERROR: " + e.getMessage()); + e.printStackTrace(System.err); + } + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionBuildInfoCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionBuildInfoCommand.java new file mode 100644 index 00000000..465078bc --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionBuildInfoCommand.java @@ -0,0 +1,171 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.support.ansi.SimpleAnsi; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationContentItem; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationRequirement; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +@Service +@Command(name = "project-version-build-info", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionBuildInfoCommand extends ManagedVersionCommand { + + @Reference + EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Reference + EntaxyResourceService entaxyResourceService; + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + + if (!version.isBuildAvailable()) { + // print output + System.out.println("Build is not available"); + return; + } + + ApplicationDescriptor applicationDescriptor = version.getBuildInfo(); + + // output main data + String mainData = "\n" + .concat("Application : ").concat(applicationDescriptor.name).concat("\n") + .concat("Group : ").concat(applicationDescriptor.group).concat("\n") + .concat("Version : ").concat(applicationDescriptor.version).concat("\n") + .concat("Build by : ").concat(CommonUtils.getValid(applicationDescriptor.buildBy, "")).concat("\n") + .concat("Built on : ").concat(applicationDescriptor.buildOn).concat("\n") + .concat("Maven : ").concat(applicationDescriptor.mavenUrl).concat("\n") + .concat("Asset : ").concat(applicationDescriptor.mavenAsset).concat("\n"); + System.out.println(mainData); + + // output features location info + System.out.println(SimpleAnsi.RESET + SimpleAnsi.INTENSITY_NORMAL + "\n\t--- FEATURE REPO:"); + if (applicationDescriptor.features == null) { + System.out.println(":: NOT FOUND"); + } else { + String featuresData = + (" INTERNAL : ").concat(applicationDescriptor.features.internalLocation).concat("\n") + .concat(" ").concat("MAVEN : ").concat(applicationDescriptor.features.mavenLocation) + .concat("\n") + .concat(" ").concat("TARGET : ") + .concat(applicationDescriptor.features.getFullTargetLocation()); + System.out.println(featuresData); + + } + + // output items + System.out.println("\n\t--- ITEMS:"); + ShellTableFixed itemsTable = new ShellTableFixed(); + itemsTable.column("Id"); + itemsTable.column("Type"); + itemsTable.column("Component"); + + for (ApplicationContentItem item : applicationDescriptor.items) { + itemsTable.addRow().addContent(item.id, item.type.name(), item.componentId); + } + + itemsTable.print(System.out); + + // output requirements + System.out.println("\n\t--- REQUIREMENTS:"); + ShellTableFixed requirementsTable = new ShellTableFixed(); + requirementsTable.column("Id").colorProvider(ApplicationShell.normalColorProvider); + requirementsTable.column("Type").colorProvider(ApplicationShell.normalColorProvider); + requirementsTable.column("Scope").colorProvider(ApplicationShell.normalColorProvider); + requirementsTable.column("Status").colorProvider(ApplicationShell.requirementStatusColorProvider).alignCenter(); + + for (ApplicationRequirement req : applicationDescriptor.requirements) { + requirementsTable.addRow().addContent( + req.id, + req.type.name(), + req.scope.name(), + checkRequirement(req) ? "V" : "X"); + } + + requirementsTable.print(System.out); + + // output components + System.out.println(SimpleAnsi.RESET + SimpleAnsi.INTENSITY_NORMAL + "\n\t--- COMPONENTS:"); +/* ShellTableFixed componentsTable = new ShellTableFixed(); +componentsTable.column("Id"); +componentsTable.column("Type"); +componentsTable.column("Priority"); +componentsTable.column("Internal location"); +componentsTable.column("Maven location"); +*/ + for (ApplicationComponent component : applicationDescriptor.components) { +/* componentsTable.addRow().addContent( + component.id, + component.type.name(), + component.priority, + component.internalLocation, + component.mavenLocation); +*/ + String componentData = component.id.concat("\n") + .concat("\t").concat("TYPE : ").concat(component.type.name()).concat("\n") + .concat("\t").concat("PRIORITY : ").concat(component.priority + "").concat("\n") + .concat("\t").concat("INTERNAL : ").concat(component.internalLocation).concat("\n") + .concat("\t").concat("MAVEN : ").concat(component.mavenLocation).concat("\n") + .concat("\t").concat("TARGET : ").concat(component.getFullTargetLocation()); + System.out.println(componentData); + } + // componentsTable.print(System.out); + + } + + protected boolean checkRequirement(ApplicationRequirement requirement) { + switch (requirement.type) { + case OBJECT: + EntaxyRuntimeObject runtimeObject = entaxyRuntimeObjectService.getRuntimeObject(requirement.id); + return runtimeObject != null && !runtimeObject.isGhost(); + case RESOURCE: + EntaxyResource entaxyResource = entaxyResourceService.getResource(requirement.id); + return entaxyResource.exists(); + case BUNDLE: + case CONFIG: + // TODO implement + return true; + default: + return true; + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCancelCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCancelCommand.java new file mode 100644 index 00000000..c77bf6b1 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCancelCommand.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-version-cancel", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionCancelCommand extends ManagedVersionCommand { + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + session.put(ApplicationShell.PROJECT_VERSION_KEY, null); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCommitCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCommitCommand.java new file mode 100644 index 00000000..5bd12e7e --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCommitCommand.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-version-commit", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionCommitCommand extends ManagedVersionCommand { + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + version.save(); + session.put(ApplicationShell.PROJECT_VERSION_KEY, null); + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCreateCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCreateCommand.java new file mode 100644 index 00000000..f0dbcabc --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionCreateCommand.java @@ -0,0 +1,65 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.completers.ProjectVersionCompleter; + +@Service +@Command(name = "project-version-create", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionCreateCommand extends ManagedProjectCommand { + + @Option(name = "-f", aliases = {"--from-version"}) + @Completion(value = ProjectVersionCompleter.class) + String fromVersion; + + @Argument(required = true) + String versionNumber; + + @Override + protected void doExecute(EntaxyApplicationProject application) { + try { + if (CommonUtils.isValid(fromVersion)) + application.createVersion(versionNumber, fromVersion); + else + application.createVersion(versionNumber); + } catch (ProjectVersionException e) { + // print error + System.err.println("ERROR: " + e.getMessage()); + e.printStackTrace(System.err); + } + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionExportToFileCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionExportToFileCommand.java new file mode 100644 index 00000000..73aea5a5 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionExportToFileCommand.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-version-export-file", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionExportToFileCommand extends ManagedVersionCommand { + + @Argument(required = true) + String filePath; + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + try { + applicationManager.exportToFile(version, filePath); + // print output + System.out.println("Successfully exported"); + } catch (ProjectVersionException e) { + // print error + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(System.err); + } + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionExportToRepositoryCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionExportToRepositoryCommand.java new file mode 100644 index 00000000..7bc3baac --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionExportToRepositoryCommand.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.completers.RepositoryNameCompleter; + +@Service +@Command(name = "project-version-export-repository", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionExportToRepositoryCommand extends ManagedVersionCommand { + + @Argument(required = true) + @Completion(value = RepositoryNameCompleter.class) + String repositoryName; + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + try { + applicationManager.exportToRepository(version, repositoryName); + // print output + System.out.println("Successfully exported"); + } catch (ProjectVersionException e) { + // print error + System.err.println("Error: " + e.getMessage()); + e.printStackTrace(System.err); + } + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionItemListCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionItemListCommand.java new file mode 100644 index 00000000..fb64b561 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionItemListCommand.java @@ -0,0 +1,86 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import java.util.List; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.item.project.EntaxyBundleItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyConfigItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyObjectItem; +import ru.entaxy.platform.integration.applications.item.project.EntaxyResourceItem; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; + +@Service +@Command(name = "project-version-items", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionItemListCommand extends ManagedVersionCommand { + + @Override + protected void doExecute(EntaxyApplicationProject application, EntaxyApplicationProjectVersion version) { + List items = version.getItems(); + + ShellTableFixed table = new ShellTableFixed(); + table.column("Status").colorProvider(ApplicationShell.itemStatusColorProvider).alignCenter(); + table.column("Id").colorProvider(ApplicationShell.normalColorProvider); + table.column("Type").colorProvider(ApplicationShell.normalColorProvider); + table.column("Scope").colorProvider(ApplicationShell.normalColorProvider); + table.column("Required").colorProvider(ApplicationShell.normalColorProvider); + table.column("Ignored").colorProvider(ApplicationShell.normalColorProvider); + + for (ApplicationProjectItem item : items) { + String status = "+"; + if (item.isGhost()) + status = "?"; + if (item.isRequired()) + if (item.isIgnored()) + status = "-"; + else + status = "!"; + + String type = EntaxyConfigItem.class.isInstance(item) ? "config" + : EntaxyObjectItem.class.isInstance(item) ? "object" + : EntaxyBundleItem.class.isInstance(item) ? "bundle" + : EntaxyResourceItem.class.isInstance(item) ? "resource" : "unknown"; + + table.addRow().addContent(status, item.getId(), type, + item.getScope().name(), + item.isRequired() ? "*" : "", + item.isIgnored() ? "*" : ""); + + + } + + table.print(System.out); + + } + +} diff --git a/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionManageCommand.java b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionManageCommand.java new file mode 100644 index 00000000..61c73036 --- /dev/null +++ b/platform/integration/applications/application-shell/src/main/java/ru/entaxy/platform/integration/applications/shell/project/VersionManageCommand.java @@ -0,0 +1,64 @@ +/*- + * ~~~~~~licensing~~~~~~ + * application-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.shell.project; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Completion; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.shell.ApplicationShell; +import ru.entaxy.platform.integration.applications.shell.completers.ProjectVersionCompleter; + +@Service +@Command(name = "project-version-manage", scope = ApplicationShell.COMMAND_SCOPE) +public class VersionManageCommand extends ManagedProjectCommand { + + @Argument(required = true) + @Completion(value = ProjectVersionCompleter.class) + String versionNumber; + + @Override + protected void doExecute(EntaxyApplicationProject application) { + if (session.get(ApplicationShell.PROJECT_VERSION_KEY) != null) { + // print error + System.err.println("Another version is being managed, please cancel or commit"); + return; + } + + EntaxyApplicationProjectVersion version = application.getVersion(versionNumber); + if (version == null) { + System.err.println("Version not found"); + return; + } + + session.put(ApplicationShell.PROJECT_VERSION_KEY, version); + + } + +} diff --git a/platform/integration/applications/pom.xml b/platform/integration/applications/pom.xml new file mode 100644 index 00000000..8d86fdd5 --- /dev/null +++ b/platform/integration/applications/pom.xml @@ -0,0 +1,34 @@ + + + 4.0.0 + + ru.entaxy.platform + integration + 1.10.0 + + ru.entaxy.platform.integration + applications + pom + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS + + + + org.osgi + org.osgi.service.component.annotations + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + + + application-api + application-impl + resource-based-storage + application-shell + application-management + + diff --git a/platform/integration/applications/resource-based-storage/LICENSE.txt b/platform/integration/applications/resource-based-storage/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/integration/applications/resource-based-storage/pom.xml b/platform/integration/applications/resource-based-storage/pom.xml new file mode 100644 index 00000000..8f7d83e0 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/pom.xml @@ -0,0 +1,54 @@ + + 4.0.0 + + ru.entaxy.platform.integration + applications + 1.10.0 + + ru.entaxy.platform.integration.applications + resource-based-storage + bundle + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: RESOURCE BASED STORAGE + ENTAXY :: PLATFORM :: INTEGRATION :: APPLICATIONS :: RESOURCE BASED STORAGE + + + + ru.entaxy.platform.integration.applications.storage.resource + + + ru.entaxy.platform.integration.applications.storage.resource.impl, + ru.entaxy.platform.integration.applications.storage.resource.impl.application, + ru.entaxy.platform.integration.applications.storage.resource.impl.project, + ru.entaxy.platform.integration.applications.storage.resource.internal + + + + + + ru.entaxy.esb.platform.runtime.base.resources + resources-api + ${project.version} + + + ru.entaxy.platform.integration.applications + application-api + ${project.version} + + + ru.entaxy.platform.integration.applications + application-impl + ${project.version} + + + com.google.code.gson + gson + + + commons-io + commons-io + ${commons-io.version} + + + + + diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/ResourceBasedStorage.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/ResourceBasedStorage.java new file mode 100644 index 00000000..29012560 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/ResourceBasedStorage.java @@ -0,0 +1,210 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource; + +import java.util.List; +import java.util.stream.Collectors; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceMetadata; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationNotFoundException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectAlreadyExistsException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectNotFoundException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.storage.AbstractApplicationStorage; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; +import ru.entaxy.platform.integration.applications.storage.resource.impl.StorageComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.project.ProjectComponent; + +public class ResourceBasedStorage extends AbstractApplicationStorage { + + protected String resourceProvider; + protected String path; + + protected EntaxyResourceService entaxyResourceService; + + protected EntaxyResource rootResourceFolder; + protected EntaxyResourceMetadata rootResourceFolderMetadata; + protected EntaxyResourceMetadata.MetadataSection rootMetaStorageSection; + + protected String rootResourceFolderUrl; + + boolean isInited = false; + + protected StorageComponent storageComponent; + + protected ResourceContext rootResourceContext; + + protected interface RootMetaProps { + String PROP_ENABLED = "enabled"; + } + + public String getResourceProvider() { + return resourceProvider; + } + + public void setResourceProvider(String resourceProvider) { + this.resourceProvider = resourceProvider; + updateResourceFolderUrl(); + setInfo("provider", this.resourceProvider); + } + + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + updateResourceFolderUrl(); + setInfo("path", this.path); + } + + protected void updateResourceFolderUrl() { + this.rootResourceFolderUrl = + CommonUtils.getValid(resourceProvider, "").concat(":").concat(CommonUtils.getValid(path, "")); + } + + public void setEntaxyResourceService(EntaxyResourceService entaxyResourceService) { + this.entaxyResourceService = entaxyResourceService; + } + + public void init() { + rootResourceContext = new ResourceContext(); + rootResourceContext.setEntaxyResourceService(entaxyResourceService); + rootResourceContext.setRootResourceFolderUrl(rootResourceFolderUrl); + rootResourceContext.init(); + storageComponent = new StorageComponent(rootResourceContext, name); + storageComponent.init(); + isInited = true; + } + + @Override + public void setEnabled(boolean isEnabled) { + super.setEnabled(isEnabled); + if (!isInited) + return; + rootMetaStorageSection.getContent().remove(RootMetaProps.PROP_ENABLED); + rootMetaStorageSection.getContent().addProperty(RootMetaProps.PROP_ENABLED, isEnabled()); + rootResourceFolderMetadata.update(); + } + + protected String getApplicationUrl(String applicationName) { + return rootResourceFolderUrl.concat("/").concat(applicationName); + } + + protected boolean projectExists(String projectName) { + return storageComponent.projectExists(projectName); + } + + protected boolean applicationExists(String applicationName) { + return storageComponent.applicationExists(applicationName); + } + + /* ApplicationStorage implementation */ + + @Override + public String getType() { + return "resource"; + } + + @Override + public List getProjects() { + return storageComponent.getProjects().stream().map(cmp -> cmp.storage(this)) + .map(cmp -> (EntaxyApplicationProject) cmp).collect(Collectors.toList()); + } + + @Override + public void addProject(EntaxyApplicationProject project) throws ProjectException, StorageException { + if (projectExists(project.getName())) + throw new ProjectAlreadyExistsException(project.getName()); + storageComponent.addProject(project); + } + + @Override + public void removeProject(EntaxyApplicationProject project) + throws ProjectException, StorageException { + if (project == null) + throw new ProjectNotFoundException("Unknown"); + if (!projectExists(project.getName())) + throw new ProjectNotFoundException(project.getName()); + storageComponent.removeProject(project); + } + + @Override + public EntaxyApplicationProject createProject(String applicationName) + throws ProjectException, StorageException { + if (projectExists(applicationName)) + throw new ProjectAlreadyExistsException(applicationName); + return storageComponent.createProject(applicationName).storage(this); + } + + @Override + public EntaxyApplicationProject getProject(String applicationName) { + ProjectComponent comp = storageComponent.getProject(applicationName); + if (comp == null) + return null; + return comp.storage(this); + } + + @Override + public List getApplications() { + return storageComponent.getApplications().stream().map(cmp -> cmp.storage(this)) + .map(cmp -> (EntaxyApplication) cmp).collect(Collectors.toList()); + } + + @Override + public EntaxyApplication getApplication(String applicationName) { + ApplicationComponent comp = storageComponent.getApplication(applicationName); + if (comp == null) + return null; + return comp.storage(this); + } + + @Override + public void removeApplication(EntaxyApplication application) throws ApplicationException, StorageException { + if (application == null) + throw new ApplicationNotFoundException("unknown"); + if (!applicationExists(application.getName())) + throw new ApplicationNotFoundException(application.getName()); + storageComponent.removeApplication(application); + } + + @Override + public EntaxyApplication createApplication(ApplicationImportContent content) + throws ApplicationException, StorageException { + return storageComponent.createApplication(content); + } + + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/AbstractResourceComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/AbstractResourceComponent.java new file mode 100644 index 00000000..ca7beae1 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/AbstractResourceComponent.java @@ -0,0 +1,185 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceMetadata; +import ru.entaxy.platform.base.support.JSONUtils; + +public abstract class AbstractResourceComponent { + + private static final Logger log = LoggerFactory.getLogger(AbstractResourceComponent.class); + + protected static final Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + protected ResourceContext resourceContext; + + // protected EntaxyResourceService entaxyResourceService; + + // protected EntaxyResource rootResourceFolder; + protected EntaxyResourceMetadata rootResourceFolderMetadata; + + protected EntaxyResource rootResource; + + // protected String rootResourceFolderUrl; + protected String rootResourceUrl; + + protected boolean isInited = false; + + protected T dataObject; + + protected abstract Class getDataObjectClass(); + + protected abstract String getRootResourceName(); + + protected abstract T createDataObject(); + + /* + protected AbstractResourceComponent(EntaxyResourceService entaxyResourceService) { + super(); + setEntaxyResourceService(entaxyResourceService); + } + */ + + protected AbstractResourceComponent(ResourceContext resourceContext) { + super(); + this.resourceContext = resourceContext; + this.resourceContext.init(); + } + + + protected T loadDataObject(JsonObject jsonObject) { + return GSON.fromJson(jsonObject, getDataObjectClass()); + }; + + protected void initializeRootResource() throws Exception { + dataObject = createDataObject(); + updateRootResource(); + } + + protected void initializeDataObject() throws Exception { + try (InputStream is = rootResource.getInputStream()) { + String data = new String(is.readAllBytes()); + dataObject = GSON.fromJson(JSONUtils.getJsonRootObject(data), getDataObjectClass()); + } + } + + protected void updateRootResource() throws Exception { + JsonObject jsonObject = GSON.toJsonTree(dataObject).getAsJsonObject(); + String data = GSON.toJson(jsonObject); + try (ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes())) { + rootResource.save(bis); + } catch (Exception e) { + throw e; + } + } + + protected EntaxyResource getResource(String relPath) { + /* + String targetUrl = rootResourceFolderUrl; + if (rootResourceFolderUrl.charAt(rootResourceFolderUrl.length() - 1) != '/') + targetUrl = targetUrl.concat("/"); + if (relPath.charAt(0) == '/') + targetUrl = targetUrl.concat(relPath.substring(1)); + else + targetUrl = targetUrl.concat(relPath); + EntaxyResource result = entaxyResourceService.getResource(targetUrl); + return result; + */ + return resourceContext.getResource(relPath); + } + + public void init() { + + // rootResourceFolder = entaxyResourceService.getResource(rootResourceFolderUrl); + + // rootResource = entaxyResourceService + // .getResource(rootResourceFolder.getURL().concat("/").concat(getRootResourceName())); + rootResource = resourceContext.getResource(getRootResourceName()); + if (!rootResource.exists()) { + try { + initializeRootResource(); + } catch (Exception ignore) { + + } + } else { + try { + initializeDataObject(); + } catch (Exception e) { + log.error("Error reading data from [" + rootResource.getURL() + "]", e); + return; + } + } + + rootResourceFolderMetadata = resourceContext.getRootResourceFolder().getMetadata(true); + + isInited = true; + + } + + public ResourceContext getResourceContext() { + return resourceContext; + } + + public void save() { + + } + + public void delete() { + if (!isInited) + return; + resourceContext.getRootResourceFolder().delete(); + } + + /* + public void setEntaxyResourceService(EntaxyResourceService entaxyResourceService) { + this.entaxyResourceService = entaxyResourceService; + } + */ + + public String getRootResourceFolderUrl() { + return resourceContext.getRootResourceFolderUrl(); + } + + /* + public void setRootResourceFolderUrl(String rootResourceFolderUrl) { + this.rootResourceFolderUrl = rootResourceFolderUrl; + } + */ + + public abstract String getComponentKey(); + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/AbstractResourceComponentWithChildren.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/AbstractResourceComponentWithChildren.java new file mode 100644 index 00000000..63caccfc --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/AbstractResourceComponentWithChildren.java @@ -0,0 +1,109 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.List; + +public abstract class AbstractResourceComponentWithChildren> + extends AbstractResourceComponent { + + + final protected ComponentCache childrenCache = new ComponentCache<>(); + + final protected Object childrenCacheLock = new Object(); + + /* + protected AbstractResourceComponentWithChildren(EntaxyResourceService entaxyResourceService) { + super(entaxyResourceService); + } + */ + + protected AbstractResourceComponentWithChildren(ResourceContext resourceContext) { + super(resourceContext); + } + + @Override + public void init() { + super.init(); + initChildrenCache(); + } + + protected void initChildrenCache() { + synchronized (childrenCacheLock) { + for (String key : getChildrenKeyList()) { + try { + C component = loadChild(key); + if (component == null) + continue; + childrenCache.put(component); + } catch (Exception e) { + handleChildLoadException(key, e); + } + } + } + } + + protected C loadChild(String key) throws Exception { + C component = createChildComponent(key); + if (component == null) + return null; + component.init(); + return component; + } + + protected C createNewChild(String key) throws Exception { + C component = createChildComponent(key); + component.init(); + synchronized (childrenCacheLock) { + addChildKey(key); + updateRootResource(); + childrenCache.put(component); + } + return component; + } + + protected void removeChild(String key) throws Exception { + synchronized (childrenCacheLock) { + C component = childrenCache.get(key); + if (component == null) + return; + component.delete(); + childrenCache.remove(key); + removeChildKey(key); + updateRootResource(); + } + } + + protected abstract C createChildComponent(String key) throws Exception; + + protected abstract List getChildrenKeyList(); + + protected abstract void addChildKey(String key); + + protected abstract void removeChildKey(String key); + + protected abstract void handleChildLoadException(String key, Exception e); +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ApplicationStorageComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ApplicationStorageComponent.java new file mode 100644 index 00000000..db061a8d --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ApplicationStorageComponent.java @@ -0,0 +1,246 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportContent; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationCausedException; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationImportCausedException; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionAlreadyExists; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.impl.ExportImportHelper.ApplicationImporter; +import ru.entaxy.platform.integration.applications.impl.StorageApplicationContentAdapter; +import ru.entaxy.platform.integration.applications.impl.StorageImportAdapter; +import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationVersionComponent; + +public class ApplicationStorageComponent extends AbstractResourceComponent + implements StorageImportAdapter { + + private static final Logger LOG = LoggerFactory.getLogger(ApplicationStorageComponent.class); + + final protected Map applicationCache = new HashMap<>(); + + protected Object applicationCacheLock = new Object(); + + /* + public ApplicationStorageComponent(EntaxyResourceService entaxyResourceService, String parentRootUrl) { + super(entaxyResourceService); + this.rootResourceFolderUrl = parentRootUrl.concat("/").concat("applications"); + } + */ + + public ApplicationStorageComponent(ResourceContext parentResourceContext) { + super(parentResourceContext.subcontext("applications")); + } + + @Override + protected Class getDataObjectClass() { + return ApplicationStorageData.class; + } + + @Override + protected String getRootResourceName() { + return ".applications"; + } + + @Override + protected ApplicationStorageData createDataObject() { + return new ApplicationStorageData(); + } + + @Override + public String getComponentKey() { + return "applications"; + } + + @Override + public void init() { + super.init(); + initializeApplicationCache(); + } + + protected void initializeApplicationCache() { + synchronized (applicationCacheLock) { + if (dataObject.applications == null) + return; + for (String applicationName : dataObject.applications) { + ApplicationComponent comp = loadApplication(applicationName); + if (comp != null) + applicationCache.put(comp.getName(), comp); + } + } + } + + protected ApplicationComponent loadApplication(String applicationName) { + try { + ApplicationComponent component = + new ApplicationComponent(resourceContext, applicationName); + component.init(); + return component; + } catch (Exception e) { + LOG.error("Error loading application [" + applicationName + "]", e); + } + return null; + } + + public boolean applicationExists(String applicationName) { + return dataObject.hasApplication(applicationName); + } + + public List getApplications() { + return new ArrayList<>(applicationCache.values()); + } + + public ApplicationComponent getApplication(String applicationName) { + return applicationCache.get(applicationName); + } + + protected ApplicationComponent getOrCreateApplication(String applicationName) + throws ApplicationException, StorageException { + ApplicationComponent result = getApplication(applicationName); + if (result != null) + return result; + result = createApplication(applicationName); + return result; + } + + public void addApplication(EntaxyApplication application) throws ApplicationException, StorageException { + // TODO Auto-generated method stub + + } + + public void removeApplication(EntaxyApplication application) + throws ApplicationException, StorageException { + synchronized (applicationCacheLock) { + String applicationName = application.getName(); + ApplicationComponent comp = applicationCache.get(applicationName); + if (comp == null) + return; + comp.delete(); + applicationCache.remove(applicationName); + dataObject.removeApplication(applicationName); + try { + updateRootResource(); + } catch (Exception e) { + LOG.error("Error removing application [" + applicationName + "]", e); + } + } + } + + protected ApplicationComponent createApplication(String applicationName) + throws ApplicationException, StorageException { + try { + ApplicationComponent component = + new ApplicationComponent(resourceContext, applicationName); + component.init(); + synchronized (applicationCacheLock) { + dataObject.addApplication(applicationName); + updateRootResource(); + applicationCache.put(component.getName(), component); + } + return component; + } catch (Exception e) { + LOG.error("Error creating application [" + applicationName + "]", e); + } + return null; + } + + public ApplicationComponent createApplication(ApplicationImportContent importContent) + throws ApplicationException, StorageException { + + ApplicationImporter applicationImporter = new ApplicationImporter(this); + String applicationName = "unknown"; + try { + applicationImporter.executeImport(importContent); + return getApplication(applicationImporter.getApplicationDescriptor().name); + } catch (ApplicationException ae) { + throw ae; + } catch (StorageException se) { + throw se; + } catch (Exception e) { + throw new ApplicationImportCausedException(applicationName, e); + } + } + + // StorageImportAdapter implementation + + @Override + public void checkDescriptor(ApplicationDescriptor applicationDescriptor) + throws ApplicationException, StorageException { + String applicationName = applicationDescriptor.name; + String applicationVersion = applicationDescriptor.version; + ApplicationComponent appComponent = getApplication(applicationName); + if (appComponent == null) + return; + if (appComponent.hasVersion(applicationVersion)) + throw new ApplicationVersionAlreadyExists(applicationName, applicationVersion); + } + + @Override + public StorageApplicationContentAdapter getContentAdapter(String applicationName, + ApplicationDescriptor applicationDescriptor) throws ApplicationException, StorageException { + String applicationVersion = applicationDescriptor.version; + + ApplicationComponent applicationComponent = getOrCreateApplication(applicationName); + try { + if (applicationComponent.hasVersion(applicationVersion)) + throw new ApplicationVersionAlreadyExists(applicationName, applicationVersion); + ApplicationVersionComponent versionComponent = + applicationComponent.createVersion(applicationVersion); + versionComponent.setDescriptor(applicationDescriptor); + versionComponent.init(); + versionComponent.save(); + return versionComponent.adapt(); + } catch (ApplicationException | StorageException rethrow) { + throw rethrow; + } catch (Exception e) { + throw new ApplicationCausedException(applicationName, e); + } + + } + + @Override + public EntaxyApplicationVersion getVersion(String applicationName, String version) + throws ApplicationException, StorageException { + ApplicationComponent appComp = getApplication(applicationName); + if (appComp == null) + return null; + return appComp.getVersion(version); + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ApplicationStorageData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ApplicationStorageData.java new file mode 100644 index 00000000..17d36d2f --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ApplicationStorageData.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.ArrayList; +import java.util.List; + +public class ApplicationStorageData { + + List applications; + + public void addApplication(String applicationName) { + if (applications == null) + applications = new ArrayList<>(); + applications.add(applicationName); + } + + public void removeApplication(String applicationName) { + if (applications != null) + applications.remove(applicationName); + } + + public boolean hasApplication(String applicationName) { + if (applications == null) + return false; + return applications.contains(applicationName); + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ComponentCache.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ComponentCache.java new file mode 100644 index 00000000..1d53ae13 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ComponentCache.java @@ -0,0 +1,107 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class ComponentCache> implements Map { + + final protected Map cache = new HashMap<>(); + + synchronized public T put(T value) { + return cache.put(value.getComponentKey(), value); + } + + public boolean has(T value) { + return cache.containsKey(value.getComponentKey()); + } + + @Override + public int size() { + return cache.size(); + } + + @Override + public boolean isEmpty() { + return cache.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return cache.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return cache.containsValue(value); + } + + @Override + public T get(Object key) { + return cache.get(key); + } + + @Override + synchronized public T put(String key, T value) { + return cache.put(key, value); + } + + @Override + synchronized public T remove(Object key) { + return cache.remove(key); + } + + @Override + synchronized public void putAll(Map m) { + cache.putAll(m); + } + + @Override + synchronized public void clear() { + cache.clear(); + } + + @Override + public Set keySet() { + return cache.keySet(); + } + + @Override + public Collection values() { + return cache.values(); + } + + @Override + public Set> entrySet() { + return cache.entrySet(); + } + + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ProjectStorageComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ProjectStorageComponent.java new file mode 100644 index 00000000..a306e628 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ProjectStorageComponent.java @@ -0,0 +1,164 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.storage.resource.impl.project.ProjectComponent; + +public class ProjectStorageComponent extends AbstractResourceComponent { + + private static final Logger LOG = LoggerFactory.getLogger(ProjectStorageComponent.class); + + final protected Map projectCache = new HashMap<>(); + + protected Object projectCacheLock = new Object(); + + /* + public ProjectStorageComponent(EntaxyResourceService entaxyResourceService, String parentRootUrl) { + super(entaxyResourceService); + this.rootResourceFolderUrl = parentRootUrl.concat("/").concat("projects"); + } + */ + + public ProjectStorageComponent(ResourceContext parentResourceContext) { + super(parentResourceContext.subcontext("projects")); + } + + @Override + protected Class getDataObjectClass() { + return ProjectStorageData.class; + } + + @Override + protected String getRootResourceName() { + return ".projects"; + } + + @Override + protected ProjectStorageData createDataObject() { + return new ProjectStorageData(); + } + + @Override + public String getComponentKey() { + return "projects"; + } + + @Override + public void init() { + super.init(); + initializeProjectCache(); + } + + protected void initializeProjectCache() { + synchronized (projectCacheLock) { + if (dataObject.projects == null) + return; + for (String projectName : dataObject.projects) { + ProjectComponent comp = loadProject(projectName); + if (comp != null) + projectCache.put(comp.getName(), comp); + } + } + } + + protected ProjectComponent loadProject(String projectName) { + try { + ProjectComponent component = + new ProjectComponent(resourceContext, projectName); + component.init(); + return component; + } catch (Exception e) { + LOG.error("Error creating project [" + projectName + "]", e); + } + return null; + } + + public boolean projectExists(String projectName) { + return dataObject.hasProject(projectName); + } + + public List getProjects() { + return new ArrayList<>(projectCache.values()); + } + + public ProjectComponent getProject(String projectName) { + return projectCache.get(projectName); + } + + public void addProject(EntaxyApplicationProject project) throws ProjectException, StorageException { + // TODO Auto-generated method stub + + } + + public void removeProject(EntaxyApplicationProject project) + throws ProjectException, StorageException { + synchronized (projectCacheLock) { + String projectName = project.getName(); + ProjectComponent comp = projectCache.get(projectName); + if (comp == null) + return; + comp.delete(); + projectCache.remove(projectName); + dataObject.removeProject(projectName); + try { + updateRootResource(); + } catch (Exception e) { + LOG.error("Error removing project [" + projectName + "]", e); + } + } + } + + public ProjectComponent createProject(String projectName) + throws ProjectException, StorageException { + try { + ProjectComponent component = + new ProjectComponent(resourceContext, projectName); + component.init(); + synchronized (projectCacheLock) { + dataObject.addProject(component.getName()); + updateRootResource(); + projectCache.put(component.getName(), component); + } + return component; + } catch (Exception e) { + LOG.error("Error creating project [" + projectName + "]", e); + } + return null; + } + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ProjectStorageData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ProjectStorageData.java new file mode 100644 index 00000000..69e299e5 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ProjectStorageData.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.ArrayList; +import java.util.List; + +public class ProjectStorageData { + + List projects; + + public void addProject(String projectName) { + if (projects == null) + projects = new ArrayList<>(); + projects.add(projectName); + } + + public void removeProject(String projectName) { + if (projects != null) + projects.remove(projectName); + } + + public boolean hasProject(String projectName) { + if (projects == null) + return false; + return projects.contains(projectName); + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ResourceContext.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ResourceContext.java new file mode 100644 index 00000000..d9539605 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/ResourceContext.java @@ -0,0 +1,98 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceService; + +public class ResourceContext { + + protected EntaxyResourceService entaxyResourceService; + + protected EntaxyResource rootResourceFolder; + + protected String rootResourceFolderUrl; + + protected ResourceContext parent = null; + + public ResourceContext() { + super(); + } + + public ResourceContext(ResourceContext parent) { + super(); + this.parent = parent; + } + + public void init() { + EntaxyResourceService resourceService = getEntaxyResourceService(); + if (resourceService != null) + this.rootResourceFolder = resourceService.getResource(rootResourceFolderUrl); + } + + public EntaxyResourceService getEntaxyResourceService() { + if (entaxyResourceService != null) + return entaxyResourceService; + if (parent != null) + return parent.getEntaxyResourceService(); + return null; + } + + public void setEntaxyResourceService(EntaxyResourceService entaxyResourceService) { + this.entaxyResourceService = entaxyResourceService; + } + + public EntaxyResource getRootResourceFolder() { + return rootResourceFolder; + } + + public String getRootResourceFolderUrl() { + return rootResourceFolderUrl; + } + + public void setRootResourceFolderUrl(String rootResourceFolderUrl) { + this.rootResourceFolderUrl = rootResourceFolderUrl; + } + + public EntaxyResource getResource(String relPath) { + String targetUrl = rootResourceFolderUrl; + if (rootResourceFolderUrl.charAt(rootResourceFolderUrl.length() - 1) != '/') + targetUrl = targetUrl.concat("/"); + if (relPath.charAt(0) == '/') + targetUrl = targetUrl.concat(relPath.substring(1)); + else + targetUrl = targetUrl.concat(relPath); + EntaxyResource result = getEntaxyResourceService().getResource(targetUrl); + return result; + } + + public ResourceContext subcontext(String subPath) { + ResourceContext result = new ResourceContext(this); + result.setRootResourceFolderUrl(rootResourceFolderUrl.concat("/").concat(subPath)); + return result; + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/StorageComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/StorageComponent.java new file mode 100644 index 00000000..450b3850 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/StorageComponent.java @@ -0,0 +1,154 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportContent; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectException; +import ru.entaxy.platform.integration.applications.exceptions.StorageException; +import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.project.ProjectComponent; + +public class StorageComponent extends AbstractResourceComponent { + + private static final Logger log = LoggerFactory.getLogger(StorageComponent.class); + + String storageName; + + protected ProjectStorageComponent projectStorageComponent; + + protected ApplicationStorageComponent applicationStorageComponent; + + /* + public StorageComponent(EntaxyResourceService entaxyResourceService, String storageName, String rootFolderUrl) { + super(entaxyResourceService); + this.storageName = storageName; + this.rootResourceFolderUrl = rootFolderUrl; + projectStorageComponent = new ProjectStorageComponent(entaxyResourceService, rootResourceFolderUrl); + applicationStorageComponent = new ApplicationStorageComponent(entaxyResourceService, rootResourceFolderUrl); + } + */ + + public StorageComponent(ResourceContext resourceContext, String storageName) { + super(resourceContext); + this.storageName = storageName; + projectStorageComponent = new ProjectStorageComponent(resourceContext); + applicationStorageComponent = new ApplicationStorageComponent(resourceContext); + } + + @Override + public String getComponentKey() { + return storageName; + } + + @Override + public void init() { + super.init(); + projectStorageComponent.init(); + applicationStorageComponent.init(); + } + + @Override + protected Class getDataObjectClass() { + return StorageData.class; + } + + @Override + protected String getRootResourceName() { + return ".storage"; + } + + @Override + protected StorageData createDataObject() { + return new StorageData(storageName); + } + + public boolean applicationExists(String applicationName) { + return applicationStorageComponent.applicationExists(applicationName); + } + + public List getApplications() { + return applicationStorageComponent.getApplications(); + } + + public ApplicationComponent getApplication(String applicationName) { + return applicationStorageComponent.getApplication(applicationName); + } + + public void addApplication(EntaxyApplication application) throws ApplicationException, StorageException { + applicationStorageComponent.addApplication(application); + } + + public void removeApplication(EntaxyApplication application) + throws ApplicationException, StorageException { + applicationStorageComponent.removeApplication(application); + } + + public ApplicationComponent createApplication(String applicationName) + throws ApplicationException, StorageException { + return applicationStorageComponent.createApplication(applicationName); + } + + public ApplicationComponent createApplication(ApplicationImportContent importContent) + throws ApplicationException, StorageException { + return applicationStorageComponent.createApplication(importContent); + } + + public boolean projectExists(String projectName) { + return projectStorageComponent.projectExists(projectName); + } + + public List getProjects() { + return projectStorageComponent.getProjects(); + } + + public ProjectComponent getProject(String projectName) { + return projectStorageComponent.getProject(projectName); + } + + public void addProject(EntaxyApplicationProject project) throws ProjectException, StorageException { + projectStorageComponent.addProject(project); + } + + public void removeProject(EntaxyApplicationProject project) + throws ProjectException, StorageException { + projectStorageComponent.removeProject(project); + } + + public ProjectComponent createProject(String projectName) + throws ProjectException, StorageException { + return projectStorageComponent.createProject(projectName); + } + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/StorageData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/StorageData.java new file mode 100644 index 00000000..87a6e550 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/StorageData.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl; + +public class StorageData { + + boolean enabled = true; + String name; + + public StorageData(String name) { + this.name = name; + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationComponent.java new file mode 100644 index 00000000..4d989b70 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationComponent.java @@ -0,0 +1,173 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionAlreadyExists; +import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponentWithChildren; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class ApplicationComponent + extends AbstractResourceComponentWithChildren + implements EntaxyApplication { + + private static final Logger log = LoggerFactory.getLogger(ApplicationComponent.class); + + protected String applicationName; + + protected ApplicationStorage applicationStorage; + + /* + public ApplicationComponent(EntaxyResourceService resourceService, String applicationName, String parentRootUrl) { + super(resourceService); + setEntaxyResourceService(resourceService); + this.applicationName = applicationName; + this.rootResourceFolderUrl = parentRootUrl.concat("/").concat(applicationName); + } + */ + + public ApplicationComponent(ResourceContext resourceContext, String applicationName) { + super(resourceContext.subcontext(applicationName)); + this.applicationName = applicationName; + } + + @Override + protected Class getDataObjectClass() { + return ApplicationData.class; + } + + @Override + protected String getRootResourceName() { + return ".application"; + } + + @Override + protected ApplicationData createDataObject() { + return new ApplicationData(applicationName); + } + + @Override + public String getComponentKey() { + return applicationName; + } + + @Override + protected ApplicationVersionComponent createChildComponent(String key) throws Exception { + return new ApplicationVersionComponent(resourceContext, key, this); + } + + @Override + protected List getChildrenKeyList() { + if (dataObject.versions == null) + return Collections.emptyList(); + return new ArrayList<>(dataObject.versions.keySet()); + } + + @Override + protected void addChildKey(String key) { + dataObject.addVersion(key, Calendar.getInstance().getTimeInMillis() + ""); + } + + @Override + protected void removeChildKey(String key) { + dataObject.removeVersion(key); + } + + @Override + protected void handleChildLoadException(String key, Exception e) { + log.error("Error loading version [" + key + "]", e); + } + + public ApplicationVersionComponent createVersion(String versionNumber) throws Exception { + if (hasVersion(versionNumber)) + throw new ApplicationVersionAlreadyExists(applicationName, versionNumber); + ApplicationVersionComponent result = createChildComponent(versionNumber); + synchronized (childrenCacheLock) { + dataObject.addVersion(versionNumber); + updateRootResource(); + childrenCache.put(result); + } + return result; + } + + public ApplicationComponent storage(ApplicationStorage storage) { + this.applicationStorage = storage; + return this; + } + + public boolean hasVersion(String versionNumber) { + return dataObject.hasVersion(versionNumber); + } + + /* EntaxyApplication implementation */ + + @Override + public String getName() { + return applicationName; + } + + @Override + public ApplicationStorage getStorage() { + return this.applicationStorage; + } + + @Override + public List getVersions() { + return new ArrayList<>(childrenCache.values()); + } + + @Override + public EntaxyApplicationVersion getLatestVersion() { + return childrenCache.get(dataObject.getLatestVersion()); + } + + @Override + public EntaxyApplicationVersion getVersion(String version) { + return childrenCache.get(version); + } + + @Override + public void removeVersion(String version) { + try { + removeChild(version); + } catch (Exception e) { + log.error("Error removing version [" + version + "]", e); + } + } + + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationData.java new file mode 100644 index 00000000..2f032bc3 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationData.java @@ -0,0 +1,79 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.util.Calendar; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +public class ApplicationData { + String name; + + Map versions; + + public ApplicationData(String name) { + this.name = name; + } + + public boolean hasVersion(String versionNumber) { + return versions != null && versions.containsKey(versionNumber); + } + + public void addVersion(String version) { + addVersion(version, Calendar.getInstance().getTimeInMillis() + ""); + } + + public void addVersion(String version, String timestamp) { + if (versions == null) + versions = new HashMap<>(); + if (!versions.containsKey(version)) + versions.put(version, timestamp); + } + + public void removeVersion(String version) { + if (versions == null) + return; + versions.remove(version); + } + + public String getLatestVersion() { + Optional> latest = + versions.entrySet().stream().sorted(new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + // reverse order + return -1 * o1.getValue().compareTo(o2.getValue()); + } + }).findFirst(); + if (!latest.isPresent()) + return null; + return latest.get().getKey(); + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationVersionComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationVersionComponent.java new file mode 100644 index 00000000..7b0ba8d0 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationVersionComponent.java @@ -0,0 +1,282 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonElement; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.integration.applications.ApplicationContent; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.ApplicationResource; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionCausedException; +import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionException; +import ru.entaxy.platform.integration.applications.impl.StorageApplicationContentAdapter; +import ru.entaxy.platform.integration.applications.impl.StorageItemAdapter; +import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponentWithChildren; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class ApplicationVersionComponent + extends AbstractResourceComponentWithChildren + implements EntaxyApplicationVersion { + + private static final Logger log = LoggerFactory.getLogger(ApplicationVersionComponent.class); + + protected String versionNumber; + + protected ApplicationComponent applicationComponent; + + protected ResourceApplicationContent applicationContent; + + /* + public ApplicationVersionComponent(EntaxyResourceService resourceService, String versionNumber, + String parentRootUrl, ApplicationComponent applicationComponent) { + super(resourceService); + setEntaxyResourceService(resourceService); + this.versionNumber = versionNumber; + this.rootResourceFolderUrl = parentRootUrl.concat("/").concat(versionNumber); + this.applicationComponent = applicationComponent; + this.applicationContent = new ResourceApplicationContent(new ApplicationDescriptor()); + } + */ + + public ApplicationVersionComponent(ResourceContext parentResourceContext, String versionNumber, + ApplicationComponent applicationComponent) { + super(parentResourceContext.subcontext(versionNumber)); + this.versionNumber = versionNumber; + this.applicationComponent = applicationComponent; + this.applicationContent = ResourceApplicationContent.fromContext(this.resourceContext.subcontext(".content")); + } + + @Override + protected Class getDataObjectClass() { + return ApplicationVersionData.class; + } + + @Override + protected String getRootResourceName() { + return ".version"; + } + + @Override + protected ApplicationVersionData createDataObject() { + return new ApplicationVersionData(versionNumber); + } + + @Override + public String getComponentKey() { + return versionNumber; + } + + @Override + protected RevisionComponent createChildComponent(String key) throws Exception { + // return new RevisionComponent(entaxyResourceService, this, key); + return new RevisionComponent(resourceContext, this, key); + } + + @Override + protected List getChildrenKeyList() { + if (dataObject.revisions == null) + return Collections.emptyList(); + return dataObject.getRevisionKeys(); + } + + @Override + protected void addChildKey(String key) { + dataObject.addRevision(key, Calendar.getInstance().getTimeInMillis() + ""); + } + + @Override + protected void removeChildKey(String key) { + dataObject.removeRevision(key); + } + + @Override + protected void handleChildLoadException(String key, Exception e) { + log.error("Error loading revision [" + key + "]", e); + } + + @Override + public void save() { + if (applicationContent != null && applicationContent.getDescriptor() != null) { + JsonElement je = GSON.toJsonTree(applicationContent.getDescriptor()); + EntaxyResource descriptorResource = + applicationContent.getResourceContext().getResource(EntaxyApplication.DESCRIPTOR_NAME); + try (InputStream is = IOUtils.toInputStream(je.toString())) { + descriptorResource.save(is); + } catch (IOException e) { + log.error("Error saving descriptor to [" + descriptorResource.getURL() + "]", e); + } + } + super.save(); + } + + public void setDescriptor(ApplicationDescriptor applicationDescriptor) { + this.applicationContent.setDescriptor(applicationDescriptor); + } + + /* EntaxyApplicationVersion implementation */ + + @Override + public String getVersionNumber() { + return versionNumber; + } + + @Override + public List getRevisions() { + return childrenCache.values().stream().collect(Collectors.toList()); + } + + @Override + public EntaxyApplicationRevision getLastRevision() { + try { + return getRevision(dataObject.getLastRevision()); + } catch (Exception e) { + return null; + } + } + + @Override + public EntaxyApplicationRevision getRevision(int revision) { + return childrenCache.get(revision + ""); + } + + @Override + public EntaxyApplicationRevision createRevision(int fromRevision) + throws ApplicationVersionException { + RevisionComponent revisionComponent; + try { + int last = dataObject.getLastRevision(); + int revisionNumber = -1; + ApplicationContent source = null; + if (last == -1) { + revisionNumber = 0; + source = this; + + } else { + revisionNumber = last + 1; + int sourceRevision = fromRevision; + if (sourceRevision < 0) + sourceRevision = last; + RevisionComponent sourceComponent = childrenCache.get(sourceRevision + ""); + source = sourceComponent; + } + if (revisionNumber < 0) + throw new InstantiationException("Failed defining new revision number"); + + ApplicationDescriptor sourceDescriptor = source.getDescriptor(); + + revisionComponent = createChildComponent(revisionNumber + ""); + revisionComponent.init(); + revisionComponent.setDescriptor(sourceDescriptor); + revisionComponent.save(); + StorageApplicationContentAdapter adapted = revisionComponent.adapt(); + + ApplicationDescriptor revisionDescriptor = revisionComponent.getDescriptor(); + + // we copy only items, not resources + Map itemMap = + source.getItems().stream().collect(Collectors.toMap(item -> item.getLocation(), item -> item)); + List components = + new ArrayList<>(); + components.add(revisionDescriptor.getFeatures()); + components.addAll(revisionDescriptor.getComponents()); + + for (ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent component : components) { + if (!itemMap.containsKey(component.getInternalLocation())) + continue; + StorageItemAdapter itemAdapter = adapted.createItem(component); + try (InputStream is = itemMap.get(component.getInternalLocation()).getInputStream()) { + itemAdapter.write(is); + } + } + + revisionComponent.save(); + + // finalize + + synchronized (childrenCacheLock) { + dataObject.addRevision(revisionNumber, Calendar.getInstance().getTimeInMillis() + ""); + updateRootResource(); + childrenCache.put(revisionComponent); + } + + } catch (ApplicationVersionException rethrow) { + throw rethrow; + } catch (Exception e) { + throw new ApplicationVersionCausedException(applicationComponent.getName(), e, versionNumber); + } + + return revisionComponent; + } + + public StorageApplicationContentAdapter adapt() { + return applicationContent; + } + + protected ApplicationDescriptor createCopy(ApplicationDescriptor origin) throws Exception { + return GSON.fromJson(GSON.toJsonTree(origin, ApplicationDescriptor.class).deepCopy(), + ApplicationDescriptor.class); + } + + @Override + public EntaxyApplication getApplication() { + return applicationComponent; + } + + @Override + public ApplicationDescriptor getDescriptor() { + return applicationContent.getDescriptor(); + } + + @Override + public List getItems() { + return applicationContent.getItems(); + } + + @Override + public List getResources() { + return applicationContent.getResources(); + } + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationVersionData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationVersionData.java new file mode 100644 index 00000000..e50d685d --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ApplicationVersionData.java @@ -0,0 +1,94 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +public class ApplicationVersionData { + + String versionNumber; + + Map revisions; + + public ApplicationVersionData(String versionNumber) { + this.versionNumber = versionNumber; + } + + public void addRevision(int revisionNumber, String timestamp) { + addRevision(revisionNumber + "", timestamp); + } + + public void addRevision(String revisionNumber, String timestamp) { + if (revisions == null) + revisions = new HashMap<>(); + if (!revisions.containsKey(revisionNumber)) + revisions.put(revisionNumber, timestamp); + } + + public void removeRevision(int revisionNumber) { + removeRevision(revisionNumber + ""); + } + + public void removeRevision(String revisionNumber) { + if (revisions == null) + return; + revisions.remove(revisionNumber); + } + + public String getLatestRevision() { + Optional> latest = + revisions.entrySet().stream().sorted(new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + // reverse order + return -1 * o1.getValue().compareTo(o2.getValue()); + } + }).findFirst(); + if (!latest.isPresent()) + return null; + return latest.get().getKey(); + } + + public int getLastRevision() { + if (revisions == null || revisions.isEmpty()) + return -1; + return revisions.keySet().stream().mapToInt(v -> Integer.parseInt(v)).max().orElse(-1); + } + + public List getRevisionKeys() { + if (revisions == null) + return Collections.emptyList(); + return new ArrayList<>(revisions.keySet()); + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationContent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationContent.java new file mode 100644 index 00000000..0c572da2 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationContent.java @@ -0,0 +1,141 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.integration.applications.ApplicationResource; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.impl.StorageApplicationContentAdapter; +import ru.entaxy.platform.integration.applications.impl.StorageItemAdapter; +import ru.entaxy.platform.integration.applications.impl.application.ApplicationContentImpl; +import ru.entaxy.platform.integration.applications.impl.application.ApplicationItemImpl; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class ResourceApplicationContent extends ApplicationContentImpl implements StorageApplicationContentAdapter { + + private static final Logger LOG = LoggerFactory.getLogger(ResourceApplicationContent.class); + + private static Gson GSON = new GsonBuilder().setPrettyPrinting().create(); + + protected boolean isDirty = false; + + public static ResourceApplicationContent fromContext(ResourceContext resourceContext) { + + // check descriptor + ApplicationDescriptor applicationDescriptor = null; + EntaxyResource descriptorResource = resourceContext.getResource(EntaxyApplication.DESCRIPTOR_NAME); + if (descriptorResource.exists()) { + // try (InputStream is = descriptorResource.getInputStream()) { + try { + applicationDescriptor = GSON.fromJson(JSONUtils.getJsonRootObject(descriptorResource.getAsString()), + ApplicationDescriptor.class); + } catch (Exception ignore) { + LOG.error("Error reading descriptor [" + descriptorResource.getURL() + "]", ignore); + } + } + + if (applicationDescriptor == null) + return new ResourceApplicationContent(new ApplicationDescriptor(), resourceContext); + + ResourceApplicationContent result = new ResourceApplicationContent(applicationDescriptor, resourceContext); + try { + result.readDescriptor(); + } catch (Exception ignore) { + LOG.error("Error processing descriptor [" + descriptorResource.getURL() + "]", ignore); + return new ResourceApplicationContent(new ApplicationDescriptor(), resourceContext); + } + return result; + + + } + + protected ResourceContext resourceContext; + + public ResourceApplicationContent(ApplicationDescriptor descriptor, ResourceContext resourceContext) { + super(descriptor); + this.resourceContext = resourceContext; + } + + public void readDescriptor() throws Exception { + createItem(descriptor.features); + + for (ApplicationComponent comp : descriptor.getComponents()) + createItem(comp); + } + + public ResourceContext getResourceContext() { + return resourceContext; + } + + public boolean isDirty() { + return isDirty; + } + + protected void setDirty(boolean isDirty) { + this.isDirty = isDirty; + } + + public void save() { + setDirty(false); + } + + @Override + public StorageItemAdapter createItem(ApplicationComponent applicationComponent) throws Exception { + ResourceApplicationItem item = new ResourceApplicationItem(applicationComponent, resourceContext); + this.items.put(item.getLocation(), item); + setDirty(true); + return item; + } + + @Override + public ApplicationResource createResource(String location, InputStream inputStream) throws Exception { + ResourceApplicationResource res = new ResourceApplicationResource(resourceContext, location); + res.write(inputStream); + this.resources.put(location, res); + setDirty(true); + return res; + } + + @Override + public StorageItemAdapter getItemAdapter(String location) throws Exception { + ApplicationItemImpl item = this.items.get(location); + if (item instanceof ResourceApplicationItem) + return (ResourceApplicationItem) item; + return null; + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationItem.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationItem.java new file mode 100644 index 00000000..87ededcd --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationItem.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.io.InputStream; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.impl.StorageItemAdapter; +import ru.entaxy.platform.integration.applications.impl.application.ApplicationItemImpl; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class ResourceApplicationItem extends ApplicationItemImpl implements StorageItemAdapter { + + protected ResourceContext resourceContext; + + public ResourceApplicationItem(ApplicationComponent applicationComponent, ResourceContext resourceContext) { + super(applicationComponent, null); + this.resourceContext = resourceContext; + this.itemAdapter = this; + } + + @Override + public InputStream getInputStream() { + EntaxyResource resource = resourceContext.getResource(getLocation()); + return resource.getInputStream(); + } + + @Override + public void write(InputStream source) throws Exception { + EntaxyResource resource = resourceContext.getResource(getLocation()); + resource.save(source); + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationResource.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationResource.java new file mode 100644 index 00000000..11e75ae9 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/ResourceApplicationResource.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.io.InputStream; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.integration.applications.impl.application.ApplicationResourceImpl; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class ResourceApplicationResource extends ApplicationResourceImpl { + + protected ResourceContext resourceContext; + + protected String location; + + public ResourceApplicationResource(ResourceContext resourceContext, String location) { + super(); + this.resourceContext = resourceContext; + this.location = location; + } + + public void write(InputStream source) { + EntaxyResource resource = resourceContext.getResource(location); + resource.save(source); + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/RevisionComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/RevisionComponent.java new file mode 100644 index 00000000..895117c2 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/RevisionComponent.java @@ -0,0 +1,273 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonElement; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.integration.applications.ApplicationItem; +import ru.entaxy.platform.integration.applications.ApplicationResource; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationComponent; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.RevisionException; +import ru.entaxy.platform.integration.applications.impl.StorageApplicationContentAdapter; +import ru.entaxy.platform.integration.applications.impl.application.RevisionHelper; +import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class RevisionComponent extends AbstractResourceComponent + implements EntaxyApplicationRevision, RevisionHelper.RevisionHelperAdapter { + + private static final Logger LOG = LoggerFactory.getLogger(RevisionComponent.class); + + int revisionNumber; + + ApplicationVersionComponent versionComponent; + + ResourceApplicationContent applicationContent; + + final String CONTENT_RESOURCE_NAME = "version.content"; + + // REVISION_STATUS status = REVISION_STATUS.NEW; + + /* + public RevisionComponent(EntaxyResourceService entaxyResourceService, + ApplicationVersionComponent versionComponent, + String revisionNumber) { + super(entaxyResourceService); + this.revisionNumber = revisionNumber; + this.versionComponent = versionComponent; + this.rootResourceFolderUrl = + versionComponent.getRootResourceFolderUrl().concat("/").concat(this.revisionNumber); + applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, versionComponent.getVersionNumber()); + applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, revisionNumber); + + // buildComponent = new BuildComponent(entaxyResourceService, rootResourceFolderUrl); + } + */ + + public RevisionComponent(ResourceContext resourceContext, + ApplicationVersionComponent versionComponent, + int revisionNumber) { + super(resourceContext.subcontext(revisionNumber + "")); + this.revisionNumber = revisionNumber; + this.versionComponent = versionComponent; + applicationContent = ResourceApplicationContent.fromContext(this.resourceContext.subcontext(".content")); + } + + public RevisionComponent(ResourceContext resourceContext, + ApplicationVersionComponent versionComponent, + String revisionNumber) { + this(resourceContext, versionComponent, Integer.parseInt(revisionNumber)); + } + + @Override + protected Class getDataObjectClass() { + return RevisionData.class; + } + + @Override + protected String getRootResourceName() { + return ".revision"; + } + + @Override + protected RevisionData createDataObject() { + return new RevisionData(this.revisionNumber + ""); + } + + @Override + public String getComponentKey() { + return revisionNumber + ""; + } + + @Override + public void init() { + super.init(); + initContent(); + } + + + @Override + public void save() { + if (applicationContent != null) + if (applicationContent.isDirty) { + if (revisionNumber > 0) { + try { + RevisionHelper helper = new RevisionHelper(applicationContent, this); + helper.update(); + } catch (Exception e) { + LOG.error("ERROR saving revision", e); + return; + } + } + applicationContent.save(); + } + if (applicationContent != null && applicationContent.getDescriptor() != null) { + JsonElement je = GSON.toJsonTree(applicationContent.getDescriptor()); + EntaxyResource descriptorResource = + applicationContent.getResourceContext().getResource(EntaxyApplication.DESCRIPTOR_NAME); + try (InputStream is = IOUtils.toInputStream(je.toString())) { + descriptorResource.save(is); + } catch (IOException e) { + LOG.error("Error saving descriptor to [" + descriptorResource.getURL() + "]", e); + } + } + super.save(); + } + + protected void initContent() {} + + public StorageApplicationContentAdapter adapt() { + return applicationContent; + } + + public void setDescriptor(ApplicationDescriptor applicationDescriptor) { + try { + this.applicationContent.setDescriptor(createCopy(applicationDescriptor)); + } catch (Exception e) { + LOG.error("Error setting descriptor", e); + return; + } + } + + protected ApplicationDescriptor createCopy(ApplicationDescriptor origin) throws Exception { + return GSON.fromJson(GSON.toJsonTree(origin, ApplicationDescriptor.class).deepCopy(), + ApplicationDescriptor.class); + } + + protected void changeDescriptorComponentsVersion() { + List components = new ArrayList<>(); + components.add(applicationContent.getDescriptor().features); + + components.addAll(applicationContent.getDescriptor().getComponents()); + + List revisionableIds = applicationContent.getItems().stream().filter(item -> item.isRevisionable()) + .map(item -> item.getId()).collect(Collectors.toList()); + + for (ApplicationComponent component : components) { + + if (!revisionableIds.contains(component.id)) + continue; + + ArtifactCoordinates coordinates = ArtifactCoordinates.fromUrl(component.mavenLocation); + coordinates.qualifier(String.format("REV_%03d", revisionNumber)); + component.mavenLocation = coordinates.toMavenString(); + coordinates = ArtifactCoordinates.fromUrl(component.targetLocation); + coordinates.qualifier(String.format("REV_%03d", revisionNumber)); + component.targetLocation = coordinates.toMavenString(); + } + + } + + /* EntaxyApplicationRevision implementation */ + + + @Override + public int getRevisionNumber() { + return revisionNumber; + } + + @Override + public REVISION_STATUS getStatus() { + return dataObject.getStatus(); + } + + @Override + public void configure() throws RevisionException { + RevisionHelper helper = new RevisionHelper(applicationContent, this); + helper.configure(); + } + + @Override + public void deploy() throws RevisionException { + RevisionHelper helper = new RevisionHelper(applicationContent, this); + helper.deploy(); + } + + @Override + public void install() throws RevisionException { + RevisionHelper helper = new RevisionHelper(applicationContent, this); + helper.install(); + } + + @Override + public void uninstall() throws RevisionException { + RevisionHelper helper = new RevisionHelper(applicationContent, this); + helper.uninstall(); + } + + @Override + public ApplicationDescriptor getDescriptor() { + return applicationContent.getDescriptor(); + } + + @Override + public List getItems() { + return applicationContent.getItems(); + } + + @Override + public List getResources() { + return applicationContent.getResources(); + } + + // RevisionHelper.RevisionHelperAdapter implementation + + @Override + public REVISION_STATUS getCurrentStatus() { + return getStatus(); + } + + @Override + public void updateStatus(REVISION_STATUS newStatus) { + this.dataObject.status = newStatus; + try { + updateRootResource(); + } catch (Exception e) { + LOG.error("Error updating root resource", e); + } + } + + @Override + public void writeItem(String location, InputStream inputStream) throws Exception { + applicationContent.getItemAdapter(location).write(inputStream); + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/RevisionData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/RevisionData.java new file mode 100644 index 00000000..9e441bc9 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/application/RevisionData.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.application; + +import ru.entaxy.platform.integration.applications.EntaxyApplicationRevision.REVISION_STATUS; + +public class RevisionData { + + int revisionNumber; + + REVISION_STATUS status; + + public RevisionData(String revisionNumber) { + this.revisionNumber = Integer.parseInt(revisionNumber); + } + + public REVISION_STATUS getStatus() { + if (status == null) + return REVISION_STATUS.NEW; + return status; + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/BuildComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/BuildComponent.java new file mode 100644 index 00000000..df5f23d3 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/BuildComponent.java @@ -0,0 +1,154 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.project; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonElement; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class BuildComponent extends AbstractResourceComponent { + + private static final Logger LOG = LoggerFactory.getLogger(BuildComponent.class); + + protected EntaxyResource buildResource; + protected EntaxyResource descriptorResource; + + protected ApplicationDescriptor applicationDescriptor; + + /* + protected BuildComponent(EntaxyResourceService entaxyResourceService, String parentRootUrl) { + super(entaxyResourceService); + this.rootResourceFolderUrl = parentRootUrl.concat("/").concat(".build"); + } + */ + + protected BuildComponent(ResourceContext parentResourceContext) { + super(parentResourceContext.subcontext(".build")); + } + + @Override + protected Class getDataObjectClass() { + return BuildData.class; + } + + @Override + protected String getRootResourceName() { + return "build-info"; + } + + @Override + protected BuildData createDataObject() { + return new BuildData(); + } + + @Override + public String getComponentKey() { + return "build"; + } + + @Override + public void init() { + super.init(); + descriptorResource = getResource("descriptor.json"); + refresh(); + } + + public void refresh() { + if (CommonUtils.isValid(dataObject.name)) { + buildResource = getResource(dataObject.name); + if (descriptorResource.exists()) + applicationDescriptor = GSON.fromJson(JSONUtils.getJsonRootObject(descriptorResource.getAsString()), + ApplicationDescriptor.class); + } + } + + public void updateBuild(URL resultUrl, ApplicationDescriptor descriptor, ArtifactCoordinates coordinates) { + + if (isBuildAvailable()) + buildResource.delete(); + + dataObject.artifactId = coordinates.getArtifactId(); + dataObject.groupId = coordinates.getGroupId(); + dataObject.version = coordinates.getVersion(); + dataObject.name = coordinates.toAssetName(); + try { + updateRootResource(); + } catch (Exception e) { + LOG.error("Error updateing root resource", e); + return; + } + + applicationDescriptor = null; + + // (re)init resources + refresh(); + + JsonElement descriptorJe = GSON.toJsonTree(descriptor, ApplicationDescriptor.class); + String descriptorJson = descriptorJe.toString(); + try (InputStream is = new ByteArrayInputStream(descriptorJson.getBytes())) { + descriptorResource.save(is); + } catch (IOException e) { + LOG.error("Error saving resource [" + descriptorResource.getURL() + "]", e); + } + + try (InputStream is = resultUrl.openStream()) { + buildResource.save(is); + } catch (IOException e) { + LOG.error("Error saving resource [" + descriptorResource.getURL() + "]", e); + } + + applicationDescriptor = GSON.fromJson(descriptorJe, + ApplicationDescriptor.class); + + } + + public boolean isBuildAvailable() { + return buildResource != null && buildResource.exists(); + } + + public EntaxyResource getBuildResource() { + return buildResource; + } + + public ApplicationDescriptor getApplicationDescriptor() { + return applicationDescriptor; + } + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/BuildData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/BuildData.java new file mode 100644 index 00000000..526d3576 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/BuildData.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.project; + +public class BuildData { + + String groupId; + String artifactId; + String version; + + String name; + + String builtBy; + String builtOn; + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectComponent.java new file mode 100644 index 00000000..55b3f512 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectComponent.java @@ -0,0 +1,254 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.project; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Collections; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.integration.applications.ApplicationProjectContent.STANDARD_PROPERTIES; +import ru.entaxy.platform.integration.applications.ApplicationProjectInfo; +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.EntaxyApplication; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionCausedException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionNotFoundException; +import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponentWithChildren; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; + +public class ProjectComponent extends AbstractResourceComponentWithChildren + implements EntaxyApplicationProject { + + private static final Logger log = LoggerFactory.getLogger(ProjectComponent.class); + + protected static String extractProjectName(String projectFullName) { + int index = projectFullName.indexOf('/'); + if (index < 0) + return projectFullName; + return projectFullName.substring(index + 1); + } + + protected String projectName; + + protected String group; + + protected ApplicationStorage applicationStorage; + + /* + public ProjectComponent(EntaxyResourceService resourceService, String projectName, String parentRootUrl) { + super(resourceService); + setEntaxyResourceService(resourceService); + this.projectName = projectName; + this.rootResourceFolderUrl = parentRootUrl.concat("/").concat(projectName); + } + */ + + public ProjectComponent(ResourceContext parentResourceContext, String projectFullName) { + super(parentResourceContext.subcontext(extractProjectName(projectFullName))); + setProjectName(projectFullName); + } + + protected void setProjectName(String projectFullName) { + int index = projectFullName.indexOf('/'); + if (index > 0) { + this.projectName = projectFullName.substring(index + 1); + setGroup(projectFullName.substring(0, index)); + } else { + this.projectName = projectFullName; + setGroup(null); + } + } + + protected void setGroup(String group) { + if (!CommonUtils.isValid(group)) + this.group = EntaxyApplication.DEFAULT_GROUP_ID; + else + this.group = group; + } + + @Override + public void init() { + super.init(); + this.group = dataObject.group; + } + + @Override + protected Class getDataObjectClass() { + return ProjectData.class; + } + + @Override + protected String getRootResourceName() { + return ".project"; + } + + @Override + protected ProjectData createDataObject() { + return new ProjectData(projectName, group); + } + + @Override + public String getComponentKey() { + return projectName; + } + + @Override + protected ProjectVersionComponent createChildComponent(String key) throws Exception { + return new ProjectVersionComponent(resourceContext, this, key); + } + + @Override + protected List getChildrenKeyList() { + if (dataObject.versions == null) + return Collections.emptyList(); + return new ArrayList<>(dataObject.versions.keySet()); + } + + @Override + protected void addChildKey(String key) { + dataObject.addVersion(key, Calendar.getInstance().getTimeInMillis() + ""); + } + + @Override + protected void removeChildKey(String key) { + dataObject.removeVersion(key); + } + + @Override + protected void handleChildLoadException(String key, Exception e) { + log.error("Error loading version [" + key + "]", e); + } + + public ProjectComponent storage(ApplicationStorage storage) { + this.applicationStorage = storage; + return this; + } + + /* EntaxyApplicationProject implementation */ + + @Override + public String getName() { + return projectName; + } + + @Override + public String getGroup() { + return group; + } + + @Override + public ApplicationStorage getStorage() { + return this.applicationStorage; + } + + @Override + public void save() { + // TODO Auto-generated method stub + + } + + @Override + public void disgard() { + // TODO Auto-generated method stub + + } + + @Override + public List getVersions() { + return new ArrayList<>(childrenCache.values()); + } + + @Override + public EntaxyApplicationProjectVersion getLatestVersion() { + String latest = dataObject.getLatestVersion(); + if (latest == null) + return null; + return getVersion(latest); + } + + @Override + public EntaxyApplicationProjectVersion getVersion(String version) { + return childrenCache.get(version); + } + + @Override + public EntaxyApplicationProjectVersion createVersion(String version) throws ProjectVersionException { + try { + return createNewChild(version); + } catch (Exception e) { + log.error("Error creating version [" + version + "]", e); + if (e instanceof ProjectVersionException) + throw (ProjectVersionException) e; + throw new ProjectVersionCausedException(projectName, version, e); + } + } + + @Override + public EntaxyApplicationProjectVersion createVersion(String version, String fromVersion) + throws ProjectVersionException { + ProjectVersionComponent sourceVersion = childrenCache.get(fromVersion); + if (sourceVersion == null) + throw new ProjectVersionNotFoundException(projectName, fromVersion); + try { + ProjectVersionComponent newVersion = createNewChild(version); + newVersion.updateFromString(sourceVersion.getAsJsonString()); + newVersion.getProperties().put(STANDARD_PROPERTIES.CREATED_ON, + Calendar.getInstance().getTimeInMillis() + ""); + newVersion.save(); + } catch (Exception e) { + log.error("Error creating version [" + version + "]", e); + if (e instanceof ProjectVersionException) + throw (ProjectVersionException) e; + throw new ProjectVersionCausedException(projectName, version, e); + } + return null; + } + + @Override + public void removeVersion(String version) { + try { + removeChild(version); + } catch (Exception e) { + log.error("Error removing version [" + version + "]", e); + } + } + + @Override + public ApplicationProjectInfo getInfo() { + // TODO Auto-generated method stub + return null; + } + + + +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectData.java new file mode 100644 index 00000000..15132c66 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectData.java @@ -0,0 +1,73 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.project; + +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; + +public class ProjectData { + + String name; + String group; + + Map versions; + + public ProjectData(String name, String group) { + this.name = name; + this.group = group; + } + + public void addVersion(String version, String timestamp) { + if (versions == null) + versions = new HashMap<>(); + if (!versions.containsKey(version)) + versions.put(version, timestamp); + } + + public void removeVersion(String version) { + if (versions == null) + return; + versions.remove(version); + } + + public String getLatestVersion() { + Optional> latest = + versions.entrySet().stream().sorted(new Comparator>() { + + @Override + public int compare(Entry o1, Entry o2) { + // reverse order + return -1 * o1.getValue().compareTo(o2.getValue()); + } + }).findFirst(); + if (!latest.isPresent()) + return null; + return latest.get().getKey(); + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectVersionComponent.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectVersionComponent.java new file mode 100644 index 00000000..4ceeba8f --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectVersionComponent.java @@ -0,0 +1,332 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.project; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceURLFactory; +import ru.entaxy.platform.integration.applications.ApplicationProjectItem; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProject; +import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion; +import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor; +import ru.entaxy.platform.integration.applications.exceptions.ItemException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionIsDirtyException; +import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionNotConsistentException; +import ru.entaxy.platform.integration.applications.impl.build.ApplicationBuilder; +import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectContentImpl; +import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponent; +import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectResource; + +public class ProjectVersionComponent extends AbstractResourceComponent + implements EntaxyApplicationProjectVersion { + + private static final Logger LOG = LoggerFactory.getLogger(ProjectVersionComponent.class); + + String versionNumber; + + ProjectComponent applicationComponent; + + ApplicationProjectContentImpl applicationContent = new ApplicationProjectContentImpl(); + + EntaxyResource contentResource; + + BuildComponent buildComponent; + + final String CONTENT_RESOURCE_NAME = "version.content"; + + VERSION_STATUS status = VERSION_STATUS.NEW; + + private boolean isDirty = false; + + protected void setDirty(boolean isDirty) { + this.isDirty = isDirty; + } + + /* + public ProjectVersionComponent(EntaxyResourceService entaxyResourceService, ProjectComponent applicationComponent, + String versionNumber) { + super(entaxyResourceService); + this.versionNumber = versionNumber; + this.applicationComponent = applicationComponent; + this.rootResourceFolderUrl = + applicationComponent.getRootResourceFolderUrl().concat("/").concat(this.versionNumber); + applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, applicationComponent.getName()); + applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, versionNumber); + + buildComponent = new BuildComponent(entaxyResourceService, rootResourceFolderUrl); + } + */ + + public ProjectVersionComponent(ResourceContext parentResourceContext, ProjectComponent applicationComponent, + String versionNumber) { + super(parentResourceContext.subcontext(versionNumber)); + this.versionNumber = versionNumber; + this.applicationComponent = applicationComponent; + applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, applicationComponent.getName()); + applicationContent.getProperties().put(STANDARD_PROPERTIES.GROUP, applicationComponent.getGroup()); + applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, versionNumber); + + buildComponent = new BuildComponent(resourceContext); + } + + @Override + protected Class getDataObjectClass() { + return ProjectVersionData.class; + } + + @Override + protected String getRootResourceName() { + return ".version"; + } + + @Override + protected ProjectVersionData createDataObject() { + return new ProjectVersionData(this.versionNumber, this.status.toString()); + } + + @Override + public String getComponentKey() { + return versionNumber; + } + + @Override + protected void initializeDataObject() throws Exception { + // TODO Auto-generated method stub + super.initializeDataObject(); + this.status = VERSION_STATUS.valueOf(dataObject.status); + } + + @Override + public void init() { + super.init(); + initContent(); + buildComponent.init(); + } + + protected void initContent() { + if (contentResource == null) { + contentResource = getResource(CONTENT_RESOURCE_NAME); + if (!contentResource.exists()) { + save(); + } else { + applicationContent.unmarshall(contentResource.getAsString()); + } + } + } + + public String getAsJsonString() { + return applicationContent.marshall(); + } + + public void updateFromString(String jsonData) { + applicationContent.unmarshall(jsonData); + applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, applicationComponent.getName()); + applicationContent.getProperties().put(STANDARD_PROPERTIES.GROUP, applicationComponent.getGroup()); + applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, versionNumber); + } + + /* EntaxyApplicationProjectVersion implementation */ + + @Override + public void disgard() { + applicationContent.unmarshall(contentResource.getAsString()); + } + + @Override + public void save() { + String data = applicationContent.marshall(); + try (ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes())) { + contentResource.save(bis); + setDirty(false); + } catch (IOException e) { + LOG.error("Error saving resource [" + contentResource.getURL() + "]", e); + } + } + + @Override + public String getVersionNumber() { + return versionNumber; + } + + @Override + public List getItems() { + return applicationContent.getItems(); + } + + @Override + public List getItems(Class itemClass) { + return applicationContent.getItems(itemClass); + } + + @Override + public void addItem(ApplicationProjectItem item) throws ItemException { + try { + applicationContent.addItem(item); + setDirty(true); + } catch (ItemException e) { + e.setVersionNumber(versionNumber); + e.setApplicationName(this.applicationComponent.getName()); + throw e; + } + } + + @Override + public void ignoreItem(ApplicationProjectItem item) throws ItemException { + try { + applicationContent.ignoreItem(item); + setDirty(true); + } catch (ItemException e) { + e.setVersionNumber(versionNumber); + e.setApplicationName(this.applicationComponent.getName()); + throw e; + } + } + + @Override + public void removeItem(ApplicationProjectItem item) throws ItemException { + try { + applicationContent.removeItem(item); + setDirty(true); + } catch (ItemException e) { + e.setVersionNumber(versionNumber); + e.setApplicationName(this.applicationComponent.getName()); + throw e; + } + } + + @Override + public EntaxyApplicationProject getApplication() { + return this.applicationComponent; + } + + @Override + public ApplicationProjectItem addObject(EntaxyRuntimeObject runtimeObject) { + setDirty(true); + return applicationContent.addObject(runtimeObject); + } + + @Override + public ApplicationProjectItem addResource(EntaxyRuntimeObjectResource runtimeObjectResource) { + setDirty(true); + return applicationContent.addResource(runtimeObjectResource); + } + + @Override + public ApplicationProjectItem addResource(EntaxyResource entaxyResource) { + setDirty(true); + return applicationContent.addResource(entaxyResource); + } + + @Override + public Map getProperties() { + return applicationContent.getProperties(); + } + + @Override + public VERSION_STATUS getStatus() { + return status; + } + + @Override + public URL build() throws ProjectVersionException { + if (!isConsistent()) + throw new ProjectVersionNotConsistentException(applicationComponent.getName(), versionNumber); + if (isDirty()) + throw new ProjectVersionIsDirtyException(applicationComponent.getName(), versionNumber); + ApplicationBuilder builder = new ApplicationBuilder(applicationContent); + builder.getCoordinates() + .groupId(applicationComponent.getGroup()) + .artifactId(applicationComponent.getName()) + .version(versionNumber); + URL result = builder.build(); + buildComponent.updateBuild(result, builder.getDescriptor(), builder.getCoordinates()); + builder.clear(); + if (isBuildAvailable()) { + status = VERSION_STATUS.BUILT; + dataObject.status = status.toString(); + try { + updateRootResource(); + } catch (Exception e) { + LOG.error("Error updating root resource for project [" + applicationComponent.getName() + + "] version [" + versionNumber + "]", e); + } + try { + return EntaxyResourceURLFactory.getGlobalUrl(buildComponent.getBuildResource()); + } catch (MalformedURLException e) { + LOG.error("Error creating URL for [" + buildComponent.getBuildResource().getURL() + "]", e); + return null; + } + } + return null; + } + + @Override + public InputStream getBuild() { + if (!isBuildAvailable()) + return null; + return buildComponent.getBuildResource().getInputStream(); + } + + @Override + public URL getBuildUrl() { + if (!isBuildAvailable()) + return null; + try { + return EntaxyResourceURLFactory.getGlobalUrl(buildComponent.getBuildResource()); + } catch (MalformedURLException e) { + LOG.error("Error getting global URL for resource [" + buildComponent.getBuildResource().getURL() + "]", e); + return null; + } + } + + @Override + public boolean isBuildAvailable() { + return buildComponent.isBuildAvailable(); + } + + @Override + public ApplicationDescriptor getBuildInfo() { + return buildComponent.getApplicationDescriptor(); + } + + @Override + public boolean isDirty() { + return isDirty; + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectVersionData.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectVersionData.java new file mode 100644 index 00000000..ed239253 --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/impl/project/ProjectVersionData.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.impl.project; + +public class ProjectVersionData { + + String versionNumber; + String status; + + public ProjectVersionData(String versionNumber, String status) { + this.versionNumber = versionNumber; + this.status = status; + } +} diff --git a/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/internal/DefaultApplicationStorage.java b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/internal/DefaultApplicationStorage.java new file mode 100644 index 00000000..4445012d --- /dev/null +++ b/platform/integration/applications/resource-based-storage/src/main/java/ru/entaxy/platform/integration/applications/storage/resource/internal/DefaultApplicationStorage.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resource-based-storage + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.integration.applications.storage.resource.internal; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.integration.applications.ApplicationStorage; +import ru.entaxy.platform.integration.applications.storage.ApplicationStorageInfo; +import ru.entaxy.platform.integration.applications.storage.resource.ResourceBasedStorage; + +@Component(service = ApplicationStorage.class, immediate = true) +@ApplicationStorageInfo(name = "default") +public class DefaultApplicationStorage extends ResourceBasedStorage { + + public DefaultApplicationStorage() { + super(); + setResourceProvider("entaxy-file-internal"); + setPath(".applications"); + } + + @Reference(cardinality = ReferenceCardinality.MANDATORY, unbind = "unbindResourceService") + public void bindResourceService(EntaxyResourceService resourceService) { + this.entaxyResourceService = resourceService; + } + + public void unbindResourceService(EntaxyResourceService resourceService) { + this.entaxyResourceService = null; + } + + @Activate + public void activate() { + init(); + } +} diff --git a/platform/integration/applications/src/main/features/features.xml b/platform/integration/applications/src/main/features/features.xml new file mode 100644 index 00000000..65d77df4 --- /dev/null +++ b/platform/integration/applications/src/main/features/features.xml @@ -0,0 +1,40 @@ + + + + + + + mvn:ru.entaxy.platform.integration.applications/application-api/${project.version} + mvn:ru.entaxy.platform.integration.applications/application-impl/${project.version} + mvn:ru.entaxy.platform.integration.applications/resource-based-storage/${project.version} + mvn:ru.entaxy.platform.integration.applications/application-shell/${project.version} + mvn:ru.entaxy.platform.integration.applications/application-management/${project.version} + + + diff --git a/platform/integration/pom.xml b/platform/integration/pom.xml new file mode 100644 index 00000000..20625381 --- /dev/null +++ b/platform/integration/pom.xml @@ -0,0 +1,16 @@ + + 4.0.0 + + platform + ru.entaxy.esb + 1.10.0 + + ru.entaxy.platform + integration + pom + ENTAXY :: PLATFORM :: INTEGRATION + ENTAXY :: PLATFORM :: INTEGRATION + + applications + + diff --git a/platform/runtime/base/base-extensions-support/LICENSE.txt b/platform/runtime/base/base-extensions-support/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/base/base-extensions-support/pom.xml b/platform/runtime/base/base-extensions-support/pom.xml new file mode 100644 index 00000000..097e3667 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime + base + 1.10.0 + + ru.entaxy.esb.platform.runtime.base + base-extensions-support + bundle + ENTAXY :: PLATFORM :: BASE :: EXTENSIONS SUPPORT + ENTAXY :: PLATFORM :: BASE :: EXTENSIONS SUPPORT + + + + ru.entaxy.esb.platform.runtime.base.extensions.api + + + ru.entaxy.esb.platform.runtime.base.extensions.impl, + ru.entaxy.esb.platform.runtime.base.extensions.shell + + none + + + + + org.osgi + org.osgi.service.component.annotations + + + org.apache.felix + org.apache.felix.scr + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + org.apache.karaf.shell + org.apache.karaf.shell.core + ${karaf.version} + + + + diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtendable.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtendable.java new file mode 100644 index 00000000..9e86dd8b --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtendable.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.api; + +import java.util.List; +import java.util.UUID; + +public interface EntaxyExtendable extends EntaxyExtensionsProvider { + + default String getExtendableId() { + if (this.getClass().isAnnotationPresent(Extendable.class)) + return this.getClass().getAnnotation(Extendable.class).value(); + return UUID.randomUUID().toString(); + } + + void addExtension(EntaxyExtension entaxyExtension); + void removeExtension(EntaxyExtension entaxyExtension); + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtension.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtension.java new file mode 100644 index 00000000..6fe1b947 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtension.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.api; + +import java.net.URL; +import java.util.Map; + +public interface EntaxyExtension { + + long getBundleId(); + Map getResources(); + + Map getCustomData(); + + String getTargetExtendableId(); +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionService.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionService.java new file mode 100644 index 00000000..cd8a2874 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionService.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.api; + +import java.util.List; + +public interface EntaxyExtensionService { + + String HEADER_EXTENSIONS_PROVIDER = "Entaxy-Extensions-Provider"; + String HEADER_EXTENSIONS_LOCATION = "Entaxy-Extensions-Location"; + + String DEFAULT_EXTENSIONS_LOCATION = "ru/entaxy/extensions"; + + List getExtensions(); + + List getExtendables(); +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionsAware.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionsAware.java new file mode 100644 index 00000000..2247db57 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionsAware.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.api; + +import java.util.List; + +public interface EntaxyExtensionsAware { + + void addExtension(EntaxyExtension entaxyExtension); + default void addExtensions(List entaxyExtensions) { + for (EntaxyExtension extension: entaxyExtensions) + addExtension(extension); + }; + + void removeExtension(EntaxyExtension entaxyExtension); + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionsProvider.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionsProvider.java new file mode 100644 index 00000000..e2f0854f --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/EntaxyExtensionsProvider.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.api; + +import java.util.List; + +public interface EntaxyExtensionsProvider { + + List getExtensions(); + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/Extendable.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/Extendable.java new file mode 100644 index 00000000..1185471d --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/api/Extendable.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.api; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface Extendable { + String value(); +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/impl/EntaxyExtensionImpl.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/impl/EntaxyExtensionImpl.java new file mode 100644 index 00000000..fef71e43 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/impl/EntaxyExtensionImpl.java @@ -0,0 +1,73 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.impl; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.osgi.framework.Bundle; + +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension; + +public class EntaxyExtensionImpl implements EntaxyExtension { + + protected Bundle bundle; + + protected String targetId; + + protected final Map customData = new HashMap<>(); + + protected final Map resources = new HashMap<>(); + + public EntaxyExtensionImpl(Bundle b, String target) { + this.bundle = b; + this.targetId = target; + } + + @Override + public long getBundleId() { + return bundle==null + ?-1 + :bundle.getBundleId(); + } + + @Override + public Map getResources() { + return resources; + } + + @Override + public Map getCustomData() { + return customData; + } + + @Override + public String getTargetExtendableId() { + return targetId; + } + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/impl/EntaxyExtensionServiceImpl.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/impl/EntaxyExtensionServiceImpl.java new file mode 100644 index 00000000..cdbe2812 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/impl/EntaxyExtensionServiceImpl.java @@ -0,0 +1,212 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.impl; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.osgi.util.tracker.BundleTracker; + +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtendable; +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension; +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionService; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerCustomizerListener; +import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerUtils; +import ru.entaxy.platform.base.support.osgi.tracker.UniformBundleTrackerCustomizer; +import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleHeaderFilter; + +@Component(service = EntaxyExtensionService.class, immediate = true) +public class EntaxyExtensionServiceImpl + extends UniformBundleTrackerCustomizer> + implements EntaxyExtensionService, + BundleTrackerCustomizerListener> { + + protected BundleContext bundleContext; + + protected Map extendables = new HashMap<>(); + + protected Object extensionsLock = new Object(); + + protected final Map> extensions = new HashMap<>(); + + protected BundleTracker> extensionTracker; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + extensionTracker = BundleTrackerUtils.>createBuilder() + .bundleContext(this.bundleContext) + .addFilter( + (new BundleHeaderFilter()).header(HEADER_EXTENSIONS_PROVIDER)) + .customizer(this.listener(this)) + .bundleState(Bundle.INSTALLED | Bundle.RESOLVED | Bundle.ACTIVE) + .get(); + extensionTracker.open(); + + } + + @Deactivate + public void deactivate() { + extensionTracker.close(); + } + + @Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY, + unbind = "removeExtendable") + public void addExtendable(EntaxyExtendable entaxyExtendable) { + synchronized (extensionsLock) { + String extendableId = entaxyExtendable.getExtendableId(); + extendables.put(extendableId, entaxyExtendable); + if (extensions.containsKey(extendableId)) + for (EntaxyExtension extension : extensions.get(extendableId)) + entaxyExtendable.addExtension(extension); + } + } + + public void removeExtendable(EntaxyExtendable entaxyExtendable) { + extendables.remove(entaxyExtendable.getExtendableId()); + } + + @Override + public void added(List managedObject) { + synchronized (extensionsLock) { + for (EntaxyExtension extension : managedObject) { + String targetId = extension.getTargetExtendableId(); + extensions.putIfAbsent(targetId, new ArrayList<>()); + + extensions.get(targetId).add(extension); + if (extendables.containsKey(targetId)) + extendables.get(targetId).addExtension(extension); + } + } + } + + @Override + public void modified(List ignore) {} + + @Override + public void removed(List managedObject) { + synchronized (extensionsLock) { + for (EntaxyExtension extension : managedObject) { + String targetId = extension.getTargetExtendableId(); + if (extendables.containsKey(targetId)) + extendables.get(targetId).removeExtension(extension); + + if (extensions.containsKey(targetId)) + extensions.get(targetId).remove(extension); + } + } + } + + @Override + protected List createManagedObject(Bundle bundle, BundleEvent event, + Map> filterResults) { + String resourceLocation = + CommonUtils.getValid(bundle.getHeaders().get(HEADER_EXTENSIONS_LOCATION), DEFAULT_EXTENSIONS_LOCATION); + Enumeration entries = bundle.findEntries(resourceLocation, "*.*", true); + + Map localExtensions = new HashMap<>(); + + if (entries != null) + while (entries.hasMoreElements()) { + URL entry = entries.nextElement(); + if (entry.toString().endsWith("/")) + continue; + + String localPath = entry.toString(); + localPath = localPath.substring(localPath.indexOf(resourceLocation) + resourceLocation.length() + 1); + + String resourceName = localPath.substring(localPath.lastIndexOf("/") + 1); + + String path = localPath.lastIndexOf("/") >= 0 + ? localPath.substring(0, localPath.lastIndexOf("/")) + : ""; + int splitIndex = path.indexOf("/"); + String target = splitIndex > 0 + ? path.substring(0, splitIndex) + : ""; + + if (splitIndex > 0) + path = path.substring(splitIndex + 1); + + if (!CommonUtils.isValid(target) || !CommonUtils.isValid(resourceName)) + continue; + + if (!localExtensions.containsKey(target)) + localExtensions.put(target, new EntaxyExtensionImpl(bundle, target)); + + localExtensions.get(target).getResources().put(path + "/" + resourceName, entry); + + } + + return localExtensions.values().stream().collect(Collectors.toList()); + } + + @Override + public List getExtensions() { + final List result = new ArrayList<>(); + extensions.values().forEach(arr -> result.addAll(arr)); + Collections.sort(result, new Comparator() { + + @Override + public int compare(EntaxyExtension o1, EntaxyExtension o2) { + int res = o1.getTargetExtendableId().compareTo(o2.getTargetExtendableId()); + if (res != 0) + return res; + if (o1.getBundleId() < o2.getBundleId()) + return -1; + if (o1.getBundleId() > o2.getBundleId()) + return 1; + return 0; + } + }); + return result; + } + + @Override + public List getExtendables() { + return extendables.values().stream().collect(Collectors.toList()); + } + + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/EntaxyExtensionServiceSupport.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/EntaxyExtensionServiceSupport.java new file mode 100644 index 00000000..535faf2b --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/EntaxyExtensionServiceSupport.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.shell; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.lifecycle.Reference; + +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionService; + +public abstract class EntaxyExtensionServiceSupport implements Action { + + @Reference + EntaxyExtensionService extensionService; + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/ExtendablesList.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/ExtendablesList.java new file mode 100644 index 00000000..94a3c553 --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/ExtendablesList.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.shell; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.support.table.ShellTable; + +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtendable; + +@Service +@Command(scope = "entaxy", name = "extendables-list") +public class ExtendablesList extends EntaxyExtensionServiceSupport { + + @Override + public Object execute() throws Exception { + + ShellTable table = new ShellTable(); + + table.column("Extendable id"); + + for (EntaxyExtendable ext: extensionService.getExtendables()) + table.addRow().addContent(ext.getExtendableId()); + + table.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/ExtensionsList.java b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/ExtensionsList.java new file mode 100644 index 00000000..0e40c5ac --- /dev/null +++ b/platform/runtime/base/base-extensions-support/src/main/java/ru/entaxy/esb/platform/runtime/base/extensions/shell/ExtensionsList.java @@ -0,0 +1,79 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-extensions-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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.base.extensions.shell; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.support.table.ShellTable; + +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension; + +@Service +@Command(scope = "entaxy", name = "extension-list") +public class ExtensionsList extends EntaxyExtensionServiceSupport { + + @Option(name = "-r", multiValued = false) + boolean showResources; + + @Override + public Object execute() throws Exception { + ShellTable shellTable = new ShellTable(); + + shellTable.column("Target"); + shellTable.column("Bundle"); + + if (showResources) { + shellTable.column("Resource"); + shellTable.column("Resource URL"); + } + + List list = extensionService.getExtensions(); + for (EntaxyExtension ext: list) + if (!showResources) + shellTable.addRow().addContent(ext.getTargetExtendableId(), ext.getBundleId()); + else { + List resources = new ArrayList<>(ext.getResources().keySet()); + Collections.sort(resources); + for (String resource: resources) { + shellTable.addRow().addContent( + ext.getTargetExtendableId(), + ext.getBundleId(), + resource, + ext.getResources().get(resource).toString()); + } + } + + shellTable.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/SimpleFileWatcher.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/SimpleFileWatcher.java new file mode 100644 index 00000000..646e8d44 --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/SimpleFileWatcher.java @@ -0,0 +1,211 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +package ru.entaxy.platform.base.support; + +import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; +import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; +import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; + +import java.io.IOException; +import java.nio.file.FileSystems; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.WatchEvent; +import java.nio.file.WatchKey; +import java.nio.file.WatchService; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.HashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SimpleFileWatcher implements Runnable { + + public static interface WatcherCallback { + + default void directoryCreated(WatchEvent event, Path directory) {}; + + default void directoryModified(WatchEvent event, Path directory) {}; + + default void directoryDeleted(WatchEvent event, Path directory) {}; + + default void fileCreated(WatchEvent event, Path directory) {}; + + default void fileModified(WatchEvent event, Path directory) {}; + + default void fileDeleted(WatchEvent event, Path directory) {}; + + } + + private static final Logger LOG = LoggerFactory.getLogger(SimpleFileWatcher.class); + + protected static final WatcherCallback NULL_CALLBACK = new WatcherCallback() {}; + + protected final WatchService watchService; + protected final Map keys; + + protected WatcherCallback watcherCallback = null; + + /** + * Creates a WatchService and registers the given directory + */ + public SimpleFileWatcher(Path dir) throws IOException { + this.watchService = FileSystems.getDefault().newWatchService(); + this.keys = new HashMap(); + + walkAndRegisterDirectories(dir); + } + + /** + * Register the given directory with the WatchService; This function will be called by + * FileVisitor + */ + private void registerDirectory(Path dir) throws IOException { + WatchKey key = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); + keys.put(key, dir); + } + + /** + * Register the given directory, and all its sub-directories, with the WatchService. + */ + private void walkAndRegisterDirectories(final Path start) throws IOException { + // register directory and sub-directories + Files.walkFileTree(start, new SimpleFileVisitor() { + @Override + public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { + registerDirectory(dir); + return FileVisitResult.CONTINUE; + } + }); + } + + public void setWatcherCallback(WatcherCallback watcherCallback) { + this.watcherCallback = watcherCallback; + } + + protected WatcherCallback getActiveCallback() { + return watcherCallback == null ? NULL_CALLBACK : watcherCallback; + } + + /** + * Process all events for keys queued to the watchService + */ + @Override + public void run() { + + WatchKey key = null; + try { + while ((key = watchService.take()) != null) { + + Path dir = keys.get(key); + if (dir == null) { + System.err.println("WatchKey not recognized!!"); + continue; + } + + for (WatchEvent event : key.pollEvents()) { + @SuppressWarnings("rawtypes") + WatchEvent.Kind kind = event.kind(); + + // Context for directory entry event is the file name of entry + @SuppressWarnings("unchecked") + Path name = ((WatchEvent) event).context(); + Path child = dir.resolve(name); + + // print out event + LOG.debug("{}: {}\n", event.kind().name(), child); + + // if directory is created, and watching recursively, then register it and its + // sub-directories + + if (kind == ENTRY_CREATE) { + try { + if (Files.isDirectory(child)) { + walkAndRegisterDirectories(child); + getActiveCallback().directoryCreated(event, dir); + } else { + LOG.debug("FOUND FILE: {}", child.toString()); + getActiveCallback().fileCreated(event, dir); + } + } catch (Exception x) { + LOG.error(String.format("FAILED processing event [%s] for [%s]", kind, child.toString()), + x); + } + } else if (kind == ENTRY_MODIFY) { + try { + if (Files.isDirectory(child)) { + getActiveCallback().directoryModified(event, dir); + } else { + getActiveCallback().fileModified(event, dir); + } + } catch (Exception x) { + LOG.error(String.format("FAILED processing event [%s] for [%s]", kind, child.toString()), + x); + } + } else if (kind == ENTRY_DELETE) { + try { + if (Files.isDirectory(child)) { + getActiveCallback().directoryDeleted(event, dir); + } else { + getActiveCallback().fileDeleted(event, dir); + } + } catch (Exception x) { + LOG.error(String.format("FAILED processing event [%s] for [%s]", kind, child.toString()), + x); + } + } + } + + // reset key and remove from set if directory no longer accessible + boolean valid = key.reset(); + if (!valid) { + keys.remove(key); + + // all directories are inaccessible + if (keys.isEmpty()) { + break; + } + } + } + } catch (InterruptedException ignore) { + // NOOP + } + } + + public void close() { + try { + for (WatchKey key : keys.keySet()) + key.cancel(); + this.watchService.close(); + } catch (IOException e) { + LOG.error("FAILED closing SimpleFileWatcher", e); + } + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/AnsiColumnExt.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/AnsiColumnExt.java new file mode 100644 index 00000000..b59d53dc --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/AnsiColumnExt.java @@ -0,0 +1,96 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to You 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. + */ +package ru.entaxy.platform.base.support.karaf.shell; + +import org.jline.utils.AttributedStringBuilder; + +/** + * Colored support for column. + */ +public class AnsiColumnExt extends ColExt { + + private int color; + private boolean bold; + + public AnsiColumnExt(String header, int color, boolean bold) { + super(header); + this.color = color; + this.bold = bold; + } + + public String getContent(ShellTableExt.CellData cellData) { + String in = super.getContent(cellData); + + AttributedStringBuilder sb = new AttributedStringBuilder(); + sb.style(sb.style().foreground(color)); + + if (bold) + sb.style(sb.style().bold()); + + sb.append(in); + + if (bold) + sb.style(sb.style().boldOff()); + + sb.style(sb.style().foregroundOff()); + + return sb.toAnsi(); + } + + @Override + @Deprecated + public String getContent(String content) { + String in = super.getContent(content); + + AttributedStringBuilder sb = new AttributedStringBuilder(); + sb.style(sb.style().foreground(color)); + + if (bold) + sb.style(sb.style().bold()); + + sb.append(in); + + if (bold) + sb.style(sb.style().boldOff()); + + sb.style(sb.style().foregroundOff()); + + return sb.toAnsi(); + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ColExt.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ColExt.java new file mode 100644 index 00000000..aa6fa3f0 --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ColExt.java @@ -0,0 +1,381 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to You 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. + */ +package ru.entaxy.platform.base.support.karaf.shell; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.support.ansi.SimpleAnsi; + +/** + * Column definition. + */ +public class ColExt { + // This is kept here only for backwards compatibility + // and is used in cyan(boolean) method + private static final Function COLOR_CYAN = + (cellContent) -> SimpleAnsi.COLOR_CYAN; + + Function colorProvider; + + Function colorProviderExt; + + protected ShellTableExt ownerTable = null; + + /** + * Column header. + */ + private String header; + + /** + * Maximum size of this column. The default -1 means the column may grow indefinitely + */ + int maxSize = -1; + + int size = 0; + + boolean wrap; + boolean bold; + boolean cyan; + + Boolean splitLists = null; + + /** + * Alignment + */ + private HAlignExt align = HAlignExt.left; + + public ColExt(String header) { + this.header = header; + } + + public ColExt align(HAlignExt align) { + this.align = align; + return this; + } + + public ColExt alignLeft() { + this.align = HAlignExt.left; + return this; + } + + public ColExt alignRight() { + this.align = HAlignExt.right; + return this; + } + + public ColExt alignCenter() { + this.align = HAlignExt.center; + return this; + } + + public ColExt maxSize(int maxSize) { + this.maxSize = maxSize; + return this; + } + + public ColExt splitLists() { + return splitLists(true); + } + + public ColExt splitLists(boolean value) { + this.splitLists = value; + return this; + } + + public ColExt wrap() { + return wrap(true); + } + + public ColExt wrap(boolean wrap) { + this.wrap = wrap; + return this; + } + + public ColExt bold() { + return bold(true); + } + + public ColExt bold(boolean bold) { + this.bold = bold; + return this; + } + + public ColExt cyan() { + return cyan(true); + } + + public ColExt cyan(boolean cyan) { + if (cyan) + colorProvider(COLOR_CYAN); + + // Only remove colorProvider if argument is false and + // member equals COLOR_CYAN + else if (this.colorProvider == COLOR_CYAN) + colorProvider(null); + + return this; + } + + public int getSize() { + return size; + } + + public ColExt colorProvider(Function colorProvider) { + this.colorProvider = colorProvider; + return this; + } + + public ColExt colorProviderExt(Function colorProvider) { + this.colorProviderExt = colorProvider; + return this; + } + + protected void updateSize(int cellSize) { + if (this.size <= cellSize) { + this.size = getClippedSize(cellSize); + } + } + + private int getClippedSize(int cellSize) { + return this.maxSize == -1 ? cellSize : Math.min(cellSize, this.maxSize); + } + + /* + String format(Object cellData) { + if (cellData == null) { + cellData = ""; + } + String fullContent = String.format("%s", cellData); + if (fullContent.length() == 0) { + return ""; + } + String finalContent = cut(fullContent, getClippedSize(fullContent.length())); + updateSize(finalContent.length()); + return finalContent; + } + */ + + protected boolean isSplitLists() { + if (this.splitLists != null) + return this.splitLists; + if (ownerTable != null) + return ownerTable.isSplitLists(); + return false; + } + + /* + @ENTAXY_FIX: + when calculating cell size we must take into account not LENGTH, but WIDTH of the data + 'cause data may contain "\n" so the LENGTH of data won't be equal to it's WIDTH + */ + @SuppressWarnings("unchecked") + public String format(Object cellData) { + if (cellData == null) { + cellData = ""; + } + + String fullContent = String.format("%s", cellData); + + if (isSplitLists() && (cellData instanceof List)) { + fullContent = (String) ((List) cellData).stream().map(v -> v == null ? "" : v.toString()) + .collect(Collectors.joining("\n")); + } + + if (fullContent.length() == 0) { + return ""; + } + String finalContent = cut(fullContent, getClippedSize(fullContent.length())); + + int finalContentWidth = 0; + for (String s : Arrays.asList(finalContent.split("\n"))) + finalContentWidth = Math.max(finalContentWidth, s.length()); + + updateSize(finalContentWidth); + return finalContent; + } + + String getHeader() { + return header; + } + + String getContent(ShellTableExt.CellData cellData) { + + String content = cellData.cellContent; + + List lines = new ArrayList<>(); + lines.addAll(Arrays.asList(content.split("\n"))); + if (wrap) { + List wrapped = new ArrayList<>(); + for (String line : lines) { + wrapped.addAll(wrap(line)); + } + lines = wrapped; + } + + String color = null; + if (colorProviderExt != null) { + color = colorProviderExt.apply(cellData); + } else if (colorProvider != null) { + color = colorProvider.apply(content); + } + + StringBuilder sb = new StringBuilder(); + for (String line : lines) { + if (sb.length() > 0) { + sb.append("\n"); + } + line = this.align.position(cut(line, size), this.size); + if (bold) { + line = SimpleAnsi.INTENSITY_BOLD + line + SimpleAnsi.INTENSITY_NORMAL; + } + + if (color != null) + sb.append(color); + + sb.append(line); + + if (color != null) + sb.append(SimpleAnsi.COLOR_DEFAULT); + } + return sb.toString(); + } + + @Deprecated + String getContent(String content) { + List lines = new ArrayList<>(); + lines.addAll(Arrays.asList(content.split("\n"))); + if (wrap) { + List wrapped = new ArrayList<>(); + for (String line : lines) { + wrapped.addAll(wrap(line)); + } + lines = wrapped; + } + + String color = null; + if (colorProvider != null) { + color = colorProvider.apply(content); + } + + StringBuilder sb = new StringBuilder(); + for (String line : lines) { + if (sb.length() > 0) { + sb.append("\n"); + } + line = this.align.position(cut(line, size), this.size); + if (bold) { + line = SimpleAnsi.INTENSITY_BOLD + line + SimpleAnsi.INTENSITY_NORMAL; + } + + if (color != null) + sb.append(color); + + sb.append(line); + + if (color != null) + sb.append(SimpleAnsi.COLOR_DEFAULT); + } + return sb.toString(); + } + + /* + protected String cut(String content, int size) { + if (content.length() <= size) { + return content; + } else { + return content.substring(0, Math.max(0, size - 1)); + } + } + */ + + protected String cut0(String content, int size) { + if (content.length() <= size) { + return content; + } else { + return content.substring(0, Math.max(0, size - 1)); + } + } + + protected String cut(String content, int size) { + if (content.length() <= size) { + return content; + } else { + + String[] contentSplitted = content.split("\n"); + for (int i = 0; i < contentSplitted.length; i++) + contentSplitted[i] = cut0(contentSplitted[i], size); + + if (contentSplitted.length == 1) + return contentSplitted[0]; + + return Arrays.asList(contentSplitted).stream().collect(Collectors.joining("\n")); + } + } + + protected List wrap(String str) { + List result = new ArrayList<>(); + Pattern wrap = Pattern.compile("(\\S\\S{" + size + ",}|.{1," + size + "})(\\s+|$)"); + int cur = 0; + while (cur >= 0) { + int lst = str.indexOf('\n', cur); + String s = (lst >= 0) ? str.substring(cur, lst) : str.substring(cur); + if (s.length() == 0) { + result.add(s); + } else { + Matcher m = wrap.matcher(s); + while (m.find()) { + result.add(m.group()); + } + } + if (lst >= 0) { + cur = lst + 1; + } else { + break; + } + } + return result; + } + + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/HAlignExt.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/HAlignExt.java new file mode 100644 index 00000000..39c3ec8d --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/HAlignExt.java @@ -0,0 +1,93 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to You 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. + */ +package ru.entaxy.platform.base.support.karaf.shell; + +import static ru.entaxy.platform.base.support.karaf.shell.StringUtil.length; +import static ru.entaxy.platform.base.support.karaf.shell.StringUtil.repeat; + +/** + * Enumeration type which contains all possible horizontal alignments. + */ +public enum HAlignExt { + + /** + * Center align. + */ + center { + @Override + public String position(String text, int colWidth) { + int width = colWidth - length(text); + text = repeat(" ", width / 2) + text + repeat(" ", width / 2); + if (length(text) < colWidth) { + // if colWidth is odd we add space at the end. + text += " "; + } + return text; + } + }, + + /** + * Left align. + */ + left { + @Override + public String position(String text, int colWidth) { + return text + repeat(" ", colWidth - length(text)); + } + }, + + /** + * Right align. + */ + right { + @Override + public String position(String text, int colWidth) { + return repeat(" ", colWidth - length(text)) + text; + } + }; + + /** + * Calculate text position. + * + * @param text the text to align. + * @param colWidth the column width. + * @return the string at the given position. + */ + public abstract String position(String text, int colWidth); + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/RowExt.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/RowExt.java new file mode 100644 index 00000000..2980bc4a --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/RowExt.java @@ -0,0 +1,132 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to You 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. + */ +package ru.entaxy.platform.base.support.karaf.shell; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class RowExt { + + protected List data; + protected List content; + + protected Object dataObject = null; + + RowExt() { + data = new ArrayList<>(); + content = new ArrayList<>(); + } + + RowExt(Object dataObject) { + data = new ArrayList<>(); + content = new ArrayList<>(); + this.dataObject = dataObject; + } + + RowExt(List cols) { + this(); + for (ColExt col : cols) { + data.add(col.getHeader()); + } + } + + public void addContent(List data) { + this.data = data; + } + + public void addContent(Object... cellDataAr) { + data.addAll(Arrays.asList(cellDataAr)); + } + + void formatContent(List cols) { + content.clear(); + int c = 0; + for (ColExt col : cols) { + content.add(col.format(data.get(c))); + c++; + } + } + + String getContent(List cols, String separator) { + if (cols.size() != content.size()) { + throw new RuntimeException("Number of columns and number of content elements do not match"); + } + + List contents = new ArrayList<>(); + int lines = 0; + for (int col = 0; col < cols.size(); col++) { + // String[] cnt = cols.get(col).getContent(content.get(col)).split("\n"); + String[] cnt = cols.get(col).getContent(new ShellTableExt.CellData(dataObject, content.get(col))).split("\n"); + lines = Math.max(lines, cnt.length); + contents.add(cnt); + } + StringBuilder st = new StringBuilder(); + for (int line = 0; line < lines; line++) { + if (line > 0) { + st.append("\n"); + } + StringBuilder st2 = new StringBuilder(); + for (int col = 0; col < cols.size(); col++) { + String[] strings = contents.get(col); + if (col > 0) { + st2.append(separator); + } + if (line < strings.length) { + st2.append(strings[line]); + } else { + st2.append(StringUtil.repeat(" ", cols.get(col).getSize())); + } + } + while (st2.charAt(st2.length() - 1) == ' ') { + st2.setLength(st2.length() - 1); + } + st.append(st2); + } + return st.toString(); + } + + public Object getDataObject() { + return dataObject; + } + + public void setDataObject(Object dataObject) { + this.dataObject = dataObject; + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ShellTableColFixed.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ShellTableColFixed.java new file mode 100644 index 00000000..ad907661 --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ShellTableColFixed.java @@ -0,0 +1,90 @@ +/*- + * ~~~~~~licensing~~~~~~ + * platform-manager-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.base.support.karaf.shell; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.support.table.Col; + +public class ShellTableColFixed extends Col { + + protected int maxSizeLocal = -1; + + public ShellTableColFixed(String header) { + super(header); + } + + @Override + protected String cut(String content, int size) { + if (content.length() <= size) { + return content; + } else { + + String[] contentSplitted = content.split("\n"); + for (int i=0; i cols = new ArrayList<>(); + private List rows = new ArrayList<>(); + private boolean showHeaders = true; + private String separator = DEFAULT_SEPARATOR; + private int size; + private String emptyTableText; + private boolean forceAscii; + + private boolean splitLists = false; + + public ShellTableExt() { + + } + + public ShellTableExt noHeaders() { + this.showHeaders = false; + return this; + } + + public ShellTableExt separator(String separator) { + this.separator = separator; + return this; + } + + public ShellTableExt size(int size) { + this.size = size; + return this; + } + + public boolean isSplitLists() { + return splitLists; + } + + public ShellTableExt splitLists() { + return splitLists(true); + } + + public ShellTableExt splitLists(boolean value) { + this.splitLists = value; + return this; + } + + public ShellTableExt column(ColExt colunmn) { + cols.add(colunmn); + colunmn.ownerTable = this; + return this; + } + + public ColExt column(String header) { + ColExt col = new ColExt(header); + col.ownerTable = this; + cols.add(col); + return col; + } + + public RowExt addRow() { + RowExt row = new RowExt(); + rows.add(row); + return row; + } + + public RowExt addRow(Object dataObject) { + RowExt row = addRow(); + row.setDataObject(dataObject); + return row; + } + + public ShellTableExt forceAscii() { + forceAscii = true; + return this; + } + + /** + * Set text to display if there are no rows in the table. + * + * @param text the text to display when the table is empty. + * @return the shell table. + */ + public ShellTableExt emptyTableText(String text) { + this.emptyTableText = text; + return this; + } + + public void print(PrintStream out) { + print(out, true); + } + + public void print(PrintStream out, boolean format) { + print(out, null, format); + } + + public void print(PrintStream out, Charset charset, boolean format) { + boolean unicode = supportsUnicode(out, charset); + String separator = unicode ? this.separator : DEFAULT_SEPARATOR_ASCII; + + // "normal" table rendering, with borders + RowExt headerRow = new RowExt(cols); + headerRow.formatContent(cols); + for (RowExt row : rows) { + row.formatContent(cols); + } + + if (size > 0) { + adjustSize(); + } + + if (format && showHeaders) { + String headerLine = headerRow.getContent(cols, separator); + out.println(headerLine); + int iCol = 0; + for (ColExt col : cols) { + if (iCol++ == 0) { + out.print(underline(col.getSize(), false, unicode)); + } else { + out.print(underline(col.getSize() + 3, true, unicode)); + } + iCol++; + } + out.println(); + } + + for (RowExt row : rows) { + if (!format) { + if (separator == null || separator.equals(DEFAULT_SEPARATOR)) + out.println(row.getContent(cols, DEFAULT_SEPARATOR_NO_FORMAT)); + else + out.println(row.getContent(cols, separator)); + } else { + out.println(row.getContent(cols, separator)); + } + } + + if (format && rows.size() == 0 && emptyTableText != null) { + out.println(emptyTableText); + } + } + + private boolean supportsUnicode(PrintStream out, Charset charset) { + if (forceAscii) { + return false; + } + if (charset == null) { + charset = getEncoding(out); + } + if (charset == null) { + return false; + } + CharsetEncoder encoder = charset.newEncoder(); + return encoder.canEncode(separator) + && encoder.canEncode(SEP_HORIZONTAL) + && encoder.canEncode(SEP_CROSS); + } + + private Charset getEncoding(PrintStream ps) { + if (ps.getClass() == ThreadPrintStream.class) { + try { + return ((Terminal) Job.Utils.current().session().get(".jline.terminal")).encoding(); + } catch (Throwable t) { + // ignore + } + try { + ps = (PrintStream) ps.getClass().getMethod("getCurrent").invoke(ps); + } catch (Throwable t) { + // ignore + } + } + try { + Field f = ps.getClass().getDeclaredField("charOut"); + f.setAccessible(true); + OutputStreamWriter osw = (OutputStreamWriter) f.get(ps); + return Charset.forName(osw.getEncoding()); + } catch (Throwable t) { + // ignore + } + return null; + } + + private void adjustSize() { + int currentSize = 0; + for (ColExt col : cols) { + currentSize += col.size + separator.length(); + } + currentSize -= separator.length(); + int sizeToGrow = size - currentSize; + + for (int i = cols.size() - 1; i >= 0; i--) { + ColExt col = cols.get(i); + if (col.maxSize == -1) { + col.size = Math.max(0, col.size + sizeToGrow); + return; + } + } + + } + + private String underline(int length, boolean crossAtBeg, boolean supported) { + char[] exmarks = new char[length]; + Arrays.fill(exmarks, supported ? SEP_HORIZONTAL : SEP_HORIZONTAL_ASCII); + if (crossAtBeg) { + exmarks[1] = supported ? SEP_CROSS : SEP_CROSS_ASCII; + } + return new String(exmarks); + } + + public static class CellData { + public Object dataObject; + public String cellContent; + + public CellData(Object dataObject, String cellContent) { + this.dataObject = dataObject; + this.cellContent = cellContent; + } + + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ShellTableFixed.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ShellTableFixed.java new file mode 100644 index 00000000..387d062b --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/ShellTableFixed.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * platform-manager-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.base.support.karaf.shell; + +import org.apache.karaf.shell.support.table.ShellTable; + +/** + * @deprecated use {@link ru.entaxy.platform.base.support.karaf.shell.ShellTableExt} instead + */ +@Deprecated +public class ShellTableFixed extends ShellTable { + + @Override + public ShellTableColFixed column(String header) { + ShellTableColFixed col = new ShellTableColFixed(header); + column(col); + return col; + } + + public ShellTableFixed column(ShellTableColFixed colunmn) { + super.column(colunmn); + return this; + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/StringUtil.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/StringUtil.java new file mode 100644 index 00000000..6876160e --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/karaf/shell/StringUtil.java @@ -0,0 +1,68 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to You 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. + */ +package ru.entaxy.platform.base.support.karaf.shell; + +public class StringUtil { + + /** + * Returns length of the string. + * + * @param string String. + * @return Length. + */ + public static int length(String string) { + return string == null ? 0 : string.length(); + } + + /** + * Utility method to repeat string. + * + * @param string String to repeat. + * @param times Number of times. + * @return Repeat string. + */ + public static String repeat(String string, int times) { + if (times <= 0) { + return ""; + } else if (times % 2 == 0) { + return repeat(string + string, times / 2); + } else { + return string + repeat(string + string, times / 2); + } + } +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/osgi/feature/FeatureCapabilityHelper.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/osgi/feature/FeatureCapabilityHelper.java new file mode 100644 index 00000000..cfd5f72b --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/osgi/feature/FeatureCapabilityHelper.java @@ -0,0 +1,69 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +package ru.entaxy.platform.base.support.osgi.feature; + +import java.util.List; + +import org.apache.karaf.features.Capability; +import org.apache.karaf.features.Feature; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptorImpl; +import ru.entaxy.platform.base.support.osgi.bundle.CapabilityHelper; + +public class FeatureCapabilityHelper extends CapabilityHelper { + + private static final Logger LOG = LoggerFactory.getLogger(FeatureCapabilityHelper.class); + + protected Feature feature; + + public FeatureCapabilityHelper(Feature feature) { + super(); + setMultipleNamespacesSupported(true); + this.feature = feature; + load(); + } + + @Override + protected void load() { + super.load(); + List featureCapabilities = feature.getCapabilities(); + for (Capability c : featureCapabilities) { + String[] caps = c.getValue().split(","); + for (String cap : caps) + try { + CapabilityDescriptorImpl descriptor = parseCapability(cap); + if (descriptor != null) + addProvidedCapability(descriptor); + } catch (Exception e) { + LOG.error(String.format("Error parsing capability [%s] for feature [%s/%s]", cap, feature.getName(), + feature.getVersion()), e); + } + } + } + +} diff --git a/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/osgi/feature/FeaturesUtils.java b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/osgi/feature/FeaturesUtils.java new file mode 100644 index 00000000..0c59d3da --- /dev/null +++ b/platform/runtime/base/base-support/src/main/java/ru/entaxy/platform/base/support/osgi/feature/FeaturesUtils.java @@ -0,0 +1,164 @@ +/*- + * ~~~~~~licensing~~~~~~ + * base-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~~~~~~ + */ +package ru.entaxy.platform.base.support.osgi.feature; + +import java.util.Arrays; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.bundle.core.BundleService; +import org.apache.karaf.features.Feature; +import org.apache.karaf.features.FeaturesService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; + +public class FeaturesUtils { + + public static class FeaturesHelper { + + private static final Logger LOG = LoggerFactory.getLogger(FeaturesUtils.FeaturesHelper.class); + + public static FeaturesHelper create() { + return new FeaturesHelper(); + } + + public static FeaturesHelper create(BundleContext bundleContext) { + return create().bundleContext(bundleContext); + } + + protected BundleContext bundleContext = FrameworkUtil.getBundle(FeaturesUtils.class).getBundleContext(); + + protected String capabilityNamespace = null; + + protected boolean installedOnly = false; + + protected Bundle bundle = null; + + protected FeaturesHelper() { + super(); + } + + public List find() throws Exception { + + + ServiceReference ref = bundleContext.getServiceReference(FeaturesService.class); + FeaturesService featuresService = bundleContext.getService(ref); + + Feature[] featureArray = + isInstalledOnly() ? featuresService.listInstalledFeatures() : featuresService.listFeatures(); + + List features = Arrays.asList(featureArray); + + if (bundle != null) { + + ServiceReference ref0 = bundleContext.getServiceReference(BundleService.class); + BundleService bundleService = bundleContext.getService(ref0); + final String location = bundleService.getInfo(bundle).getUpdateLocation(); + bundleContext.ungetService(ref0); + + features = features.stream().filter( + f -> (f.getBundles().stream().filter(bi -> bi.getLocation().equals(location)) + .count() > 0)) + .collect(Collectors.toList()); + } + + if (CommonUtils.isValid(capabilityNamespace)) { + features = features.stream() + .filter(f -> (new FeatureCapabilityHelper(f).isCapabilityProvided(capabilityNamespace))) + .collect(Collectors.toList()); + } + + bundleContext.ungetService(ref); + + return features; + } + + public FeaturesUtils.FeaturesHelper bundleContext(BundleContext BundleContextValue) { + this.setBundleContext(BundleContextValue); + return this; + } + + public FeaturesUtils.FeaturesHelper withCapabilityNamespace(String capabilityNamespaceValue) { + this.setCapabilityNamespace(capabilityNamespaceValue); + return this; + }; + + public FeaturesUtils.FeaturesHelper installedOnly() { + this.setInstalledOnly(true); + return this; + }; + + public FeaturesUtils.FeaturesHelper installedOnly(boolean InstalledOnlyValue) { + this.setInstalledOnly(InstalledOnlyValue); + return this; + }; + + public FeaturesUtils.FeaturesHelper containingBundle(Bundle bundleValue) { + this.setBundle(bundleValue); + return this; + }; + + public BundleContext getBundleContext() { + return bundleContext; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + public String getCapabilityNamespace() { + return capabilityNamespace; + } + + public void setCapabilityNamespace(String capabilityNamespace) { + this.capabilityNamespace = capabilityNamespace; + } + + public boolean isInstalledOnly() { + return installedOnly; + } + + public void setInstalledOnly(boolean installedOnly) { + this.installedOnly = installedOnly; + } + + public Bundle getBundle() { + return bundle; + } + + public void setBundle(Bundle bundle) { + this.bundle = bundle; + }; + + } + +} diff --git a/platform/runtime/base/cellar-extensions/LICENSE.txt b/platform/runtime/base/cellar-extensions/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/base/cellar-extensions/pom.xml b/platform/runtime/base/cellar-extensions/pom.xml new file mode 100644 index 00000000..4c247a76 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/pom.xml @@ -0,0 +1,89 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime + base + 1.10.0 + + ru.entaxy.esb.platform.runtime.base + cellar-extensions + bundle + ENTAXY :: PLATFORM :: BASE :: CELLAR EXTENSIONS + ENTAXY :: PLATFORM :: BASE :: CELLAR EXTENSIONS + + + + ru.entaxy.platform.runtime.cellar.helper, + ru.entaxy.platform.runtime.cellar.sequence + + + org.apache.karaf.features.internal.model, + org.apache.felix.utils.version, + org.apache.felix.utils.properties, + org.apache.karaf.util, + ru.entaxy.platform.runtime.cellar.sequence.process, + ru.entaxy.platform.runtime.cellar.sequence.impl + + + + + + + org.apache.felix + org.apache.felix.configadmin + ${felix.configadmin.version} + + + + + + + org.apache.karaf.features + org.apache.karaf.features.core + ${karaf.version} + + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + org.apache.karaf.shell + org.apache.karaf.shell.core + + + + + + org.apache.karaf + org.apache.karaf.util + + + org.apache.karaf.cellar + org.apache.karaf.cellar.core + ${cellar.version} + + + + org.apache.karaf.cellar + org.apache.karaf.cellar.event + ${cellar.version} + + + + org.apache.karaf.cellar + org.apache.karaf.cellar.features + ${cellar.version} + + + + + + diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/CellarFeaturesHelper.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/CellarFeaturesHelper.java new file mode 100644 index 00000000..53f2afbd --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/CellarFeaturesHelper.java @@ -0,0 +1,738 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +/* + * 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. + */ +package ru.entaxy.platform.runtime.cellar.helper; + +import java.net.URI; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.management.openmbean.CompositeData; +import javax.management.openmbean.CompositeDataSupport; +import javax.management.openmbean.CompositeType; +import javax.management.openmbean.OpenType; +import javax.management.openmbean.SimpleType; +import javax.management.openmbean.TabularData; +import javax.management.openmbean.TabularDataSupport; +import javax.management.openmbean.TabularType; + +// import org.apache.karaf.cellar.bundle.BundleState; +import org.apache.karaf.cellar.core.CellarSupport; +import org.apache.karaf.cellar.core.ClusterManager; +import org.apache.karaf.cellar.core.Configurations; +import org.apache.karaf.cellar.core.Group; +import org.apache.karaf.cellar.core.GroupManager; +import org.apache.karaf.cellar.core.control.SwitchStatus; +import org.apache.karaf.cellar.core.event.EventProducer; +import org.apache.karaf.cellar.core.event.EventType; +import org.apache.karaf.cellar.features.ClusterFeaturesEvent; +import org.apache.karaf.cellar.features.ClusterRepositoryEvent; +import org.apache.karaf.cellar.features.Constants; +import org.apache.karaf.cellar.features.FeatureState; +import org.apache.karaf.cellar.features.management.CellarFeaturesMBean; +import org.apache.karaf.features.Feature; +import org.apache.karaf.features.FeatureEvent; +import org.apache.karaf.features.FeaturesService; +import org.apache.karaf.features.RepositoryEvent; +// import org.osgi.framework.BundleEvent; +import org.apache.karaf.features.internal.model.Features; +import org.apache.karaf.features.internal.model.JaxbUtil; +import org.osgi.service.cm.ConfigurationAdmin; + +/** + * Implementation of the Cellar Features MBean. + */ +public class CellarFeaturesHelper implements CellarFeaturesMBean { + + private ClusterManager clusterManager; + private GroupManager groupManager; + private EventProducer eventProducer; + private FeaturesService featuresService; + private ConfigurationAdmin configurationAdmin; + + public CellarFeaturesHelper() { + super(); + } + + public ClusterManager getClusterManager() { + return this.clusterManager; + } + + public void setClusterManager(ClusterManager clusterManager) { + this.clusterManager = clusterManager; + } + + public GroupManager getGroupManager() { + return this.groupManager; + } + + public void setGroupManager(GroupManager groupManager) { + this.groupManager = groupManager; + } + + public EventProducer getEventProducer() { + return eventProducer; + } + + public void setEventProducer(EventProducer eventProducer) { + this.eventProducer = eventProducer; + } + + public FeaturesService getFeaturesService() { + return featuresService; + } + + public void setFeaturesService(FeaturesService featuresService) { + this.featuresService = featuresService; + } + + public ConfigurationAdmin getConfigurationAdmin() { + return configurationAdmin; + } + + public void setConfigurationAdmin(ConfigurationAdmin configurationAdmin) { + this.configurationAdmin = configurationAdmin; + } + + @Override + public void installFeature(String groupName, String name, String version, boolean noRefresh, boolean noStart, + boolean noManage, boolean upgrade) throws Exception { + // check if the group exists + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + // check if the producer is ON + if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + throw new IllegalStateException("Cluster event producer is OFF"); + } + + // check if the feature is allowed outbound + CellarSupport support = new CellarSupport(); + support.setClusterManager(this.clusterManager); + support.setGroupManager(this.groupManager); + support.setConfigurationAdmin(this.configurationAdmin); + if (!support.isAllowed(group, Constants.CATEGORY, name, EventType.OUTBOUND)) { + throw new IllegalArgumentException( + "Feature " + name + " is blocked outbound for cluster group " + groupName); + } + + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + try { + + // get the features in the cluster group + Map clusterFeatures = + clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName); + + // check if the feature exist + FeatureState feature = null; + String key = null; + + String targetKey = null; + + // collect features to remove if upgrade = true + List featuresToRemove = new ArrayList<>(); + + for (String k : clusterFeatures.keySet()) { + FeatureState state = clusterFeatures.get(k); + key = k; + if (version == null) { + if (state.getName().equals(name)) { + feature = state; + targetKey = key; + break; + } + } else { + if (state.getName().equals(name)) { + if (state.getVersion().equals(version)) { + feature = state; + targetKey = key; + if (!upgrade) + break; + } else if (upgrade) + featuresToRemove.add(key); + } + } + } + + if (feature == null) { + if (version == null) + throw new IllegalArgumentException( + "Feature " + name + " doesn't exist in cluster group " + groupName); + else + throw new IllegalArgumentException( + "Feature " + name + "/" + version + " doesn't exist in cluster group " + groupName); + } + + // update the cluster group + + // set previous features uninstalled if we upgrade + // actual uninstallation will be executed on end nodes + if (upgrade) { + for (String featureKey : featuresToRemove) { + FeatureState fs = clusterFeatures.get(featureKey); + fs.setInstalled(false); + clusterFeatures.put(featureKey, fs); + } + + } + + // set current feature installed + feature.setInstalled(true); + clusterFeatures.put(targetKey, feature); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + + // broadcast the cluster event + ClusterFeaturesEvent event = new ClusterFeaturesEvent(name, version, noRefresh, noStart, noManage, upgrade, + FeatureEvent.EventType.FeatureInstalled); + event.setSourceGroup(group); + eventProducer.produce(event); + } + + @Override + public void installFeature(String groupName, String name, String version) throws Exception { + this.installFeature(groupName, name, version, false, false, false, false); + } + + @Override + public void installFeature(String groupName, String name) throws Exception { + this.installFeature(groupName, name, null); + } + + + @Override + public void installFeature(String groupName, String name, boolean noRefresh, boolean noStart, boolean noManage, + boolean upgrade) throws Exception { + this.installFeature(groupName, name, null, noRefresh, noStart, noManage, upgrade); + } + + @Override + public void uninstallFeature(String groupName, String name, String version) throws Exception { + this.uninstallFeature(groupName, name, version, false); + } + + @Override + public void uninstallFeature(String groupName, String name, String version, boolean noRefresh) throws Exception { + // check if the group exists + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + // check if the producer is ON + if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + throw new IllegalStateException("Cluster event producer is OFF"); + } + + // check if the feature is allowed outbound + CellarSupport support = new CellarSupport(); + support.setClusterManager(this.clusterManager); + support.setGroupManager(this.groupManager); + support.setConfigurationAdmin(this.configurationAdmin); + if (!support.isAllowed(group, Constants.CATEGORY, name, EventType.OUTBOUND)) { + throw new IllegalArgumentException( + "Feature " + name + " is blocked outbound for cluster group " + groupName); + } + + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + try { + + // get the features in the cluster group + Map clusterFeatures = + clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName); + + // check if the feature exist + FeatureState feature = null; + String key = null; + for (String k : clusterFeatures.keySet()) { + FeatureState state = clusterFeatures.get(k); + key = k; + if (version == null) { + if (state.getName().equals(name)) { + feature = state; + break; + } + } else { + if (state.getName().equals(name) && state.getVersion().equals(version)) { + feature = state; + break; + } + } + } + + if (feature == null) { + if (version == null) + throw new IllegalArgumentException( + "Feature " + name + " doesn't exist in cluster group " + groupName); + else + throw new IllegalArgumentException( + "Feature " + name + "/" + version + " doesn't exist in cluster group " + groupName); + } + + // update the cluster group + feature.setInstalled(false); + clusterFeatures.put(key, feature); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + + // broadcast the cluster event + ClusterFeaturesEvent event = new ClusterFeaturesEvent(name, version, noRefresh, false, false, false, + FeatureEvent.EventType.FeatureUninstalled); + event.setSourceGroup(group); + eventProducer.produce(event); + } + + @Override + public void uninstallFeature(String groupName, String name) throws Exception { + this.uninstallFeature(groupName, name, null, false); + } + + @Override + public void uninstallFeature(String groupName, String name, boolean noRefresh) throws Exception { + this.uninstallFeature(groupName, name, null, noRefresh); + } + + @Override + public TabularData getFeatures(String groupName) throws Exception { + + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + CellarSupport support = new CellarSupport(); + support.setClusterManager(clusterManager); + support.setGroupManager(groupManager); + support.setConfigurationAdmin(configurationAdmin); + + CompositeType featuresType = new CompositeType("Feature", "Karaf Cellar feature", + new String[] {"name", "version", "installed", "located", "blocked"}, + new String[] {"Name of the feature", "Version of the feature", + "Whether the feature is installed or not", + "Location of the feature (on the cluster or the local node)", + "Feature block policy"}, + new OpenType[] {SimpleType.STRING, SimpleType.STRING, SimpleType.BOOLEAN, SimpleType.STRING, + SimpleType.STRING}); + + TabularType tabularType = new TabularType("Features", "Table of all Karaf Cellar features", + featuresType, new String[] {"name", "version"}); + TabularData table = new TabularDataSupport(tabularType); + + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + try { + Map features = gatherFeatures(groupName); + if (features != null && !features.isEmpty()) { + for (ExtendedFeatureState feature : features.values()) { + + String located = ""; + boolean cluster = feature.isCluster(); + boolean local = feature.isLocal(); + if (cluster && local) + located = "cluster/local"; + if (cluster && !local) + located = "cluster"; + if (local && !cluster) + located = "local"; + + String blocked = ""; + boolean inbound = + support.isAllowed(group, Constants.CATEGORY, feature.getName(), EventType.INBOUND); + boolean outbound = + support.isAllowed(group, Constants.CATEGORY, feature.getName(), EventType.OUTBOUND); + if (!inbound && !outbound) + blocked = "in/out"; + if (!inbound && outbound) + blocked = "in"; + if (!outbound && inbound) + blocked = "out"; + + CompositeData data = new CompositeDataSupport(featuresType, + new String[] {"name", "version", "installed", "located", "blocked"}, + new Object[] {feature.getName(), feature.getVersion(), feature.getInstalled(), located, + blocked}); + table.put(data); + } + } + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + + return table; + } + + private Map gatherFeatures(String groupName) throws Exception { + Map features = new HashMap(); + + // get cluster features + Map clusterFeatures = + clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName); + for (String key : clusterFeatures.keySet()) { + FeatureState state = clusterFeatures.get(key); + ExtendedFeatureState extendedState = new ExtendedFeatureState(); + extendedState.setName(state.getName()); + extendedState.setInstalled(state.getInstalled()); + extendedState.setVersion(state.getVersion()); + extendedState.setCluster(true); + extendedState.setLocal(true); + features.put(key, extendedState); + } + + // get local features + for (Feature feature : featuresService.listFeatures()) { + String key = feature.getName() + "/" + feature.getVersion(); + if (features.containsKey(key)) { + ExtendedFeatureState extendedState = features.get(key); + if (featuresService.isInstalled(feature)) + extendedState.setInstalled(true); + extendedState.setLocal(true); + } else { + ExtendedFeatureState extendedState = new ExtendedFeatureState(); + extendedState.setCluster(false); + extendedState.setLocal(true); + extendedState.setName(feature.getName()); + extendedState.setVersion(feature.getVersion()); + if (featuresService.isInstalled(feature)) + extendedState.setInstalled(true); + else + extendedState.setInstalled(false); + features.put(key, extendedState); + } + } + + return features; + } + + @Override + public List getRepositories(String groupName) throws Exception { + // check if the group exists + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + // get the features repositories in the cluster group + Map clusterRepositories = + clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName); + + List result = new ArrayList(); + for (String clusterRepository : clusterRepositories.keySet()) { + result.add(clusterRepository); + } + + return result; + } + + @Override + public void addRepository(String groupName, String nameOrUrl) throws Exception { + this.addRepository(groupName, nameOrUrl, null, false); + } + + @Override + public void addRepository(String groupName, String nameOrUrl, String version) throws Exception { + this.addRepository(groupName, nameOrUrl, version, false); + } + + @Override + public void addRepository(String groupName, String nameOrUrl, String version, boolean install) throws Exception { + // check if the group exists + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + // check if the event producer is ON + if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + throw new IllegalStateException("Cluster event producer is OFF"); + } + + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + try { + // get the features repositories in the cluster group + Map clusterRepositories = + clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName); + // get the features in the cluster group + Map clusterFeatures = + clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName); + + URI uri = featuresService.getRepositoryUriFor(nameOrUrl, version); + if (uri == null) { + uri = new URI(nameOrUrl); + } + + // check if the URL is already registered + String name = null; + for (String repository : clusterRepositories.keySet()) { + if (repository.equals(uri)) { + name = clusterRepositories.get(repository); + break; + } + } + if (name == null) { + // parsing the features repository to get content + Features repository = JaxbUtil.unmarshal(uri.toASCIIString(), true); + + // update the cluster group + clusterRepositories.put(uri.toString(), repository.getName()); + + // update the features in the cluster group + for (Feature feature : repository.getFeature()) { + FeatureState state = new FeatureState(); + state.setName(feature.getName()); + state.setVersion(feature.getVersion()); + state.setInstalled(featuresService.isInstalled(feature)); + clusterFeatures.put(feature.getName() + "/" + feature.getVersion(), state); + } + + // broadcast the cluster event + ClusterRepositoryEvent event = + new ClusterRepositoryEvent(uri.toString(), RepositoryEvent.EventType.RepositoryAdded); + event.setInstall(install); + event.setSourceGroup(group); + event.setSourceNode(clusterManager.getNode()); + eventProducer.produce(event); + } else { + throw new IllegalArgumentException("Features repository URL " + uri + " already registered"); + } + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + @Override + public void refreshRepository(String groupName, String nameOrUrl) throws Exception { + // check if the group exists + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + // check if the event producer is ON + if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + throw new IllegalStateException("Cluster event producer is OFF"); + } + + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + try { + String uri = null; + if (nameOrUrl != null) { + // get the cluster features repositories + Map clusterFeaturesRepositories = + clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName); + + for (Map.Entry entry : clusterFeaturesRepositories.entrySet()) { + if (entry.getKey().equals(nameOrUrl) || entry.getValue().equals(nameOrUrl)) { + uri = entry.getKey(); + break; + } + } + + if (uri == null) { + throw new IllegalArgumentException( + "Features repository " + nameOrUrl + " doesn't exist in cluster group " + groupName); + } + } + + // broadcast the cluster event + ClusterRepositoryEvent event = new ClusterRepositoryEvent(uri, RepositoryEvent.EventType.RepositoryAdded); + event.setRefresh(true); + event.setSourceGroup(group); + event.setSourceNode(clusterManager.getNode()); + eventProducer.produce(event); + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + @Override + public void removeRepository(String groupName, String repository) throws Exception { + this.removeRepository(groupName, repository, false); + } + + @Override + public void removeRepository(String groupName, String repo, boolean uninstall) throws Exception { + // check if the group exists + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + // check if the event producer is ON + if (eventProducer.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + throw new IllegalStateException("Cluster event producer is OFF"); + } + + // get the features repositories in the cluster group + Map clusterRepositories = + clusterManager.getMap(Constants.REPOSITORIES_MAP + Configurations.SEPARATOR + groupName); + // get the features in the cluster group + Map clusterFeatures = + clusterManager.getMap(Constants.FEATURES_MAP + Configurations.SEPARATOR + groupName); + + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + try { + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + + List urls = new ArrayList(); + Pattern pattern = Pattern.compile(repo); + for (String repositoryUrl : clusterRepositories.keySet()) { + String repositoryName = clusterRepositories.get(repositoryUrl); + if (repositoryName != null && !repositoryName.isEmpty()) { + // repository has name, try regex on the name + Matcher nameMatcher = pattern.matcher(repositoryName); + if (nameMatcher.matches()) { + urls.add(repositoryUrl); + } else { + // the name regex doesn't match, fallback to repository URI regex + Matcher uriMatcher = pattern.matcher(repositoryUrl); + if (uriMatcher.matches()) { + urls.add(repositoryUrl); + } + } + } else { + // the repository name is not defined, use repository URI regex + Matcher uriMatcher = pattern.matcher(repositoryUrl); + if (uriMatcher.matches()) { + urls.add(repositoryUrl); + } + } + } + + for (String url : urls) { + // looking for the URL in the list + boolean found = false; + for (String repository : clusterRepositories.keySet()) { + if (repository.equals(url)) { + found = true; + break; + } + } + if (found) { + Features repositoryModel = JaxbUtil.unmarshal(url, true); + + // update the features repositories in the cluster group + clusterRepositories.remove(url); + + // update the features in the cluster group + for (Feature feature : repositoryModel.getFeature()) { + clusterFeatures.remove(feature.getName() + "/" + feature.getVersion()); + } + + // broadcast a cluster event + ClusterRepositoryEvent event = + new ClusterRepositoryEvent(url, RepositoryEvent.EventType.RepositoryRemoved); + event.setUninstall(uninstall); + event.setSourceGroup(group); + event.setSourceNode(clusterManager.getNode()); + eventProducer.produce(event); + } else { + throw new IllegalArgumentException( + "Features repository URL " + url + " not found in cluster group " + groupName); + } + } + } finally { + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + } + + @Override + public void block(String groupName, String featurePattern, boolean whitelist, boolean blacklist, boolean in, + boolean out) throws Exception { + + Group group = groupManager.findGroupByName(groupName); + if (group == null) { + throw new IllegalArgumentException("Cluster group " + groupName + " doesn't exist"); + } + + CellarSupport support = new CellarSupport(); + support.setClusterManager(clusterManager); + support.setGroupManager(groupManager); + support.setConfigurationAdmin(configurationAdmin); + + if (in) { + if (whitelist) + support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.INBOUND, + featurePattern); + if (blacklist) + support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.INBOUND, + featurePattern); + } + if (out) { + if (whitelist) + support.switchListEntry(Configurations.WHITELIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, + featurePattern); + if (blacklist) + support.switchListEntry(Configurations.BLACKLIST, groupName, Constants.CATEGORY, EventType.OUTBOUND, + featurePattern); + } + + } + + class ExtendedFeatureState extends FeatureState { + + private boolean cluster; + private boolean local; + + public boolean isCluster() { + return cluster; + } + + public void setCluster(boolean cluster) { + this.cluster = cluster; + } + + public boolean isLocal() { + return local; + } + + public void setLocal(boolean local) { + this.local = local; + } + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/HelperFactory.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/HelperFactory.java new file mode 100644 index 00000000..bc32eef6 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/HelperFactory.java @@ -0,0 +1,91 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.helper; + +import java.util.Collections; +import java.util.Map; + +import org.apache.karaf.cellar.core.ClusterManager; +import org.apache.karaf.cellar.core.GroupManager; +import org.apache.karaf.cellar.core.event.EventProducer; +import org.apache.karaf.cellar.features.management.CellarFeaturesMBean; +import org.apache.karaf.features.FeaturesService; +import org.osgi.service.cm.ConfigurationAdmin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class HelperFactory { + + private static final Logger LOG = LoggerFactory.getLogger(HelperFactory.class); + + public static T createHelper(Class targetClass) { + + return createHelper(targetClass, Collections.emptyMap()); + + } + + public static T createHelper(Class targetClass, Map parameters) { + + if (CellarFeaturesMBean.class.equals(targetClass)) + return (T) createFeaturesHelper(parameters); + + return null; + + } + + + protected static CellarFeaturesHelper createFeaturesHelper(Map parameters) { + CellarFeaturesHelper result = new CellarFeaturesHelper(); + + if (parameters.containsKey(ClusterManager.class.getName())) + result.setClusterManager((ClusterManager) parameters.get(ClusterManager.class.getName())); + else if (Services.INSTANCE != null) + result.setClusterManager(Services.INSTANCE.clusterManager); + + if (parameters.containsKey(ConfigurationAdmin.class.getName())) + result.setConfigurationAdmin((ConfigurationAdmin) parameters.get(ConfigurationAdmin.class.getName())); + else if (Services.INSTANCE != null) + result.setConfigurationAdmin(Services.INSTANCE.configurationAdmin); + + if (parameters.containsKey(EventProducer.class.getName())) + result.setEventProducer((EventProducer) parameters.get(EventProducer.class.getName())); + else if (Services.INSTANCE != null) + result.setEventProducer(Services.INSTANCE.eventProducer); + + if (parameters.containsKey(FeaturesService.class.getName())) + result.setFeaturesService((FeaturesService) parameters.get(FeaturesService.class.getName())); + else if (Services.INSTANCE != null) + result.setFeaturesService(Services.INSTANCE.featuresService); + + if (parameters.containsKey(GroupManager.class.getName())) + result.setGroupManager((GroupManager) parameters.get(GroupManager.class.getName())); + else if (Services.INSTANCE != null) + result.setGroupManager(Services.INSTANCE.groupManager); + + return result; + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/Services.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/Services.java new file mode 100644 index 00000000..06ed3a0e --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/helper/Services.java @@ -0,0 +1,69 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.helper; + +import org.apache.karaf.cellar.core.ClusterManager; +import org.apache.karaf.cellar.core.GroupManager; +import org.apache.karaf.cellar.core.event.EventProducer; +import org.apache.karaf.features.FeaturesService; +import org.osgi.service.cm.ConfigurationAdmin; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; + +@Component(service = Services.class, immediate = true) +public class Services { + + public static Services INSTANCE = null; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC) + public volatile ClusterManager clusterManager; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC) + public volatile ConfigurationAdmin configurationAdmin; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC) + public volatile EventProducer eventProducer; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC) + public volatile FeaturesService featuresService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC) + public volatile GroupManager groupManager; + + @Activate + public void activate() { + INSTANCE = this; + } + + @Deactivate + public void deactivate() { + INSTANCE = null; + } +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceEvent.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceEvent.java new file mode 100644 index 00000000..07a3621c --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceEvent.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.apache.karaf.cellar.core.event.Event; + +public class CellarSequenceEvent extends Event implements Serializable { + + List sequence = new ArrayList<>(); + + boolean waitLast = true; + + public CellarSequenceEvent(String sequenceId) { + super(sequenceId); + } + + public List getSequence() { + return sequence; + } + + public boolean isWaitLast() { + return waitLast; + } + + public void setWaitLast(boolean waitLast) { + this.waitLast = waitLast; + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceItemEvent.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceItemEvent.java new file mode 100644 index 00000000..35deeb5b --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceItemEvent.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence; + +import org.apache.karaf.cellar.core.event.Event; + +public class CellarSequenceItemEvent extends Event { + + Event event; + + // -1 - infinite + // 0 - don't wait + // x - time in mills + int operationTimeout = -1; + + public CellarSequenceItemEvent(String id, Event event) { + super(id); + this.event = event; + } + + public Event getEvent() { + return event; + } + + public int getOperationTimeout() { + return operationTimeout; + } + + public void setOperationTimeout(int operationTimeout) { + this.operationTimeout = operationTimeout; + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceManager.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceManager.java new file mode 100644 index 00000000..7ec41184 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/CellarSequenceManager.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence; + +public interface CellarSequenceManager { + + void releaseSequence(String sequenceId); + + void produceSequence(String sequenceId); + + T getSequencedHelper(String sequenceId, Class targetClass); + + SequenceBuilder getSequence(String sequenceId); + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/SequenceBuilder.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/SequenceBuilder.java new file mode 100644 index 00000000..8853426a --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/SequenceBuilder.java @@ -0,0 +1,60 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence; + +import org.apache.karaf.cellar.core.control.BasicSwitch; +import org.apache.karaf.cellar.core.control.Switch; +import org.apache.karaf.cellar.core.event.Event; +import org.apache.karaf.cellar.core.event.EventProducer; + +public class SequenceBuilder implements EventProducer { + + protected CellarSequenceEvent cellarSequenceEvent; + + protected Switch eventSwitch = new BasicSwitch(getClass().getName()); + + public SequenceBuilder(String sequenceId) { + super(); + this.cellarSequenceEvent = new CellarSequenceEvent(sequenceId); + } + + public CellarSequenceEvent getEvent() { + return cellarSequenceEvent; + } + + @Override + public Switch getSwitch() { + return eventSwitch; + } + + @Override + public void produce(Event event) { + + cellarSequenceEvent.sequence.add(new CellarSequenceItemEvent(event.getId(), event)); + + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/SequenceEventHandler.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/SequenceEventHandler.java new file mode 100644 index 00000000..cd069451 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/SequenceEventHandler.java @@ -0,0 +1,65 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence; + +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.apache.karaf.cellar.core.control.BasicSwitch; +import org.apache.karaf.cellar.core.control.Switch; +import org.apache.karaf.cellar.core.event.EventHandler; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.runtime.cellar.sequence.process.SequenceTask; + +@Component(service = EventHandler.class, immediate = true) +public class SequenceEventHandler implements EventHandler { + + private static final Logger LOG = LoggerFactory.getLogger(SequenceEventHandler.class); + + protected Switch eventSwitch = new BasicSwitch(getClass().getName()); + + protected ExecutorService threadPool = Executors.newCachedThreadPool(); + + @Override + public Class getType() { + return CellarSequenceEvent.class; + } + + @Override + public Switch getSwitch() { + return eventSwitch; + } + + @Override + public void handle(CellarSequenceEvent event) { + LOG.info("Received event: " + event.getId()); + threadPool.execute(new SequenceTask(event, Thread.currentThread().getContextClassLoader())); + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/impl/CellarSequenceManagerImpl.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/impl/CellarSequenceManagerImpl.java new file mode 100644 index 00000000..8d5ea714 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/impl/CellarSequenceManagerImpl.java @@ -0,0 +1,88 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.karaf.cellar.core.event.EventProducer; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; + +import ru.entaxy.platform.runtime.cellar.helper.HelperFactory; +import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceManager; +import ru.entaxy.platform.runtime.cellar.sequence.SequenceBuilder; + +@Component(service = CellarSequenceManager.class, immediate = true) +public class CellarSequenceManagerImpl implements CellarSequenceManager { + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC) + protected volatile EventProducer eventProducer; + + protected final Map sequences = new HashMap<>(); + protected Object sequencesLock = new Object(); + + @Override + public T getSequencedHelper(String sequenceId, Class targetClass) { + + Map properties = new HashMap<>(); + properties.put(EventProducer.class.getName(), getSequenceBuilder(sequenceId)); + + return HelperFactory.createHelper(targetClass, properties); + + } + + @Override + public void produceSequence(String sequenceId) { + synchronized (sequencesLock) { + if (sequences.containsKey(sequenceId)) + eventProducer.produce(sequences.get(sequenceId).getEvent()); + } + } + + @Override + public void releaseSequence(String sequenceId) { + synchronized (sequencesLock) { + sequences.remove(sequenceId); + } + } + + @Override + public SequenceBuilder getSequence(String sequenceId) { + return getSequenceBuilder(sequenceId); + } + + protected SequenceBuilder getSequenceBuilder(String sequenceId) { + synchronized (sequencesLock) { + if (!sequences.containsKey(sequenceId)) + sequences.put(sequenceId, new SequenceBuilder(sequenceId)); + return sequences.get(sequenceId); + } + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/ChangeListener.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/ChangeListener.java new file mode 100644 index 00000000..04e6e20b --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/ChangeListener.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence.process; + +public interface ChangeListener { + + public interface CallBack { + void success(); + + default void fail() {}; + + default void timeout() {}; + } + + void setCallback(CallBack callBack); + + void register(); + + void unregister(); + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/ChangeListenerFactory.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/ChangeListenerFactory.java new file mode 100644 index 00000000..2aa72655 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/ChangeListenerFactory.java @@ -0,0 +1,143 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence.process; + +import org.apache.karaf.cellar.core.event.Event; +import org.apache.karaf.cellar.features.ClusterFeaturesEvent; +import org.apache.karaf.cellar.features.ClusterRepositoryEvent; +import org.apache.karaf.features.FeatureEvent; +import org.apache.karaf.features.FeaturesListener; +import org.apache.karaf.features.RepositoryEvent; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.runtime.cellar.helper.Services; + +public class ChangeListenerFactory { + + private static final Logger LOG = LoggerFactory.getLogger(ChangeListenerFactory.class); + + public static ChangeListener create(Event originEvent) { + + if (originEvent instanceof ClusterRepositoryEvent) { + return new RepositoryListener((ClusterRepositoryEvent) originEvent); + } + + if (originEvent instanceof ClusterFeaturesEvent) { + return new FeatureListener((ClusterFeaturesEvent) originEvent); + } + + return null; + } + + protected static abstract class AbstractChangeListener implements ChangeListener { + + protected CallBack callBack; + + protected T originEvent; + + public AbstractChangeListener(T event) { + super(); + this.originEvent = event; + } + + @Override + public void setCallback(CallBack callBack) { + this.callBack = callBack; + } + + } + + protected static class RepositoryListener extends AbstractChangeListener + implements FeaturesListener { + + public RepositoryListener(ClusterRepositoryEvent event) { + super(event); + } + + @Override + public void register() { + Services.INSTANCE.featuresService.registerListener(this); + + } + + @Override + public void unregister() { + Services.INSTANCE.featuresService.unregisterListener(this); + } + + @Override + public void featureEvent(FeatureEvent event) { + // ignore + } + + @Override + public void repositoryEvent(RepositoryEvent event) { + if (event.getRepository().getURI().toString().equals(originEvent.getId())) { + if (originEvent.getType().equals(event.getType())) { + LOG.debug("REPOSITORY EVENT for [{}]", originEvent.getId()); + callBack.success(); + } + } + } + + } + protected static class FeatureListener extends AbstractChangeListener + implements FeaturesListener { + + public FeatureListener(ClusterFeaturesEvent event) { + super(event); + } + + @Override + public void register() { + Services.INSTANCE.featuresService.registerListener(this); + + } + + @Override + public void unregister() { + Services.INSTANCE.featuresService.unregisterListener(this); + } + + @Override + public void featureEvent(FeatureEvent event) { + if (event.getFeature().getId().equals(originEvent.getId())) { + if (originEvent.getType().equals(event.getType())) { + LOG.debug("FEATURE EVENT for [{}]", originEvent.getId()); + callBack.success(); + } + } + } + + @Override + public void repositoryEvent(RepositoryEvent event) { + // ignore + } + + } + +} diff --git a/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/SequenceTask.java b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/SequenceTask.java new file mode 100644 index 00000000..914f6e03 --- /dev/null +++ b/platform/runtime/base/cellar-extensions/src/main/java/ru/entaxy/platform/runtime/cellar/sequence/process/SequenceTask.java @@ -0,0 +1,276 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cellar-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.cellar.sequence.process; + +import java.util.ArrayDeque; +import java.util.Collections; +import java.util.concurrent.Callable; +import java.util.concurrent.CancellationException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.apache.karaf.cellar.core.event.Event; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.runtime.cellar.helper.Services; +import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceEvent; +import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceItemEvent; + +public class SequenceTask implements Runnable, ChangeListener.CallBack { + + private static final Logger LOG = LoggerFactory.getLogger(SequenceTask.class); + + protected enum EVENT_RESULT { + NONE, + SUCCESS, + ERROR, + TIMEOUT + } + + protected CellarSequenceEvent sequence; + + protected ArrayDeque events; + + protected Object eventsLock = new Object(); + + protected CellarSequenceItemEvent currentEvent; + + protected ChangeListener currentChangeListener; + + protected Object currentChangeListenerLock = new Object(); + + protected ExecutorService threadPool = Executors.newCachedThreadPool(); + + protected Future future; + + protected Object futureLock = new Object(); + + protected EVENT_RESULT currentResult; + + protected Object currentResultLock = new Object(); + + public SequenceTask(CellarSequenceEvent event, ClassLoader classLoader) { + super(); + this.sequence = event; + events = new ArrayDeque<>(this.sequence.getSequence()); + Thread.currentThread().setContextClassLoader(classLoader); + LOG.debug("\n--> CREATED SequenceTask for [{}]", sequence.getId()); + } + + protected void updateCurrentResult(EVENT_RESULT newResult) { + synchronized (currentResultLock) { + LOG.debug("\n--> CURRENT RESULT set to [{}]", newResult.name()); + this.currentResult = newResult; + } + } + + protected void resetResult() { + updateCurrentResult(EVENT_RESULT.NONE); + } + + @Override + public void run() { + + LOG.debug("\n--> RUNNING SequenceTask for [{}]", sequence.getId()); + + resetResult(); + + // global limit for operation = 5 min + long maxExecution = 300000; + long executionStep = 500; + + while (!events.isEmpty()) { + next(); + long executionPeriod = 0; + while (EVENT_RESULT.NONE.equals(currentResult) && (executionPeriod < maxExecution)) { + try { + LOG.debug("\n--> WAITING FOR RESULT [{}]", currentEvent == null ? "null" : currentEvent.getId()); + executionPeriod += executionStep; + Thread.sleep(executionStep); + } catch (InterruptedException e) { + LOG.debug("\n--> INTERRUPTED WAITING FOR RESULT [{}]", + currentEvent == null ? "null" : currentEvent.getId()); + updateCurrentResult(EVENT_RESULT.ERROR); + } + } + + // maxExecution reached + if (EVENT_RESULT.NONE.equals(currentResult)) { + LOG.debug("\n--> CURRENT RESULT is NONE for [{}]", + currentEvent == null ? "null" : currentEvent.getId()); + updateCurrentResult(EVENT_RESULT.ERROR); + } + + if (EVENT_RESULT.SUCCESS.equals(currentResult)) { + LOG.debug("\n--> CURRENT RESULT is SUCCESS for [{}]", + currentEvent == null ? "null" : currentEvent.getId()); + resetResult(); + } else { + LOG.debug("\n--> CURRENT RESULT is [{}] for [{}]", + currentResult == null ? "null" : currentResult.name(), + currentEvent == null ? "null" : currentEvent.getId()); + LOG.error("Failed processing sequence event"); + return; + } + } + + } + + protected boolean haveToWait() { + if (events.isEmpty() && !sequence.isWaitLast()) + return false; + return true; + } + + protected void next() { + synchronized (eventsLock) { + LOG.debug("\n--> NEXT event"); + currentEvent = null; + currentChangeListener = null; + + if (events.isEmpty()) + return; + + currentEvent = events.pop(); + LOG.debug("\n--> CURRENT event is [{}]", currentEvent == null ? "null" : currentEvent.getId()); + + if (haveToWait()) { + + LOG.debug("\n--> WILL WAIT for result for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + + currentChangeListener = ChangeListenerFactory.create(currentEvent.getEvent()); + if (currentChangeListener == null) { + updateCurrentResult(EVENT_RESULT.ERROR); + return; + } + + currentChangeListener.setCallback(this); + currentChangeListener.register(); + + Callable task = new Callable() { + + @Override + public Object call() throws Exception { + Event eventToSend = currentEvent.getEvent(); + eventToSend.setDestination(Collections.singleton(Services.INSTANCE.clusterManager.getNode())); + + LOG.debug("\n--> EVENT SENT: [{}]:[{}]", eventToSend.getClass().getName(), eventToSend.getId()); + Services.INSTANCE.eventProducer.produce(eventToSend); + + // timeout for operation + // Thread.sleep(100000); + return null; + } + }; + + future = threadPool.submit(task); + try { + Object result = future.get(100, TimeUnit.SECONDS); + LOG.debug("\n--> RESULT RECEIVED for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + } catch (TimeoutException timeoutEx) { + LOG.debug("\n--> TimeoutException for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + updateCurrentResult(EVENT_RESULT.TIMEOUT); + unregisterChangeListener(); + } catch (InterruptedException ignore) { + // NOOP + LOG.debug("\n--> InterruptedException for [{}]", + currentEvent == null ? "null" : currentEvent.getId()); + } catch (CancellationException ignore) { + // NOOP + LOG.debug("\n--> CancellationException for [{}]", + currentEvent == null ? "null" : currentEvent.getId()); + } catch (Exception e) { + LOG.debug("\n--> Exception for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + LOG.error("Exception on next event processing", e); + updateCurrentResult(EVENT_RESULT.ERROR); + unregisterChangeListener(); + } finally { + // unregisterChangeListener(); + } + } else { + LOG.debug("\n--> WILL NOT WAIT for result for [{}]", + currentEvent == null ? "null" : currentEvent.getId()); + + threadPool.execute(new Runnable() { + + @Override + public void run() { + Event eventToSend = currentEvent.getEvent(); + eventToSend.setDestination(Collections.singleton(Services.INSTANCE.clusterManager.getNode())); + Services.INSTANCE.eventProducer.produce(eventToSend); + LOG.debug("\n--> EVENT SENT: [{}]:[{}]", eventToSend.getClass().getName(), eventToSend.getId()); + } + }); + updateCurrentResult(EVENT_RESULT.SUCCESS); + } + } + } + + protected void unregisterChangeListener() { + synchronized (currentChangeListenerLock) { + if (currentChangeListener != null) + currentChangeListener.unregister(); + } + } + + @Override + public void success() { + LOG.debug("\n--> CALLED 'success' for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + synchronized (futureLock) { + if (this.future != null) + future.cancel(true); + } + unregisterChangeListener(); + updateCurrentResult(EVENT_RESULT.SUCCESS); + } + + @Override + public void timeout() { + LOG.debug("\n--> CALLED 'timeout' for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + synchronized (futureLock) { + if (this.future != null) + future.cancel(true); + } + unregisterChangeListener(); + updateCurrentResult(EVENT_RESULT.TIMEOUT); + } + + @Override + public void fail() { + LOG.debug("\n--> CALLED 'fail' for [{}]", currentEvent == null ? "null" : currentEvent.getId()); + synchronized (futureLock) { + if (this.future != null) + future.cancel(true); + } + unregisterChangeListener(); + updateCurrentResult(EVENT_RESULT.ERROR); + } + +} diff --git a/platform/runtime/base/connecting/generator/generator-api/src/main/java/ru/entaxy/base/generator/template/LegacyTemplate.java b/platform/runtime/base/connecting/generator/generator-api/src/main/java/ru/entaxy/base/generator/template/LegacyTemplate.java new file mode 100644 index 00000000..d15f2a4f --- /dev/null +++ b/platform/runtime/base/connecting/generator/generator-api/src/main/java/ru/entaxy/base/generator/template/LegacyTemplate.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * generator-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.base.generator.template; + +import java.net.URL; +import java.util.Map; + +import org.osgi.framework.BundleContext; + +public interface LegacyTemplate { + String getTemplateName(); + + URL getTemplateLocation(); + + Map getParams(); + + void setBundleContext(BundleContext bundleContext); + + String getTemplateFileName(); +} diff --git a/platform/runtime/base/connecting/generator/generator-api/src/main/java/ru/entaxy/base/generator/template/exception/TemplateNotFound.java b/platform/runtime/base/connecting/generator/generator-api/src/main/java/ru/entaxy/base/generator/template/exception/TemplateNotFound.java new file mode 100644 index 00000000..3fe2a33e --- /dev/null +++ b/platform/runtime/base/connecting/generator/generator-api/src/main/java/ru/entaxy/base/generator/template/exception/TemplateNotFound.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.base.generator.template.exception; + +public class TemplateNotFound extends RuntimeException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public TemplateNotFound() { + super(); + } + + public TemplateNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public TemplateNotFound(String message, Throwable cause) { + super(message, cause); + } + + public TemplateNotFound(String message) { + super(message); + } + + public TemplateNotFound(Throwable cause) { + super(cause); + } + +} diff --git a/platform/runtime/base/logging/LICENSE.txt b/platform/runtime/base/logging/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/base/logging/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/base/logging/cef-logger-layout/LICENSE.txt b/platform/runtime/base/logging/cef-logger-layout/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/base/logging/cef-logger-layout/pom.xml b/platform/runtime/base/logging/cef-logger-layout/pom.xml new file mode 100644 index 00000000..10146897 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/pom.xml @@ -0,0 +1,98 @@ + + 4.0.0 + + ru.entaxy.platform + logging + 1.10.0 + + ru.entaxy.platform.logging + cef-logger-layout + bundle + ENTAXY :: LOGGING :: CEF LOGGER + ENTAXY :: LOGGING :: CEF LOGGER + + + ru.emdev.cef + !ru.emdev.cef + + + + + org.apache.logging.log4j + log4j-api + 2.13.2 + compile + + org.apache.logging.log4j + log4j-core + 2.13.2 + compile + + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-databind + + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + + org.mockito + mockito-all + 1.10.19 + test + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + log4j-plugin-processor + + compile + + process-classes + + only + + org.apache.logging.log4j.core.config.plugins.processor.PluginProcessor + + + + + + + + + org.apache.felix + maven-bundle-plugin + true + + + org.ops4j.pax.logging.pax-logging-log4j2 + META-INF=${project.build.outputDirectory}/META-INF + * + + + + + + + + diff --git a/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/AuditEvent.java b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/AuditEvent.java new file mode 100644 index 00000000..8bfa0a4c --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/AuditEvent.java @@ -0,0 +1,94 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import static java.util.regex.Pattern.compile; + +import java.util.regex.Pattern; + +public enum AuditEvent { + APP_OWNER_UPDATED("app_owner_updated", "Owner of application updated", compile( + "(?^Successfully updated the owner of application ((?!from).*) from ((?!to).*) to (?.*).$)")), + COMMON_ACTION_RESULT("action", "Common action result", compile( + "^Initiator : (?[^|]*) \\| Action : (?[^|]*) \\| (?Target : ([^|]*) \\| Data : ([^|]*) \\| Result : (.*)$)")), + COMMON_ACTION_OUTCOME("action", "Common action outcome", compile( + "^Initiator=(?(?! Action).*) Action=(?(?! Target).*) (?Target=((?! Data).*) Data=((?! Outcome).*) Outcome=((?!Error=).*)$)")), + COMMON_ACTION_ERROR("action", "Common action error", compile( + "^Initiator=(?(?! Action).*) Action=(?(?! Target).*) (?Target=((?! Data).*) Data=((?! Outcome).*) Outcome=Failure Error=(.*)$)")), + COMMON_ACTION_CLAIMS("action", "Common action claims", compile( + "^Initiator : (?[^|]*) \\| Action : (?[^|]*) \\| (?Target : ([^|]*) \\| Claims : (.*)$)")), + SIGN_WRAPPING_ATTACK("attack", "Possible Signature Wrapping Attack", compile( + "(?^Signature do not confirm to SAML signature profile. Possible XML Signature Wrapping (?Attack)!$)")), + LOGGED_OUT("auth", "Logged out", compile( + "(?^'(?(?!@).*)@((?! ).*) \\[((?!]).*)]' logged out at (?((?! delegated).*))$)")), + LOGGED_OUT_DELEGATED("auth", "Logged out", compile( + "(?^'(?(?!@).*)@((?! ).*) \\[((?!]).*)]' logged out at (?((?! delegated).*)) delegated by (.*)$)")), + LOGIN_FAILED("auth", "Unauthorized login attempt", compile( + "(?^Login failed\\. Unauthorized login attempt '(?(?!\\[).*)\\[((?!]).*)]' at (?.*)$)")), + LOGIN("auth", "Login success", + compile("(?^'(?[^@]*)@([^ ]*) \\[((?!]).*)]' logged in at (?.*)$)")), + LOGIN_NULL_DOMAIN("auth", "Null domain login attempt", + compile("(?^User with null domain tried to login\\.$)")), + LOGIN_FROM_IP("auth", "Login success from ip", compile( + "(?^'(?(?!@).*)@((?! ).*) \\[((?!]).*)]' logged in at (?(?! from).*) from IP address (?.*)$)")), + JMX_AUTHENTICATED("auth", "User authenticated to JMX", compile( + "(?^User (?(?! successfully).*) successfully authenticated to perform JMX operations\\.$)")), + JMX_AUTHORIZED("auth", "User authorized to JMX", compile( + "(?^User : (?(?! successfully).*) successfully authorized to perform JMX operations\\.$)")), + JMX_UNAUTHORIZED("auth", "Unauthorized access attempt to JMX", compile( + "(?^Unauthorized access attempt to JMX operation\\. $)")), + USER_NOT_AUTHORIZED("auth", "Unauthorized attempt to read the resource", compile( + "(?^User (?(?! is).*) is not authorized to read the resource (.*)$)")), + CSRF_ATTACK_WITH_HEADER("attack", "Possible CSRF attack", compile( + "(?^Possible CSRF attack. Refer header : (.*)$)")), + CSRF_ATTACK_WITHOUT_HEADER("attack", "Possible CSRF attack", compile( + "(?^Possible CSRF attack. Request to '([^']*)' does not have a Referer header$)")), + THREAT_ATTACK("attack", "Threat detected", compile( + "(?^(.*)Threat detected in (.*)$)")); + + private final Pattern pattern; + private final String eventName; + private final String eventType; + + + AuditEvent(String eventType, String eventName, Pattern pattern) { + this.eventType = eventType; + this.eventName = eventName; + this.pattern = pattern; + } + + public Pattern getPattern() { + return pattern; + } + + public String getEventName() { + return eventName; + } + + public String getEventType() { + return eventType; + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/AuditLayout.java b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/AuditLayout.java new file mode 100644 index 00000000..0ff7685c --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/AuditLayout.java @@ -0,0 +1,410 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import static java.util.Objects.nonNull; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.ZonedDateTime; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.layout.AbstractStringLayout; +import org.apache.logging.log4j.core.lookup.StrSubstitutor; +import org.apache.logging.log4j.message.Message; +import org.apache.logging.log4j.util.Strings; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class AuditLayout extends AbstractStringLayout { + /** + * Формат сообщения и версия + */ + public static final String CEF_VERSION = "cefVersion"; + + /** + * Производитель ПО + */ + public static final String VENDOR = "vendor"; + /** + * Имя компонента + */ + public static final String PRODUCT = "product"; + /** + * Версия компонента + */ + public static final String VERSION = "version"; + /** + * Версия компонента + */ + public static final String EVENT_TYPE = "typ"; + /** + * Название события + */ + public static final String EVENT_NAME = "eventName"; + /** + * Важность события + */ + public static final String SEVERITY = "severity"; + + public static final List HEADER_FIELDS = + Arrays.asList(CEF_VERSION, VENDOR, PRODUCT, VERSION, EVENT_TYPE, EVENT_NAME, SEVERITY); + /** + * Дополнительные поля + */ + public static final String EXTENSION = "extension"; + + /** + * IP пользователя + */ + public static final String EXT_SRC = "src"; + /** + * IP сервиса + */ + public static final String EXT_DST = "dst"; + + /** + * хост пользователя + */ + public static final String EXT_SHOST = "shost"; + + /** + * SID пользователя + */ + public static final String EXT_SUID = "suid"; + /** + * имя пользователя + */ + public static final String EXT_SOURCE_USER_NAME = "suser"; + /** + * описание события + */ + public static final String EXT_MSG = "msg"; + /** + * время события + */ + public static final String EXT_END = "end"; + + public static final List EXT_FIELDS = + Arrays.asList(EXT_SRC, EXT_DST, EXT_SHOST, EXT_SUID, EXT_SOURCE_USER_NAME, EXT_MSG, EXT_END); + + public static final List ALL_FIELDS = + Stream.concat(HEADER_FIELDS.stream(), EXT_FIELDS.stream()).collect(Collectors.toList()); + + public static final Map DEFAULTS = new HashMap() { + { + put(CEF_VERSION, "0"); + put(VENDOR, "EMDEV"); + put(PRODUCT, "ENTAXY"); + put(VERSION, "1.10.0"); + put(EVENT_TYPE, "common"); + put(EVENT_NAME, "common event"); + + put(EXT_SRC, ""); + put(EXT_DST, ""); + put(EXT_SHOST, ""); + put(EXT_SUID, ""); + put(EXT_SOURCE_USER_NAME, ""); + put(EXT_MSG, ""); + put(EXT_END, ""); + } + }; + + public static final Map SEVERITY_BY_EVENT_NAME = new HashMap() { + { + put("Add-User", "6"); + put("Delete-User", "8"); + put("Delete-User-Claim-Values", "8"); + put("Delete-User-Claim-Value", "8"); + put("Disable user account", "8"); + put("Enable user account", "6"); + put("bulk_user_import", "6"); + put("Remove local user account association with federated account", "6"); + put("Change-Password-by-User", "6"); + put("Change-Password-by-Administrator", "6"); + put("Login", "6"); + put("Login success", "6"); + put("LoginStepSuccess", "6"); + put("Login success from ip", "6"); + put("Unauthorized login attempt", "8"); + put("Null domain login attempt", "8"); + put("User authenticated to JMX", "6"); + put("User authorized to JMX", "6"); + put("Unauthorized access attempt to JMX", "8"); + put("Unauthorized attempt to read the resource", "8"); + put("DELETED", "8"); + put("PRODUCT_DELETED", "8"); + put("APIPRODUCT_DELETED", "8"); + put("APPLICATION_DELETED", "8"); + put("SUBSCRIPTION_DELETED", "8"); + put("Owner of application updated", "6"); + put("Possible Signature Wrapping Attack", "9"); + put("Possible CSRF attack", "9"); + put("Delete-Role", "8"); + put("delete", "8"); + put("Add-Role", "3"); + put("Update-Role-Name", "3"); + put("Update-Users-of-Role", "3"); + put("Update-Roles-of-User", "3"); + put("Threat detected", "9"); + } + }; + + + public static final String CEF_FORMAT = + "CEF:${" + CEF_VERSION + "}|${" + VENDOR + "}|${" + PRODUCT + "}|${" + VERSION + "}|${" + + EVENT_TYPE + "}|${" + EVENT_NAME + "}|${" + SEVERITY + "}|${" + EXTENSION + "}"; + + private static final ObjectMapper objectMapper = new ObjectMapper(); + private final String pattern; + public static final String ANY_NOT_WORD_SYMBOLS = "\\W"; + + public AuditLayout(String pattern) { + super(StandardCharsets.UTF_8); + this.pattern = pattern; + } + + @SuppressWarnings("unused") + // @PluginFactory + public static AuditLayout createLayout( + // @PluginAttribute(value = "pattern", defaultString = CEF_FORMAT) String pattern) { + String pattern) { + return new AuditLayout(pattern); + } + + @Override + public String toSerializable(LogEvent logEvent) { + return Optional.ofNullable(logEvent).map(LogEvent::getMessage).map(Message::getFormattedMessage) + .map(this::convert).orElse(null); + } + + public Map jsonMap(LogEvent logEvent) { + return Optional.ofNullable(logEvent).map(LogEvent::getMessage).map(Message::getFormattedMessage) + .map(this::asMap).orElse(Collections.emptyMap()); + } + + + private Map asMap(String message) { + final Map allFields = new HashMap<>(); + parseByRegexp(message, allFields); + if (allFields.isEmpty()) { + parseByJackson(message, allFields); + } + if (!allFields.isEmpty()) { + prepareAllFields(allFields); + + prepareExtension(allFields); + + prepareHeader(allFields); + + enhance(allFields); + } + return allFields; + } + + private String convert(String message) { + final Map allFields = asMap(message); + + parseByRegexp(message, allFields); + if (allFields.isEmpty()) { + parseByJackson(message, allFields); + } + + if (!allFields.isEmpty()) { + message = StrSubstitutor.replace(pattern, allFields); + } + return message + Strings.LINE_SEPARATOR; + } + + private void prepareAllFields(final Map allFields) { + ALL_FIELDS.forEach(field -> { + String value = allFields.get(field); + if (nonNull(value) && !value.isEmpty()) { + if (HEADER_FIELDS.contains(field)) { + value = value.replace("|", "\\|"); + } + if (EXT_FIELDS.contains(field)) { + value = value.replace("\\", "\\\\") + .replace("=", "\\=") + .replaceAll("\\n", " "); + + } + if (field.equals(EXT_SRC)) { + value = DnsResolver.tryResolve(value); + } + allFields.put(field, value); + } + }); + } + + private void prepareExtension(final Map allFields) { + StringBuilder extension = new StringBuilder(); + EXT_FIELDS.stream().filter(f -> !f.equals(EXT_END)).forEach(key -> { + String value1 = allFields.get(key); + if (nonNull(value1) && !value1.isEmpty()) { + extension.append(key).append("=").append(value1).append(" "); + } + }); + extension.append(EXT_END).append("=").append(ZonedDateTime.now().toInstant().toEpochMilli()); + + allFields.put(EXTENSION, extension.toString().trim()); + } + + private void prepareHeader(final Map allFields) { + HEADER_FIELDS.forEach(s -> { + String value = Optional.ofNullable(allFields.get(s)).orElse(DEFAULTS.get(s)); + allFields.put(s, value); + }); + } + + private void enhance(Map allFields) { + + final String eventName = allFields.get(EVENT_NAME); + + String severity = SEVERITY_BY_EVENT_NAME.keySet().stream() + .filter(s -> eventEquals(eventName, s)).findFirst().map(s -> { + allFields.put(EVENT_NAME, s); + return s; + }).map(SEVERITY_BY_EVENT_NAME::get).orElse("3"); + + allFields.put(SEVERITY, severity); + + + if (eventEquals(eventName, "Login") && nonNull(allFields.get(EXT_MSG))) { + String msq = allFields.get(EXT_MSG).toLowerCase(); + + if (msq.contains("result : success")) { + allFields.put(SEVERITY, "6"); + } else if (msq.contains("result : failed")) { + allFields.put(SEVERITY, "8"); + } + } + } + + private boolean eventEquals(String left, String right) { + if (left != null) { + left = left.replaceAll(ANY_NOT_WORD_SYMBOLS, ""); + left = left.toUpperCase(); + } + if (right != null) { + right = right.replaceAll(ANY_NOT_WORD_SYMBOLS, ""); + right = right.toUpperCase(); + } + return Objects.equals(left, right); + } + + private void parseByJackson(String message, Map reqFields) { + try { + JsonNode jsonNode = objectMapper.readTree(message); + if (jsonNode.isObject()) { + + String typ = Optional.ofNullable(jsonNode.get("typ")).map(JsonNode::asText).orElse(""); + + String action = + Optional.ofNullable(jsonNode.get("action")).map(JsonNode::asText).orElse(""); + + if (!typ.isEmpty() && !action.isEmpty()) { + reqFields.put(EVENT_TYPE, "API"); + if (!typ.equalsIgnoreCase("api")) { + action = typ + "_" + action; + } + } + if (!action.isEmpty()) { + reqFields.put(EVENT_NAME, action.toUpperCase()); + } + + Optional.ofNullable(jsonNode.get("performedBy")).map(JsonNode::asText) + .ifPresent(s -> reqFields.put(EXT_SOURCE_USER_NAME, s)); + + Optional.ofNullable(jsonNode.get("info")).map(JsonNode::toString) + .ifPresent(s -> reqFields.put(EXT_MSG, s)); + } + } catch (IOException ignore) { + // ignore + } + } + + public static void reverse(Object[] input) { + if (input == null || input.length == 0) { + return; + } + int i = 0; + int j = input.length - 1; + Object tmp; + while (j > i) { + tmp = input[j]; + input[j] = input[i]; + input[i] = tmp; + j--; + i++; + } + } + + private void parseByRegexp(String message, Map allFields) { + AuditEvent[] values = AuditEvent.values(); + reverse(values); + for (AuditEvent auditEvent : values) { + Pattern pattern = auditEvent.getPattern(); + Matcher matcher = pattern.matcher(message); + if (matcher.matches()) { + ALL_FIELDS.forEach(field -> { + String value = ""; + try { + value = matcher.group(field); + } catch (IllegalArgumentException ignored) { + } + if (!value.isEmpty()) { + allFields.put(field, value); + allFields.put(EVENT_TYPE, auditEvent.getEventType()); + if (Strings.isEmpty(allFields.get(EVENT_NAME))) { + allFields.put(EVENT_NAME, auditEvent.getEventName()); + } + } + if (allFields.containsKey(EXT_SRC)) { + allFields.replace(EXT_SRC, DnsResolver.tryResolve(allFields.get(EXT_SRC))); + } + }); + break; + } + } + } + + public void addOverrides(Map override) { + DEFAULTS.putAll(override); + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFAppender.java b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFAppender.java new file mode 100644 index 00000000..1dbbe897 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFAppender.java @@ -0,0 +1,89 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import org.apache.logging.log4j.core.Appender; +import org.apache.logging.log4j.core.Core; +import org.apache.logging.log4j.core.Filter; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.appender.AbstractAppender; +import org.apache.logging.log4j.core.config.AppenderControl; +import org.apache.logging.log4j.core.config.Configuration; +import org.apache.logging.log4j.core.config.plugins.*; + +import java.util.ArrayList; +import java.util.List; + +@Plugin(name = "CEFAggregate", category = Core.CATEGORY_NAME, elementType = Appender.ELEMENT_TYPE, printObject = true) +public class CEFAppender extends AbstractAppender { + + private final Configuration config; + private final String children; + private final List controls = new ArrayList<>(); + + private CEFAppender(String name, Filter filter, String children, Configuration config, Boolean ignoreExceptions) { + super(name, filter, null, ignoreExceptions, null); + this.config = config; + this.children = children; + } + + @Override + public void start() { + String[] refs = children.split(","); + for (String ref : refs) { + String cleaned = ref.trim(); + Appender appender = config.getAppender(cleaned); + if (appender != null) { + controls.add(new AppenderControl(appender, null, null)); + } + } + super.start(); + } + + @Override + public void append(LogEvent event) { + String formattedMessage = event.getMessage().getFormattedMessage(); + boolean skipMessage = formattedMessage.startsWith("GET /") || formattedMessage.startsWith("POST /"); + if (!skipMessage) { + for (AppenderControl control : controls) { + control.callAppender(event); + } + } + } + + @PluginFactory + public static CEFAppender createAppender( + @PluginAttribute("name") final String name, + @PluginAttribute("children") final String children, + @PluginElement("Filter") final Filter filter, + @PluginConfiguration final Configuration config + ) { + if (children == null) { + throw new IllegalArgumentException("`children` key cannot be null"); + } + return new CEFAppender(name, filter, children, config, false); + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFLayout.java b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFLayout.java new file mode 100644 index 00000000..6660ad55 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFLayout.java @@ -0,0 +1,153 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.logging.log4j.core.Layout; +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.config.Node; +import org.apache.logging.log4j.core.config.plugins.Plugin; +import org.apache.logging.log4j.core.config.plugins.PluginAttribute; +import org.apache.logging.log4j.core.config.plugins.PluginFactory; +import org.apache.logging.log4j.core.layout.AbstractStringLayout; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Plugin(name = "CEFLayout", category = Node.CATEGORY, elementType = Layout.ELEMENT_TYPE, printObject = true) +public class CEFLayout extends AbstractStringLayout { + public static final String EMDEV_EVENTS = "isEmdevEvents"; + private final String header; + + private static final ObjectMapper mapper = new ObjectMapper(); + private final String separator; + + private final String format; + private final Map defaults; + private AuditLayout auditLayout; + + public CEFLayout(String version, String separator, String vendor, String product, + String productVersion, String format) { + super(Charset.defaultCharset()); + this.separator = separator; + this.format = format; + header = new StringBuilder() + .append("CEF:").append(version).append(separator) + .append(vendor).append(separator) + .append(product).append(separator) + .append(productVersion).toString(); + String pattern = + "CEF:${" + AuditLayout.CEF_VERSION + "}|${" + AuditLayout.VENDOR + "}|${" + AuditLayout.PRODUCT + "}|${" + + AuditLayout.VERSION + "}|${" + + AuditLayout.EVENT_TYPE + "}|${" + AuditLayout.EVENT_NAME + "}|${" + AuditLayout.SEVERITY + + "}|${" + AuditLayout.EXTENSION + "}"; + this.auditLayout = new AuditLayout(pattern); + Map overrides = new HashMap<>(); + overrides.put(AuditLayout.CEF_VERSION, version); + overrides.put(AuditLayout.VENDOR, vendor); + overrides.put(AuditLayout.PRODUCT, product); + overrides.put(AuditLayout.VERSION, productVersion); + this.defaults = new LinkedHashMap<>(overrides); + auditLayout.addOverrides(overrides); + } + + // test-only + void setAuditLayout(AuditLayout layout) { + this.auditLayout = layout; + } + + @Override + public String toSerializable(LogEvent event) { + String formattedMessage = event.getMessage().getFormattedMessage(); + String result = null; + if (formattedMessage != null) { + try { + result = tryProcessEmdevEvent(formattedMessage); + } catch (IOException e) { + + } + if (result == null) { + result = tryAlternate(event); + } + } + return result; + } + + private String tryAlternate(LogEvent event) { + String result = null; + if (format.equalsIgnoreCase("json")) { + Map parsedMessage = auditLayout.jsonMap(event); + try { + result = mapper.writeValueAsString(parsedMessage) + "\n"; + } catch (JsonProcessingException e) { + // pass + } + } else { + result = auditLayout.toSerializable(event); + } + return result; + } + + private String tryProcessEmdevEvent(String formattedMessage) throws IOException { + String result = null; + JsonNode jsonNode = mapper.readTree(formattedMessage); + JsonNode isEmdev = jsonNode.get(EMDEV_EVENTS); + boolean process = isEmdev != null && !isEmdev.isNull() && isEmdev.asBoolean(false); + if (process) { + CEFRecord record = CEFRecord.fromJson(jsonNode); + if (record.getSrc() != null) { + String resolvedAddress = DnsResolver.tryResolve(record.getSrc()); + if (resolvedAddress != null) { + record.setSrc(resolvedAddress); + } + } + if (this.format.equalsIgnoreCase("cef")) { + result = record.asString(header, separator) + "\n"; + } else if (format.equalsIgnoreCase("json")) { + Map jsonRecord = record.asJson(defaults); + result = mapper.writeValueAsString(jsonRecord) + "\n"; + } + } + return result; + } + + @PluginFactory + public static CEFLayout createCEFLayout( + @PluginAttribute(value = "version", defaultString = "0") String version, + @PluginAttribute(value = "separator", defaultString = "|") String separator, + @PluginAttribute(value = "vendor", defaultString = "EMDEV") String vendor, + @PluginAttribute(value = "product") String product, + @PluginAttribute(value = "productVersion") String productVersion, + @PluginAttribute(value = "format", defaultString = "cef") String format) { + return new CEFLayout(version, separator, vendor, product, productVersion, format); + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFRecord.java b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFRecord.java new file mode 100644 index 00000000..b18aeb91 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/CEFRecord.java @@ -0,0 +1,309 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.NullNode; + +import java.time.ZonedDateTime; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.function.BiConsumer; + + +public class CEFRecord { + public static final String SPACE = " "; + public static final String EQUALS = "="; + private String type; + private String performedBy; + private String action; + private String src; + private String dst; + private String shost; + private String suid; + private String suser; + private String msg; + private String cs1; + private String cs1Label; + private String severity; + private final long end; + private String outcome; + private String duser; + private String spriv; + + public CEFRecord() { + this.end = ZonedDateTime.now().toInstant().toEpochMilli(); + } + + public String getSrc() { + return src; + } + + public CEFRecord setSrc(String src) { + this.src = src; + return this; + } + + public String getDst() { + return dst; + } + + public CEFRecord setDst(String dst) { + this.dst = dst; + return this; + } + + public String getShost() { + return shost; + } + + public CEFRecord setShost(String shost) { + this.shost = shost; + return this; + } + + public String getSuid() { + return suid; + } + + public CEFRecord setSuid(String suid) { + this.suid = suid; + return this; + } + + public String getSuser() { + return suser; + } + + public CEFRecord setSuser(String suser) { + this.suser = suser; + return this; + } + + public String getMsg() { + return msg; + } + + public CEFRecord setMsg(String msg) { + this.msg = msg; + return this; + } + + public String getCs1() { + return cs1; + } + + public CEFRecord setCs1(String cs1) { + this.cs1 = cs1; + return this; + } + + public String getCs1Label() { + return cs1Label; + } + + public CEFRecord setCs1Label(String cs1Label) { + this.cs1Label = cs1Label; + return this; + } + + public long getEnd() { + return end; + } + + public String getType() { + return type; + } + + public CEFRecord setType(String type) { + this.type = type; + return this; + } + + public String getPerformedBy() { + return performedBy; + } + + public CEFRecord setPerformedBy(String performedBy) { + this.performedBy = performedBy; + return this; + } + + public String getAction() { + return action; + } + + public CEFRecord setAction(String action) { + this.action = action; + return this; + } + + public String getSeverity() { + return severity; + } + + public CEFRecord setSeverity(String severity) { + this.severity = severity; + return this; + } + + public static CEFRecord fromJson(JsonNode jsonNode) { + String type = safeGet(jsonNode, "typ").asText(""); + String action = safeGet(jsonNode, "action").asText(""); + String performedBy = safeGet(jsonNode, "performedBy").asText(""); + JsonNode info = safeGet(jsonNode, "info"); + String src = safeGet(info, "src").asText(""); + String shost = safeGet(info,"shost").asText(""); + String dst = safeGet(info, "dst").asText(""); + String suid = safeGet(info, "suid").asText(""); + String msg = safeGet(info, "msg").asText(""); + String suser = safeGet(info, "suser").asText(""); + String outcome = safeGet(info, "outcome").asText(""); + String severity = safeGet(info, "severity").asText("0"); + String duser = safeGet(info, "duser").asText(""); + String spriv = safeGet(info, "spriv").asText(""); + return new CEFRecord() + .setType(type) + .setAction(action) + .setPerformedBy(performedBy) + .setShost(shost) + .setSrc(src) + .setDst(dst) + .setSuid(suid) + .setMsg(msg) + .setSuser(suser) + .setSeverity(severity) + .setOutcome(outcome) + .setDuser(duser) + .setSpriv(spriv); + } + + private static JsonNode safeGet(JsonNode node, String path) { + JsonNode child = node.get(path); + if (child == null) { + return NullNode.getInstance(); + } else { + return child; + } + } + + public String asString(String header, String separator) { + final StringBuilder builder = new StringBuilder(header); + builder + .append(separator).append(type) //eventClassId + .append(separator).append(action) //name + .append(separator).append(severity).append(separator); + BiConsumer consumer = (key, value) -> builder.append(key).append(EQUALS).append(value).append(SPACE); + Processor p = new Processor(consumer); + p.process("src", src). + process("dst", dst). + process("shost", shost). + process("suid", suid). + process("suser", suser). + process("duser", duser). + process("spriv", spriv). + process("msg", msg.replaceAll("=", "\\\\=").replaceAll("\\n", " ")). + process("outcome", outcome). + process("end", end); + return builder.toString(); + } + + public Map asJson(Map defaults) { + final Map data = new LinkedHashMap<>(defaults); + Processor p = new Processor(data::put); + p.process("typ", type). + process("action", action). + process("severity", severity). + process("src", src). + process("dst", dst). + process("shost", shost). + process("suid", suid). + process("suser", suser). + process("duser", duser). + process("spriv", spriv). + process("msg", msg.replaceAll("\\n", " ")). + process("outcome", outcome). + process("cs1", cs1). + process("cs1Label", cs1Label). + process("end", end); + return data; + } + + private void acceptNotEmpty(String key, T value, BiConsumer consumer) { + if (value != null && notEmpty(String.valueOf(value))) { + consumer.accept(key, value); + } + } + + public CEFRecord setOutcome(String outcome) { + this.outcome = outcome; + return this; + } + + public String getOutcome() { + return outcome; + } + + public CEFRecord setDuser(String duser) { + this.duser = duser; + return this; + } + + public String getDuser() { + return duser; + } + + public CEFRecord setSpriv(String spriv) { + this.spriv = spriv; + return this; + } + + public String getSpriv() { + return spriv; + } + + static class Processor { + final BiConsumer consumer; + Processor(BiConsumer consumer) { + this.consumer = consumer; + } + + public Processor process(String key, Object value) { + acceptNotEmpty(key, value); + return this; + } + + private void acceptNotEmpty(String key, T value) { + if (value != null && notEmpty(String.valueOf(value))) { + consumer.accept(key, value); + } + } + + } + private static boolean notEmpty(String s) { + return s != null && s.trim().length() > 0; + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/DnsResolver.java b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/DnsResolver.java new file mode 100644 index 00000000..ca91526f --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/main/java/ru/emdev/cef/DnsResolver.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import java.io.IOException; +import java.net.InetAddress; +import java.util.concurrent.ConcurrentHashMap; + +public class DnsResolver { + private final static ConcurrentHashMap dnsCache = new ConcurrentHashMap<>(1024); + + public static String tryResolve(String hostname) { + return dnsCache.computeIfAbsent(hostname, (s) -> { + try { + InetAddress addr = InetAddress.getByName(s); + return addr.getHostAddress(); + } catch (IOException e) { + return s; + } + }); + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/test/java/ru/emdev/cef/CEFRecordTest.java b/platform/runtime/base/logging/cef-logger-layout/src/test/java/ru/emdev/cef/CEFRecordTest.java new file mode 100644 index 00000000..dae7c3ec --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/test/java/ru/emdev/cef/CEFRecordTest.java @@ -0,0 +1,94 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.jupiter.api.Assertions.*; + +public class CEFRecordTest { + + private final static ObjectMapper mapper = new ObjectMapper(); + private final static String SEPARATOR = "|"; + private final static String HEADER = "CEF:0|VENDOR|PRODUCT|1.0.0"; + public static final int CEF_FIELD_COUNT = 8; + + @Test + public void cefRecordCanBeBuiltFromEmptyJson() { + JsonNode jsonNode = readResource("examples/empty.json"); + CEFRecord record = CEFRecord.fromJson(jsonNode); + assertNotNull(record); + assertNotEquals(0, record.getEnd()); + } + + @Test + public void cefRecordCanBeBuiltFromJsonWithouInfo() { + JsonNode jsonNode = readResource("examples/noinfo.json"); + CEFRecord record = CEFRecord.fromJson(jsonNode); + assertNotNull(record); + assertNotEquals(0, record.getEnd()); + assertEquals("type", record.getType()); + assertEquals("action", record.getAction()); + assertEquals("user", record.getPerformedBy()); + assertEquals("0", record.getSeverity()); + } + + @Test + public void testFormatting() { + JsonNode jsonNode = readResource("examples/almostFull.json"); + CEFRecord record = CEFRecord.fromJson(jsonNode); + assertNotNull(record); + assertEquals("10", record.getSeverity()); + assertEquals("", record.getSuser()); + assertEquals("", record.getSuid()); + String message = record.asString(HEADER, SEPARATOR); + String[] mainFields = message.split("\\|"); + assertEquals(CEF_FIELD_COUNT, mainFields.length); + assertEquals("type", mainFields[4]); + assertEquals("action", mainFields[5]); + assertEquals("10", mainFields[6]); + String[] secFields = mainFields[7].split("\\s"); + assertEquals(5, secFields.length); + assertEquals("src=127.0.0.1", secFields[0]); + assertEquals("dst=127.0.0.1:443", secFields[1]); + assertEquals("shost=localhost.localdomain", secFields[2]); + assertEquals("msg=CODE\\=400", secFields[3]); + assertTrue(secFields[4].matches("^end=\\d+$")); + } + + private static JsonNode readResource(String name) { + try (InputStream in = ClassLoader.getSystemResourceAsStream(name)){ + return mapper.readTree(in); + } catch (IOException e) { + return null; + } + } +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/test/java/ru/emdev/cef/ProcessingTest.java b/platform/runtime/base/logging/cef-logger-layout/src/test/java/ru/emdev/cef/ProcessingTest.java new file mode 100644 index 00000000..9ad3d442 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/test/java/ru/emdev/cef/ProcessingTest.java @@ -0,0 +1,93 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cef-logger-layout + * ========== + * 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~~~~~~ + */ +package ru.emdev.cef; + + +import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.message.Message; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + +public class ProcessingTest { + + public static final String AUDIT_LOG_MARKER = "auditLog"; + private CEFLayout cefLayout; + private AuditLayout auditLayout; + + @BeforeEach + protected void setUp() { + cefLayout = new CEFLayout("", "|", "", "", "", "cef"); + auditLayout = Mockito.mock(AuditLayout.class); + Mockito.when(auditLayout.toSerializable(any())).thenReturn(AUDIT_LOG_MARKER); + cefLayout.setAuditLayout(auditLayout); + } + + @Test + public void testIsEmdevEvents() { + LogEvent emdevOne = createLogEvent("{\"isEmdevEvents\": \"true\"}"); + String message = cefLayout.toSerializable(emdevOne); + assertNotNull(message); + verify(auditLayout, never()).toSerializable(any()); + } + + @Test + public void testNotEmdevEvents() { + LogEvent emdevOne = createLogEvent("{\"isEmdevEvents\": \"false\"}"); + String message = cefLayout.toSerializable(emdevOne); + assertNotNull(message); + verify(auditLayout, times(1)).toSerializable(any()); + } + + @Test + public void testSkipJsonWithoutEmdevMarker() { + LogEvent emdevOne = createLogEvent("{}"); + String message = cefLayout.toSerializable(emdevOne); + assertNotNull(message); + verify(auditLayout, times(1)).toSerializable(any()); + } + + @Test + public void testSkipPlainText() { + LogEvent emdevOne = createLogEvent("Log message"); + String message = cefLayout.toSerializable(emdevOne); + assertNotNull(message); + verify(auditLayout, times(1)).toSerializable(any()); + } + + private static LogEvent createLogEvent(String message) { + LogEvent event = Mockito.mock(LogEvent.class); + Message logMessage = Mockito.mock(Message.class); + Mockito.when(logMessage.getFormattedMessage()).thenReturn(message); + Mockito.when(event.getMessage()).thenReturn(logMessage); + return event; + } + +} diff --git a/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/almostFull.json b/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/almostFull.json new file mode 100644 index 00000000..7fde695f --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/almostFull.json @@ -0,0 +1,12 @@ +{ + "typ": "type", + "action": "action", + "performedBy": "user", + "info" : { + "severity": 10, + "shost": "localhost.localdomain", + "src": "127.0.0.1", + "dst": "127.0.0.1:443", + "msg": "CODE=400" + } +} \ No newline at end of file diff --git a/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/empty.json b/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/empty.json new file mode 100644 index 00000000..9e26dfee --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/empty.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/noinfo.json b/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/noinfo.json new file mode 100644 index 00000000..b7900cde --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/src/test/resources/examples/noinfo.json @@ -0,0 +1,5 @@ +{ + "typ": "type", + "action": "action", + "performedBy": "user" +} \ No newline at end of file diff --git a/platform/runtime/base/logging/cef-logger-layout/wso2/conf/deployment.toml b/platform/runtime/base/logging/cef-logger-layout/wso2/conf/deployment.toml new file mode 100644 index 00000000..19103bec --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/wso2/conf/deployment.toml @@ -0,0 +1,275 @@ +[server] +hostname = "localhost" +#offset=0 +base_path = "${carbon.protocol}://${carbon.host}:${carbon.management.port}" +#discard_empty_caches = false +server_role = "default" + +[super_admin] +username = "admin" +password = "admin" +create_admin_account = true + +[user_store] +type = "database_unique_id" + +[database.apim_db] +type = "h2" +url = "jdbc:h2:./repository/database/WSO2AM_DB;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE" +username = "wso2carbon" +password = "wso2carbon" + +[database.shared_db] +type = "h2" +url = "jdbc:h2:./repository/database/WSO2SHARED_DB;DB_CLOSE_ON_EXIT=FALSE" +username = "wso2carbon" +password = "wso2carbon" + +[keystore.tls] +file_name = "wso2carbon.jks" +type = "JKS" +password = "wso2carbon" +alias = "wso2carbon" +key_password = "wso2carbon" + +#[keystore.listener_profile] +#bind_address = "0.0.0.0" + +#[keystore.primary] +#file_name = "wso2carbon.jks" +#type = "JKS" +#password = "wso2carbon" +#alias = "wso2carbon" +#key_password = "wso2carbon" + +#[keystore.internal] +#file_name = "wso2carbon.jks" +#type = "JKS" +#password = "wso2carbon" +#alias = "wso2carbon" +#key_password = "wso2carbon" + +[[apim.gateway.environment]] +name = "Default" +type = "hybrid" +provider = "wso2" +display_in_api_console = true +description = "This is a hybrid gateway that handles both production and sandbox token traffic." +show_as_token_endpoint_url = true +service_url = "https://localhost:${mgt.transport.https.port}/services/" +username= "${admin.username}" +password= "${admin.password}" +ws_endpoint = "ws://localhost:9099" +wss_endpoint = "wss://localhost:8099" +http_endpoint = "http://localhost:${http.nio.port}" +https_endpoint = "https://localhost:${https.nio.port}" +websub_event_receiver_http_endpoint = "http://localhost:9021" +websub_event_receiver_https_endpoint = "https://localhost:8021" + +[apim.sync_runtime_artifacts.gateway] +gateway_labels =["Default"] + +#[apim.cache.gateway_token] +#enable = true +#expiry_time = "900s" + +#[apim.cache.resource] +#enable = true +#expiry_time = "900s" + +#[apim.cache.km_token] +#enable = false +#expiry_time = "15m" + +#[apim.cache.recent_apis] +#enable = false + +#[apim.cache.scopes] +#enable = true + +#[apim.cache.publisher_roles] +#enable = true + +#[apim.cache.jwt_claim] +#enable = true +#expiry_time = "15m" + +#[apim.cache.tags] +#expiry_time = "2m" + +[apim.analytics] +enable = false +auth_token = "" + +#[apim.key_manager] +#service_url = "https://localhost:${mgt.transport.https.port}/services/" +#username = "$ref{super_admin.username}" +#password = "$ref{super_admin.password}" +#pool.init_idle_capacity = 50 +#pool.max_idle = 100 +#key_validation_handler_type = "default" +#key_validation_handler_type = "custom" +#key_validation_handler_impl = "org.wso2.carbon.apimgt.keymgt.handlers.DefaultKeyValidationHandler" + +#[apim.idp] +#server_url = "https://localhost:${mgt.transport.https.port}" +#authorize_endpoint = "https://localhost:${mgt.transport.https.port}/oauth2/authorize" +#oidc_logout_endpoint = "https://localhost:${mgt.transport.https.port}/oidc/logout" +#oidc_check_session_endpoint = "https://localhost:${mgt.transport.https.port}/oidc/checksession" + +#[apim.jwt] +#enable = true +#encoding = "base64" # base64,base64url +#generator_impl = "org.wso2.carbon.apimgt.keymgt.token.JWTGenerator" +#claim_dialect = "http://wso2.org/claims" +#convert_dialect = false +#header = "X-JWT-Assertion" +#signing_algorithm = "SHA256withRSA" +#enable_user_claims = true +#claims_extractor_impl = "org.wso2.carbon.apimgt.impl.token.ExtendedDefaultClaimsRetriever" + +#[apim.oauth_config] +#enable_outbound_auth_header = false +#auth_header = "Authorization" +#revoke_endpoint = "https://localhost:${https.nio.port}/revoke" +#enable_token_encryption = false +#enable_token_hashing = false + +#[apim.devportal] +#url = "https://localhost:${mgt.transport.https.port}/devportal" +#enable_application_sharing = false +#if application_sharing_type, application_sharing_impl both defined priority goes to application_sharing_impl +#application_sharing_type = "default" #changed type, saml, default #todo: check the new config for rest api +#application_sharing_impl = "org.wso2.carbon.apimgt.impl.SAMLGroupIDExtractorImpl" +#display_multiple_versions = false +#display_deprecated_apis = false +#enable_comments = true +#enable_ratings = true +#enable_forum = true +#enable_anonymous_mode=true +#enable_cross_tenant_subscriptions = true +#default_reserved_username = "apim_reserved_user" + +[apim.cors] +allow_origins = "*" +allow_methods = ["GET","PUT","POST","DELETE","PATCH","OPTIONS"] +allow_headers = ["authorization","Access-Control-Allow-Origin","Content-Type","SOAPAction","apikey","Internal-Key"] +allow_credentials = false + +#[apim.throttling] +#enable_data_publishing = true +#enable_policy_deploy = true +#enable_blacklist_condition = true +#enable_persistence = true +#throttle_decision_endpoints = ["tcp://localhost:5672","tcp://localhost:5672"] + +#[apim.throttling.blacklist_condition] +#start_delay = "5m" +#period = "1h" + +#[apim.throttling.jms] +#start_delay = "5m" + +#[apim.throttling.event_sync] +#hostName = "0.0.0.0" +#port = 11224 + +#[apim.throttling.event_management] +#hostName = "0.0.0.0" +#port = 10005 + +#[[apim.throttling.url_group]] +#traffic_manager_urls = ["tcp://localhost:9611","tcp://localhost:9611"] +#traffic_manager_auth_urls = ["ssl://localhost:9711","ssl://localhost:9711"] +#type = "loadbalance" + +#[[apim.throttling.url_group]] +#traffic_manager_urls = ["tcp://localhost:9611","tcp://localhost:9611"] +#traffic_manager_auth_urls = ["ssl://localhost:9711","ssl://localhost:9711"] +#type = "failover" + +#[apim.workflow] +#enable = false +#service_url = "https://localhost:9445/bpmn" +#username = "$ref{super_admin.username}" +#password = "$ref{super_admin.password}" +#callback_endpoint = "https://localhost:${mgt.transport.https.port}/api/am/admin/v0.17/workflows/update-workflow-status" +#token_endpoint = "https://localhost:${https.nio.port}/token" +#client_registration_endpoint = "https://localhost:${mgt.transport.https.port}/client-registration/v0.17/register" +#client_registration_username = "$ref{super_admin.username}" +#client_registration_password = "$ref{super_admin.password}" + +#data bridge config +#[transport.receiver] +#type = "binary" +#worker_threads = 10 +#session_timeout = "30m" +#keystore.file_name = "$ref{keystore.tls.file_name}" +#keystore.password = "$ref{keystore.tls.password}" +#tcp_port = 9611 +#ssl_port = 9711 +#ssl_receiver_thread_pool_size = 100 +#tcp_receiver_thread_pool_size = 100 +#ssl_enabled_protocols = ["TLSv1","TLSv1.1","TLSv1.2"] +#ciphers = ["SSL_RSA_WITH_RC4_128_MD5","SSL_RSA_WITH_RC4_128_SHA"] + +#[apim.notification] +#from_address = "APIM.com" +#username = "APIM" +#password = "APIM+123" +#hostname = "localhost" +#port = 3025 +#enable_start_tls = false +#enable_authentication = true + +#[apim.token.revocation] +#notifier_impl = "org.wso2.carbon.apimgt.keymgt.events.TokenRevocationNotifierImpl" +#enable_realtime_notifier = true +#realtime_notifier.ttl = 5000 +#enable_persistent_notifier = true +#persistent_notifier.hostname = "https://localhost:2379/v2/keys/jti/" +#persistent_notifier.ttl = 5000 +#persistent_notifier.username = "root" +#persistent_notifier.password = "root" + +[[event_handler]] +name="userPostSelfRegistration" +subscriptions=["POST_ADD_USER"] + +[service_provider] +sp_name_regex = "^[\\sa-zA-Z0-9._-]*$" + +[database.local] +url = "jdbc:h2:./repository/database/WSO2CARBON_DB;DB_CLOSE_ON_EXIT=FALSE" + +[[event_listener]] +id = "token_revocation" +type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler" +name = "org.wso2.is.notification.ApimOauthEventInterceptor" +order = 1 + +[[event_listener]] +id = "token_refresh" +type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler" +name = "org.wso2.carbon.identity.data.publisher.oauth.listener.RefreshTokenGrantAuditLogger" +order = 2 + +[[event_listener]] +id = "token_refresh_revoke" +type = "org.wso2.carbon.identity.core.handler.AbstractIdentityHandler" +name = "org.wso2.carbon.identity.data.publisher.oauth.listener.TokenRevocationAuditLogger" +order = 3 + +[event_listener.properties] +notification_endpoint = "https://localhost:${mgt.transport.https.port}/internal/data/v1/notify" +username = "${admin.username}" +password = "${admin.password}" +'header.X-WSO2-KEY-MANAGER' = "default" + +[oauth.grant_type.token_exchange] +enable = true +allow_refresh_tokens = true +iat_validity_period = "1h" + +[apim.key_manager] +enable_apikey_subscription_validation = true \ No newline at end of file diff --git a/platform/runtime/base/logging/cef-logger-layout/wso2/conf/log4j2-entaxy.properties b/platform/runtime/base/logging/cef-logger-layout/wso2/conf/log4j2-entaxy.properties new file mode 100644 index 00000000..ef0b531a --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/wso2/conf/log4j2-entaxy.properties @@ -0,0 +1,26 @@ +# CEF logger +log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE +log4j2.logger.AUDIT_FILE.level = INFO +log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger +log4j2.logger.AUDIT_FILE.additivity = false + +log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate +log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger +log4j2.appender.AUDIT_LOGFILE.children = CefFile +log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter +log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO + +log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile +log4j2.appender.AUDIT_LOGFILE_1.name = CefFile +log4j2.appender.AUDIT_LOGFILE_1.append = true +log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log +log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log +log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout +log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV +log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY +log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT +log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies +log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy +log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB +log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter +log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO \ No newline at end of file diff --git a/platform/runtime/base/logging/cef-logger-layout/wso2/conf/log4j2.properties b/platform/runtime/base/logging/cef-logger-layout/wso2/conf/log4j2.properties new file mode 100644 index 00000000..964a0c56 --- /dev/null +++ b/platform/runtime/base/logging/cef-logger-layout/wso2/conf/log4j2.properties @@ -0,0 +1,484 @@ +# list of all appenders +#add entry "syslog" to use the syslog appender +appenders=CARBON_CONSOLE, CARBON_LOGFILE, AUDIT_LOGFILE, ATOMIKOS_LOGFILE, CARBON_TRACE_LOGFILE, ERROR_LOGFILE, OPEN_TRACING,SERVICE_APPENDER, TRACE_APPENDER, osgi, CORRELATION, BOTDATA_APPENDER, API_LOGFILE, AUDIT_LOGFILE_1, AUDIT_LOGFILE_2 +#, syslog + +# CARBON_CONSOLE is set to be a ConsoleAppender using a PatternLayout. +appender.CARBON_CONSOLE.type = Console +appender.CARBON_CONSOLE.name = CARBON_CONSOLE +appender.CARBON_CONSOLE.layout.type = PatternLayout +appender.CARBON_CONSOLE.layout.pattern = [%d{DEFAULT}] %5p - %c{1} %m%n +appender.CARBON_CONSOLE.filter.threshold.type = ThresholdFilter +appender.CARBON_CONSOLE.filter.threshold.level = DEBUG + +# CARBON_LOGFILE is set to be a DailyRollingFileAppender using a PatternLayout. +appender.CARBON_LOGFILE.type = RollingFile +appender.CARBON_LOGFILE.name = CARBON_LOGFILE +appender.CARBON_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2carbon.log +appender.CARBON_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2carbon-%d{MM-dd-yyyy}-%i.log +appender.CARBON_LOGFILE.layout.type = PatternLayout +appender.CARBON_LOGFILE.layout.pattern = TID: [%tenantId] [%appName] [%d] %5p {%c} - %m%ex%n +appender.CARBON_LOGFILE.policies.type = Policies +appender.CARBON_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy +appender.CARBON_LOGFILE.policies.time.interval = 1 +appender.CARBON_LOGFILE.policies.time.modulate = true +appender.CARBON_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy +appender.CARBON_LOGFILE.policies.size.size = 10MB +appender.CARBON_LOGFILE.strategy.type = DefaultRolloverStrategy +appender.CARBON_LOGFILE.strategy.max = 20 +appender.CARBON_LOGFILE.filter.threshold.type = ThresholdFilter +appender.CARBON_LOGFILE.filter.threshold.level = DEBUG + +# Appender config to AUDIT_LOGFILE +appender.AUDIT_LOGFILE.type = CEFAggregate +appender.AUDIT_LOGFILE.name = AUDIT_LOGFILE +appender.AUDIT_LOGFILE.children = AUDIT_LOGFILE_1, AUDIT_LOGFILE_2 +appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter +appender.AUDIT_LOGFILE.filter.threshold.level = INFO + +# audit.log CEF output +appender.AUDIT_LOGFILE_1.type = RollingFile +appender.AUDIT_LOGFILE_1.name = AUDIT_LOGFILE_1 +appender.AUDIT_LOGFILE_1.fileName = ${sys:carbon.home}/repository/logs/audit.log +appender.AUDIT_LOGFILE_1.filePattern = ${sys:carbon.home}/repository/logs/audit-%d{MM-dd-yyyy}.log +#appender.AUDIT_LOGFILE.layout.type = PatternLayout +#appender.AUDIT_LOGFILE.layout.pattern = TID: [%tenantId] [%d] %5p {%c} - %m%ex%n +appender.AUDIT_LOGFILE_1.layout.type = CEFLayout +appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV +appender.AUDIT_LOGFILE_1.layout.product = WSO2APIM +appender.AUDIT_LOGFILE_1.layout.productVersion = 4.1.0 +appender.AUDIT_LOGFILE_1.policies.type = Policies +appender.AUDIT_LOGFILE_1.policies.time.type = TimeBasedTriggeringPolicy +appender.AUDIT_LOGFILE_1.policies.time.interval = 1 +appender.AUDIT_LOGFILE_1.policies.time.modulate = true +appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy +appender.AUDIT_LOGFILE_1.policies.size.size = 10MB +appender.AUDIT_LOGFILE_1.strategy.type = DefaultRolloverStrategy +appender.AUDIT_LOGFILE_1.strategy.max = 20 +appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter +appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO + +# console audit JSON output +appender.AUDIT_LOGFILE_2.type = Console +appender.AUDIT_LOGFILE_2.name = AUDIT_LOGFILE_2 +appender.AUDIT_LOGFILE_2.layout.type = CEFLayout +appender.AUDIT_LOGFILE_2.layout.vendor = EMDEV +appender.AUDIT_LOGFILE_2.layout.product = WSO2APIM +appender.AUDIT_LOGFILE_2.layout.productVersion = 4.1.0 +appender.AUDIT_LOGFILE_2.layout.format = json +appender.AUDIT_LOGFILE_2.filter.threshold.type = ThresholdFilter +appender.AUDIT_LOGFILE_2.filter.threshold.level = INFO + + +# Appender config API logging +appender.API_LOGFILE.type = RollingFile +appender.API_LOGFILE.name = API_LOGFILE +appender.API_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/api.log +appender.API_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/api-%d{MM-dd-yyyy}-%i.log +appender.API_LOGFILE.layout.type = PatternLayout +appender.API_LOGFILE.layout.pattern = [%d] %5p {%c} %X{apiName} - %m%ex%n +appender.API_LOGFILE.policies.type = Policies +appender.API_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy +appender.API_LOGFILE.policies.time.interval = 1 +appender.API_LOGFILE.policies.time.modulate = true +appender.API_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy +appender.API_LOGFILE.policies.size.size = 10MB +appender.API_LOGFILE.strategy.type = DefaultRolloverStrategy +appender.API_LOGFILE.strategy.max = 20 +appender.API_LOGFILE.filter.threshold.type = ThresholdFilter +appender.API_LOGFILE.filter.threshold.level = DEBUG + +# Appender config to send Atomikos transaction logs to new log file tm.out. +appender.ATOMIKOS_LOGFILE.type = RollingFile +appender.ATOMIKOS_LOGFILE.name = ATOMIKOS_LOGFILE +appender.ATOMIKOS_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/tm.out +appender.ATOMIKOS_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/tm-%d{MM-dd-yyyy}.out +appender.ATOMIKOS_LOGFILE.layout.type = PatternLayout +appender.ATOMIKOS_LOGFILE.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n +appender.ATOMIKOS_LOGFILE.policies.type = Policies +appender.ATOMIKOS_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy +appender.ATOMIKOS_LOGFILE.policies.time.interval = 1 +appender.ATOMIKOS_LOGFILE.policies.time.modulate = true +appender.ATOMIKOS_LOGFILE.strategy.type = DefaultRolloverStrategy +appender.ATOMIKOS_LOGFILE.strategy.max = 20 + +# Appender config to CARBON_TRACE_LOGFILE +appender.CARBON_TRACE_LOGFILE.type = RollingFile +appender.CARBON_TRACE_LOGFILE.name = CARBON_TRACE_LOGFILE +appender.CARBON_TRACE_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2carbon-trace-messages.log +appender.CARBON_TRACE_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2carbon-trace-messages-%d{MM-dd-yyyy}.log +appender.CARBON_TRACE_LOGFILE.layout.type = PatternLayout +appender.CARBON_TRACE_LOGFILE.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n +appender.CARBON_TRACE_LOGFILE.policies.type = Policies +appender.CARBON_TRACE_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy +appender.CARBON_TRACE_LOGFILE.policies.time.interval = 1 +appender.CARBON_TRACE_LOGFILE.policies.time.modulate = true +appender.CARBON_TRACE_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy +appender.CARBON_TRACE_LOGFILE.policies.size.size = 10MB +appender.CARBON_TRACE_LOGFILE.strategy.type = DefaultRolloverStrategy +appender.CARBON_TRACE_LOGFILE.strategy.max = 20 + +# Appender config to put correlation Log. +appender.CORRELATION.type = RollingFile +appender.CORRELATION.name = CORRELATION +appender.CORRELATION.fileName = ${sys:carbon.home}/repository/logs/correlation.log +appender.CORRELATION.filePattern =${sys:carbon.home}/repository/logs/correlation-%d{MM-dd-yyyy}-%i.log.gz +appender.CORRELATION.layout.type = PatternLayout +appender.CORRELATION.layout.pattern = %d{yyyy-MM-dd HH:mm:ss,SSS}|%X{Correlation-ID}|%t|%m%n +appender.CORRELATION.policies.type = Policies +appender.CORRELATION.policies.time.type = TimeBasedTriggeringPolicy +appender.CORRELATION.policies.time.interval = 1 +appender.CORRELATION.policies.time.modulate = true +appender.CORRELATION.policies.size.type = SizeBasedTriggeringPolicy +appender.CORRELATION.policies.size.size = 10MB +appender.CORRELATION.strategy.type = DefaultRolloverStrategy +appender.CORRELATION.strategy.max = 20 +appender.CORRELATION.filter.threshold.type = ThresholdFilter +appender.CORRELATION.filter.threshold.level = INFO + +appender.ERROR_LOGFILE.type = RollingFile +appender.ERROR_LOGFILE.name = ERROR_LOGFILE +appender.ERROR_LOGFILE.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-errors.log +appender.ERROR_LOGFILE.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-errors-%d{MM-dd-yyyy}-%i.log.gz +appender.ERROR_LOGFILE.layout.type = PatternLayout +appender.ERROR_LOGFILE.layout.pattern = %d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n +appender.ERROR_LOGFILE.policies.type = Policies +appender.ERROR_LOGFILE.policies.time.type = TimeBasedTriggeringPolicy +appender.ERROR_LOGFILE.policies.time.interval = 1 +appender.ERROR_LOGFILE.policies.time.modulate = true +appender.ERROR_LOGFILE.policies.size.type = SizeBasedTriggeringPolicy +appender.ERROR_LOGFILE.policies.size.size = 10MB +appender.ERROR_LOGFILE.strategy.type = DefaultRolloverStrategy +appender.ERROR_LOGFILE.strategy.max = 20 +appender.ERROR_LOGFILE.filter.threshold.type = ThresholdFilter +appender.ERROR_LOGFILE.filter.threshold.level = WARN + +appender.CARBON_SYS_LOG.type = Syslog +appender.CARBON_SYS_LOG.name = CARBON_SYS_LOG +appender.CARBON_SYS_LOG.host = localhost +appender.CARBON_SYS_LOG.facility = USER +appender.CARBON_SYS_LOG.layout.type = PatternLayout +appender.CARBON_SYS_LOG.layout.pattern = [%d] %5p - %x %m {%c}%n +appender.CARBON_SYS_LOG.filter.threshold.type = ThresholdFilter +appender.CARBON_SYS_LOG.filter.threshold.level = DEBUG + +appender.OPEN_TRACING.type = RollingFile +appender.OPEN_TRACING.name = OPEN_TRACING +appender.OPEN_TRACING.fileName = ${sys:carbon.home}/repository/logs/wso2-apimgt-open-tracing.log +appender.OPEN_TRACING.filePattern = ${sys:carbon.home}/repository/logs/wso2-apimgt-open-tracing-%d{MM-dd-yyyy}-%i.log.gz +appender.OPEN_TRACING.layout.type = PatternLayout +appender.OPEN_TRACING.layout.pattern = %d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %m%nn +appender.OPEN_TRACING.policies.type = Policies +appender.OPEN_TRACING.policies.time.type = TimeBasedTriggeringPolicy +appender.OPEN_TRACING.policies.time.interval = 1 +appender.OPEN_TRACING.policies.time.modulate = true +appender.OPEN_TRACING.policies.size.type = SizeBasedTriggeringPolicy +appender.OPEN_TRACING.policies.size.size = 10MB +appender.OPEN_TRACING.strategy.type = DefaultRolloverStrategy +appender.OPEN_TRACING.strategy.max = 20 +appender.OPEN_TRACING.filter.threshold.type = ThresholdFilter +appender.OPEN_TRACING.filter.threshold.level = TRACE + +appender.TRACE_APPENDER.type = RollingFile +appender.TRACE_APPENDER.name = TRACE_APPENDER +appender.TRACE_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-trace.log +appender.TRACE_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-trace-%d{MM-dd-yyyy}.log +appender.TRACE_APPENDER.layout.type = PatternLayout +appender.TRACE_APPENDER.layout.pattern = %d{HH:mm:ss,SSS} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n +appender.TRACE_APPENDER.policies.type = Policies +appender.TRACE_APPENDER.policies.time.type = TimeBasedTriggeringPolicy +appender.TRACE_APPENDER.policies.time.interval = 1 +appender.TRACE_APPENDER.policies.time.modulate = true +appender.TRACE_APPENDER.strategy.type = DefaultRolloverStrategy +appender.TRACE_APPENDER.strategy.max = 20 + +appender.SERVICE_APPENDER.type = RollingFile +appender.SERVICE_APPENDER.name = SERVICE_APPENDER +appender.SERVICE_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-apigw-service.log +appender.SERVICE_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-apigw-service-%i.log +appender.SERVICE_APPENDER.layout.type = PatternLayout +appender.SERVICE_APPENDER.layout.pattern = %d{ISO8601} [%X{ip}-%X{host}] [%t] %5p %c{1} %m%n +appender.SERVICE_APPENDER.policies.type = Policies +appender.SERVICE_APPENDER.policies.size.type = SizeBasedTriggeringPolicy +appender.SERVICE_APPENDER.policies.size.size=1000KB +appender.SERVICE_APPENDER.strategy.type = DefaultRolloverStrategy +appender.SERVICE_APPENDER.strategy.max = 10 + +appender.osgi.type = PaxOsgi +appender.osgi.name = PaxOsgi +appender.osgi.filter = * + +loggers = AUDIT_LOG, trace-messages, org-apache-coyote, com-hazelcast, Owasp-CsrfGuard, org-apache-axis2-wsdl-codegen-writer-PrettyPrinter, org-apache-axis2-clustering, org-apache-catalina, org-apache-tomcat, org-wso2-carbon-apacheds, org-apache-directory-server-ldap, org-apache-directory-server-core-event, com-atomikos, org-quartz, org-apache-jackrabbit-webdav, org-apache-juddi, org-apache-commons-digester-Digester, org-apache-jasper-compiler-TldLocationsCache, org-apache-qpid, org-apache-qpid-server-Main, qpid-message, qpid-message-broker-listening, org-apache-tiles, org-apache-commons-httpclient, org-apache-solr, me-prettyprint-cassandra-hector-TimingLogger, org-apache-axis-enterprise, org-apache-directory-shared-ldap, org-apache-directory-server-ldap-handlers, org-apache-directory-shared-ldap-entry-DefaultServerAttribute, org-apache-directory-server-core-DefaultDirectoryService, org-apache-directory-shared-ldap-ldif-LdifReader, org-apache-directory-server-ldap-LdapProtocolHandler, org-apache-directory-server-core, org-apache-directory-server-ldap-LdapSession, DataNucleus, Datastore, Datastore-Schema, JPOX-Datastore, JPOX-Plugin, JPOX-MetaData, JPOX-Query, JPOX-General, JPOX-Enhancer, org-apache-hadoop-hive, hive, ExecMapper, ExecReducer, net-sf-ehcache-config-ConfigurationFactory, axis2Deployment, equinox, tomcat2, StAXDialectDetector, trace, synapse, synapse_transport, axis2, axis2_transport, org-wso2-carbon, hunsicker, thrift-publisher, service_logger, trace_logger, org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator, wso2-callhome, correlation, JAGGERY_LOG, API_LOG + +logger.API_LOG.name = API_LOG +logger.API_LOG.level = INFO +logger.API_LOG.appenderRef.API_LOGFILE.ref = API_LOGFILE +logger.API_LOG.additivity = false + +logger.JAGGERY_LOG.name = JAGGERY +logger.JAGGERY_LOG.level = INFO + +logger.AUDIT_LOG.name = AUDIT_LOG +logger.AUDIT_LOG.level = INFO +logger.AUDIT_LOG.appenderRef.AUDIT_LOGFILE.ref = AUDIT_LOGFILE +logger.AUDIT_LOG.additivity = false + +logger.trace-messages.name = trace.messages +logger.trace-messages.level = TRACE +logger.trace-messages.appenderRef.CARBON_TRACE_LOGFILE.ref = CARBON_TRACE_LOGFILE + +logger.org-apache-coyote.name = org.apache.coyote +logger.org-apache-coyote.level = WARN + +logger.com-hazelcast.name = com.hazelcast +logger.com-hazelcast.level = ERROR + +logger.Owasp-CsrfGuard.name = Owasp.CsrfGuard +logger.Owasp-CsrfGuard.level = WARN + +logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.name = org.apache.axis2.wsdl.codegen.writer.PrettyPrinter +logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.level = ERROR +logger.org-apache-axis2-wsdl-codegen-writer-PrettyPrinter.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-axis2-clustering.name = org.apache.axis2.clustering +logger.org-apache-axis2-clustering.level = INFO +logger.org-apache-axis2-clustering.additivity = false + +logger.org-apache.name = org.apache +logger.org-apache.level = INFO +logger.org-apache.additivity = false +logger.org-apache.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-catalina.name = org.apache.catalina +logger.org-apache-catalina.level = ERROR + +logger.org-apache-tomcat.name = org.apache.tomcat +logger.org-apache-tomcat.level = INFO + +logger.org-wso2-carbon-apacheds.name = org.wso2.carbon.apacheds +logger.org-wso2-carbon-apacheds.level = WARN + +logger.org-apache-directory-server-ldap.name = org.apache.directory.server.ldap +logger.org-apache-directory-server-ldap.level = ERROR + +logger.org-apache-directory-server-core-event.name = org.apache.directory.server.core.event +logger.org-apache-directory-server-core-event.level = WARN + +logger.com-atomikos.name = com.atomikos +logger.com-atomikos.level = INFO +logger.com-atomikos.additivity = false +logger.com-atomikos.appenderRef.ATOMIKOS_LOGFILE.ref = ATOMIKOS_LOGFILE + +logger.org-quartz.name = org.quartz +logger.org-quartz.level = WARN + +logger.org-apache-jackrabbit-webdav.name = org.apache.jackrabbit.webdav +logger.org-apache-jackrabbit-webdav.level = WARN + +logger.org-apache-juddi.name = org.apache.juddi +logger.org-apache-juddi.level = ERROR + +logger.org-apache-commons-digester-Digester.name = org.apache.commons.digester.Digester +logger.org-apache-commons-digester-Digester.level = WARN + +logger.org-apache-jasper-compiler-TldLocationsCache.name = org.apache.jasper.compiler.TldLocationsCache +logger.org-apache-jasper-compiler-TldLocationsCache.level = WARN + +logger.org-apache-qpid.name = org.apache.qpid +logger.org-apache-qpid.level = WARN + +logger.org-apache-qpid-server-Main.name = org.apache.qpid.server.Main +logger.org-apache-qpid-server-Main.level = INFO + +logger.qpid-message.name = qpid.message +logger.qpid-message.level = WARN + +logger.qpid-message-broker-listening.name = qpid.message.broker.listening +logger.qpid-message-broker-listening.level = INFO + +logger.org-apache-tiles.name = org.apache.tiles +logger.org-apache-tiles.level = WARN + +logger.org-apache-commons-httpclient.name = org.apache.commons.httpclient +logger.org-apache-commons-httpclient.level = ERROR + +logger.org-apache-solr.name = org.apache.solr +logger.org-apache-solr.level = ERROR + +logger.me-prettyprint-cassandra-hector-TimingLogger.name = me.prettyprint.cassandra.hector.TimingLogger +logger.me-prettyprint-cassandra-hector-TimingLogger.level = ERROR + +logger.org-wso2.name = org.wso2 +logger.org-wso2.level = INFO + +logger.org-wso2-carbon.name = org.wso2.carbon +logger.org-wso2-carbon.level = INFO + +logger.org-apache-axis-enterprise.name = org.apache.axis2.enterprise +logger.org-apache-axis-enterprise.level = FATAL +logger.org-apache-axis-enterprise.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-shared-ldap.name = org.apache.directory.shared.ldap +logger.org-apache-directory-shared-ldap.level = WARN +logger.org-apache-directory-shared-ldap.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-server-ldap-handlers.name = org.apache.directory.server.ldap.handlers +logger.org-apache-directory-server-ldap-handlers.level = WARN +logger.org-apache-directory-server-ldap-handlers.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +# Following are to remove false error messages from startup (IS) +logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.name = org.apache.directory.shared.ldap.entry.DefaultServerAttribute +logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.level = FATAL +logger.org-apache-directory-shared-ldap-entry-DefaultServerAttribute.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-server-core-DefaultDirectoryService.name = org.apache.directory.server.core.DefaultDirectoryService +logger.org-apache-directory-server-core-DefaultDirectoryService.level = ERROR +logger.org-apache-directory-server-core-DefaultDirectoryService.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-shared-ldap-ldif-LdifReader.name = org.apache.directory.shared.ldap.ldif.LdifReader +logger.org-apache-directory-shared-ldap-ldif-LdifReader.level = ERROR +logger.org-apache-directory-shared-ldap-ldif-LdifReader.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-server-ldap-LdapProtocolHandler.name = org.apache.directory.server.ldap.LdapProtocolHandler +logger.org-apache-directory-server-ldap-LdapProtocolHandler.level = ERROR +logger.org-apache-directory-server-ldap-LdapProtocolHandler.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-server-core.name = org.apache.directory.server.core +logger.org-apache-directory-server-core.level = ERROR +logger.org-apache-directory-server-core.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.org-apache-directory-server-ldap-LdapSession.name = org.apache.directory.server.ldap.LdapSession +logger.org-apache-directory-server-ldap-LdapSession.level = Error +logger.org-apache-directory-server-ldap-LdapSession.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE + +logger.correlation.name = correlation +logger.correlation.level = INFO +logger.correlation.appenderRef.CORRELATION.ref = CORRELATION +logger.correlation.additivity = false + +# Hive Related Log configurations +logger.DataNucleus.name = DataNucleus +logger.DataNucleus.level = ERROR + +logger.Datastore.name = Datastore +logger.Datastore.level = ERROR + +logger.Datastore-Schema.name = Datastore.Schema +logger.Datastore-Schema.level = ERROR + +logger.JPOX-Datastore.name = JPOX.Datastore +logger.JPOX-Datastore.level = ERROR + +logger.JPOX-Plugin.name = JPOX.Plugin +logger.JPOX-Plugin.level = ERROR + +logger.JPOX-MetaData.name = JPOX.MetaData +logger.JPOX-MetaData.level = ERROR + +logger.JPOX-Query.name = JPOX.Query +logger.JPOX-Query.level = ERROR + +logger.JPOX-General.name = JPOX.General +logger.JPOX-General.level = ERROR + +logger.JPOX-Enhancer.name = JPOX.Enhancer +logger.JPOX-Enhancer.level = ERROR + +logger.org-apache-hadoop-hive.name = org.apache.hadoop.hive +logger.org-apache-hadoop-hive.level = WARN + +logger.hive.name = hive +logger.hive.level = WARN + +logger.ExecMapper.name = ExecMapper +logger.ExecMapper.level = WARN + +logger.ExecReducer.name = ExecReducer +logger.ExecReducer.level = WARN + +logger.net-sf-ehcache-config-ConfigurationFactory.name = net.sf.ehcache.config.ConfigurationFactory +logger.net-sf-ehcache-config-ConfigurationFactory.level = ERROR + +logger.axis2Deployment.name = org.apache.axis2.deployment +logger.axis2Deployment.level = WARN + +logger.equinox.name = org.eclipse.equinox +logger.equinox.level = FATAL + +logger.tomcat2.name = tomcat +logger.tomcat2.level = FATAL + +logger.StAXDialectDetector.name = org.apache.axiom.util.stax.dialect.StAXDialectDetector +logger.StAXDialectDetector.level = ERROR + +logger.trace.name = tracer +logger.trace.level = TRACE +logger.trace.appenderRef.OPEN_TRACING.ref = OPEN_TRACING + +logger.synapse.name = org.apache.synapse +logger.synapse.level = INFO + +logger.synapse_transport.name = org.apache.synapse.transport +logger.synapse_transport.level = INFO + +logger.axis2.name = org.apache.axis2 +logger.axis2.level = INFO + +logger.axis2_transport.name = org.apache.axis2.transport +logger.axis2_transport.level = INFO + +logger.hunsicker.name = de.hunsicker.jalopy.io +logger.hunsicker.level = FATAL + +logger.synapse-headers.name = org.apache.synapse.transport.http.headers +logger.synapse-headers.level = DEBUG + +logger.synapse-wire.name = org.apache.synapse.transport.http.wire +logger.synapse-wire.level = DEBUG + +logger.thrift-publisher.name = org.wso2.carbon.databridge.agent.thrift.AsyncDataPublisher +logger.thrift-publisher.level = WARN + +logger.service_logger.name = SERVICE_LOGGER +logger.service_logger.level = INFO +logger.service_logger.additivity = false +logger.service_logger.appenderRef.SERVICE_APPENDER.ref = SERVICE_APPENDER + +logger.wso2-callhome.name = org.wso2.callhome +logger.wso2-callhome.level = INFO + +logger.trace_logger.name = TRACE_LOGGER +logger.trace_logger.level = INFO +logger.trace_logger.appenderRef.TRACE_APPENDER.ref = TRACE_APPENDER + +# root loggers +rootLogger.level = ERROR +rootLogger.appenderRef.CARBON_CONSOLE.ref = CARBON_CONSOLE +rootLogger.appenderRef.CARBON_LOGFILE.ref = CARBON_LOGFILE +rootLogger.appenderRef.ERROR_LOGFILE.ref = ERROR_LOGFILE +rootLogger.appenderRef.PaxOsgi.ref = PaxOsgi +#rootLogger.appenderReg.CARBON_SYS_LOG.ref = CARBON_SYS_LOG +#rootLogger.appenderRef.syslog.ref = syslog + +# bot detection feature appender +appender.BOTDATA_APPENDER.type = RollingFile +appender.BOTDATA_APPENDER.name = BOTDATA_APPENDER +appender.BOTDATA_APPENDER.fileName = ${sys:carbon.home}/repository/logs/wso2-BotDetectedData.log +appender.BOTDATA_APPENDER.filePattern = ${sys:carbon.home}/repository/logs/wso2-BotDetectedData-%d{MM-dd-yyyy}.log +appender.BOTDATA_APPENDER.layout.type = PatternLayout +appender.BOTDATA_APPENDER.layout.pattern = [%d] [%tenantId] %5p {%c} - %m%ex%n +appender.BOTDATA_APPENDER.policies.type = Policies +appender.BOTDATA_APPENDER.policies.time.type = TimeBasedTriggeringPolicy +appender.BOTDATA_APPENDER.policies.time.interval = 1 +appender.BOTDATA_APPENDER.policies.time.modulate = true +appender.BOTDATA_APPENDER.policies.size.type = SizeBasedTriggeringPolicy +appender.BOTDATA_APPENDER.policies.size.size = 10MB +appender.BOTDATA_APPENDER.strategy.type = DefaultRolloverStrategy +appender.BOTDATA_APPENDER.strategy.max = 20 + +logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.name = org.wso2.carbon.apimgt.gateway.mediators.BotDetectionMediator +logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.level = INFO +logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.appenderRef.BOTDATA_APPENDER.ref = BOTDATA_APPENDER +logger.org-wso2-carbon-apimgt-gateway-mediators-BotDetectionMediator.additivity = false + +category.SERVICE_APPENDER._OpenService_ = TRACE_APPENDER, BOTDATA_APPENDER diff --git a/platform/runtime/base/logging/entaxy-audit/LICENSE.txt b/platform/runtime/base/logging/entaxy-audit/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/base/logging/entaxy-audit/Logging-config.md b/platform/runtime/base/logging/entaxy-audit/Logging-config.md new file mode 100644 index 00000000..75ae5e2c --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/Logging-config.md @@ -0,0 +1,48 @@ +# Настройка логгирования в entaxy + + +Нужен артефакт cef-logger-layout версии __1.0.1__. +Его требуется любым доступным способом задеплоить +в karaf/entaxy. + +## Настройка лог-файла + +В файл `/etc/org.ops4j.pax.logging.cfg` необходимо добавить: + +``` +# CEF logger +log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE +log4j2.logger.AUDIT_FILE.level = INFO +log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger +log4j2.logger.AUDIT_FILE.additivity = false + +log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate +log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger +log4j2.appender.AUDIT_LOGFILE.children = CefFile +log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter +log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO + +log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile +log4j2.appender.AUDIT_LOGFILE_1.name = CefFile +log4j2.appender.AUDIT_LOGFILE_1.append = true +log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log +log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log +log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout +log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV +log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY +log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT +log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies +log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy +log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB +log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter +log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO +``` +Здесь используется композитный логгер, так что при необходимости +можно добавить вывод в консоль в cef или json формате +по образцу того, как было сделано в wso2. + +Логгируется: + +- Вход/выход в hawtio +- Все команды JAAS в karaf +- Изменения бандлов и конфигурации в karaf. \ No newline at end of file diff --git a/platform/runtime/base/logging/entaxy-audit/README.md b/platform/runtime/base/logging/entaxy-audit/README.md new file mode 100644 index 00000000..4bdffe0e --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/README.md @@ -0,0 +1,10 @@ +# Установка + +- Установите или просто скопируйте в deploy файл `cef-logger-layout-1.0.1.jar` +- Установите бандл `entaxy-audit-logging-1.0.1.jar` (`bundle:install mvn:ru.entaxy/entaxy-audit-logging/1.0.1`) и +запустите его (bundle:start ) +- Замените файл `/system/io/hawt/hawtio-osgi/2.14.1/hawtio-osgi-2.14.1.war` на одноименный из сборки + с зависимостью от `entaxy-audit-logging` (лучше сразу подготовить сборку с ним - он включается в WEB-INF/lib) + +Сконфигурируйте логгирование как описано в файле +`Logging-config.md` в этом репозитории. diff --git a/platform/runtime/base/logging/entaxy-audit/pom.xml b/platform/runtime/base/logging/entaxy-audit/pom.xml new file mode 100644 index 00000000..ab55d71c --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/pom.xml @@ -0,0 +1,88 @@ + + 4.0.0 + + ru.entaxy.platform + logging + 1.10.0 + + ru.entaxy.platform.logging + entaxy-audit + bundle + ENTAXY :: LOGGING :: AUDIT + ENTAXY :: LOGGING :: AUDIT + + + + ru.entaxy.audit* + + + + + + org.slf4j + slf4j-api + ${slf4j.version} + provided + + + javax.servlet + javax.servlet-api + + + com.google.code.gson + gson + ${gson.version} + + + org.apache.felix + org.apache.felix.eventadmin + 1.5.0 + + + + org.junit.jupiter + junit-jupiter + 5.8.1 + test + + + org.osgi + org.osgi.core + ${osgi.version} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + org.apache.felix + maven-bundle-plugin + true + + + ru.entaxy.audit.service.osgi.Activator + * + ${project.build.directory}/classes/ + + + + + package + + bundle + + + + + + + + diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/cfg/generated/fragments.xml b/platform/runtime/base/logging/entaxy-audit/src/main/cfg/generated/fragments.xml new file mode 100644 index 00000000..7d46d3ec --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/cfg/generated/fragments.xml @@ -0,0 +1,5 @@ + + + mvn:ru.entaxy.platform.logging/entaxy-audit/1.10.0/cfg/ru.entaxy.audit.interpreter.jmx + + \ No newline at end of file diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/cfg/ru.entaxy.audit.interpreter.jmx.cfg b/platform/runtime/base/logging/entaxy-audit/src/main/cfg/ru.entaxy.audit.interpreter.jmx.cfg new file mode 100644 index 00000000..5bc6dfc2 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/cfg/ru.entaxy.audit.interpreter.jmx.cfg @@ -0,0 +1,27 @@ +### +# ~~~~~~licensing~~~~~~ +# entaxy-audit +# ========== +# 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~~~~~~ +### +topics.ignore=GETATTRIBUTE,GETMBEANINFO +topics.process=INVOKE diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Actions.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Actions.java new file mode 100644 index 00000000..2d5d97dd --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Actions.java @@ -0,0 +1,31 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.data; + +public enum Actions { + LOGIN, + LOGOUT +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/AuditEvent.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/AuditEvent.java new file mode 100644 index 00000000..c0b10efe --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/AuditEvent.java @@ -0,0 +1,147 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.data; + +import ru.entaxy.audit.utils.AuditHelper; + +public class AuditEvent { + private final String target; + private final String category; + private final String suser; + private final String duser; + private final String message; + private final Outcome outcome; + + private final Severity severity; + private final String src; + + public AuditEvent(String target, String category, String suser, + String duser, String message, Outcome outcome, + Severity severity, String src) { + this.target = target; + this.category = category; + this.suser = suser; + this.duser = duser; + this.message = message; + this.outcome = outcome; + this.severity = severity; + this.src = src; + } + + public String getTarget() { + return target; + } + + public String getCategory() { + return category; + } + + public String getSuser() { + return suser; + } + + public String getDuser() { + return duser; + } + + public String getMessage() { + return message; + } + + public Outcome getOutcome() { + return outcome; + } + + public Severity getSeverity() { + return severity; + } + + public String getSrc() { + return src; + } + + public static class AuditLoggingEventBuilder { + private String target = AuditHelper.DEFAULT_TARGET; + private String category; + private String suser; + private String duser; + private String message; + + private String src; + private Outcome outcome = Outcome.SUCCESS; + private Severity severity = AuditHelper.DEFAULT_SEVERITY; + + + public static AuditLoggingEventBuilder getInstance() { + return new AuditLoggingEventBuilder(); + } + + public AuditLoggingEventBuilder target(String target) { + this.target = target; + return this; + } + + public AuditLoggingEventBuilder category(String category) { + this.category = category; + return this; + } + + public AuditLoggingEventBuilder suser(String suser) { + this.suser = suser; + return this; + } + + public AuditLoggingEventBuilder duser(String duser) { + this.duser = duser; + return this; + } + + public AuditLoggingEventBuilder message(String message) { + this.message = message; + return this; + } + + public AuditLoggingEventBuilder outcome(Outcome outcome) { + this.outcome = outcome; + return this; + } + + public AuditLoggingEventBuilder severity(Severity severity) { + this.severity = severity; + return this; + } + + public AuditLoggingEventBuilder src(String src) { + this.src = src; + return this; + } + + public AuditEvent build() { + return new AuditEvent(target, category, suser, duser, + message, outcome, severity, src); + } + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Outcome.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Outcome.java new file mode 100644 index 00000000..5e5d9aa1 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Outcome.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.data; + +public enum Outcome { + SUCCESS("Success"), FAILURE("Failed"); + private final String label; + + Outcome(String label) { + this.label = label; + } + + public String getLabel() { + return label; + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Severity.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Severity.java new file mode 100644 index 00000000..b0e013f4 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/data/Severity.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.data; + +public enum Severity { + INFO(3), WARNING(8), IMPORTANT(6); + + private final int value; + + Severity(int i) { + this.value = i; + } + + public int getValue() { + return value; + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/AuditService.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/AuditService.java new file mode 100644 index 00000000..08f99acd --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/AuditService.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import javax.security.auth.Subject; +import javax.servlet.http.HttpServletRequest; + +import org.osgi.service.event.Event; + +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.data.Outcome; + + +public interface AuditService { + void onAudit(AuditEvent record); + + void onLogin(String username, HttpServletRequest request, Outcome outcome); + + void onLogout(String username, HttpServletRequest request); + + void onOSGIEvent(Event event); + + void onFileChange(Event event); + + boolean interpret(Event event); + + void setRequestAndSubject(Subject subject, HttpServletRequest request); + + void setRequestAndUser(String user, HttpServletRequest request); +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/AuditServiceFactory.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/AuditServiceFactory.java new file mode 100644 index 00000000..f4fdb99f --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/AuditServiceFactory.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import ru.entaxy.audit.service.impl.AuditServiceImpl; + +public class AuditServiceFactory { + private static final AuditServiceImpl INSTANCE = new AuditServiceImpl(); + + + public static AuditService getAuditService() { + return INSTANCE; + } + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventConverter.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventConverter.java new file mode 100644 index 00000000..4aef2762 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventConverter.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import ru.entaxy.audit.data.AuditEvent; + +public interface EventConverter { + + default Class[] getAllowedClasses() { + if (getClass().isAnnotationPresent(EventConverterInfo.class)) { + return getClass().getAnnotation(EventConverterInfo.class).classes(); + } + return new Class[] {}; + }; + + AuditEvent convert(T event); + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventConverterInfo.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventConverterInfo.java new file mode 100644 index 00000000..0d696a70 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventConverterInfo.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface EventConverterInfo { + + Class[] classes(); + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventInterpreter.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventInterpreter.java new file mode 100644 index 00000000..12781026 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventInterpreter.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import org.osgi.service.event.Event; + +public interface EventInterpreter { + + InterpretedEvent interpret(Event origin); + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventSubscriber.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventSubscriber.java new file mode 100644 index 00000000..b67b0557 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/EventSubscriber.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import org.osgi.service.event.Event; +import org.osgi.service.event.EventHandler; +import ru.entaxy.audit.service.filter.EventRouter; + +public class EventSubscriber implements EventHandler { + private final EventRouter eventRouter; + + public EventSubscriber(EventRouter eventRouter) { + this.eventRouter = eventRouter; + } + + @Override + public void handleEvent(Event event) { + eventRouter.consumeEvent(event); + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/InterpretedEvent.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/InterpretedEvent.java new file mode 100644 index 00000000..64071f42 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/InterpretedEvent.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service; + +import java.util.HashMap; +import java.util.Map; + +import org.osgi.service.event.Event; + +public class InterpretedEvent { + + public enum EventResolution { + IGNORE, + PROCESS, + NONE + } + + public Event originalEvent; + + public EventResolution resolution = EventResolution.NONE; + + protected Map eventEssense = new HashMap<>(); + + public InterpretedEvent(Event origin) { + this.originalEvent = origin; + eventEssense.put("event.topic", origin.getTopic()); + } + + public Map getEventEssense() { + return eventEssense; + } + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/filter/EventRouter.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/filter/EventRouter.java new file mode 100644 index 00000000..a314d1aa --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/filter/EventRouter.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.filter; + +import java.util.Queue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.atomic.AtomicLong; + +import org.osgi.service.event.Event; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.audit.service.AuditService; + +public class EventRouter { + private final Queue events = new LinkedBlockingQueue<>(10_000); + private final AtomicLong counter = new AtomicLong(0); + private final AtomicLong consumed = new AtomicLong(0); + private final AtomicLong rejected = new AtomicLong(0); + private final ExecutorService executor = Executors.newFixedThreadPool(3, + (r) -> new Thread(r, "audit-logger-helper-thread #" + counter.getAndIncrement())); + private final AuditService auditService; + + private static final Logger LOGGER = LoggerFactory.getLogger(EventRouter.class); + + public EventRouter(AuditService service) { + this.auditService = service; + } + + private boolean processEvent(Event event) { + if (event == null) { + return false; + } + if (event.getTopic().contains("EXECUTED") && event.getProperty("command") != null) { + auditService.onOSGIEvent(event); + return true; + } else { + // if it's a log event + if (event.getTopic().startsWith("org/osgi/service/log")) { + String bundleSymbolicName = (String) event.getProperty("bundle.symbolicname"); + // if it's configuration update event + if (bundleSymbolicName != null && "org.apache.felix.fileinstall".equals(bundleSymbolicName)) { + Object message = event.getProperty("message"); + if (message instanceof String) { + String messageText = (String) message; + if (messageText.contains("Updating")) { + auditService.onFileChange(event); + return true; + } + } + } + } else { + return auditService.interpret(event); + } + } + return false; + } + + public String stats() { + return String.format("Consumed: %d, rejected: %d", consumed.get(), rejected.get()); + } + + public void consumeEvent(Event event) { + boolean added = events.offer(event); + if (added) { + executor.submit(() -> { + Event evt = events.poll(); + if (processEvent(evt)) { + consumed.incrementAndGet(); + } else { + rejected.incrementAndGet(); + } + }); + } else { + LOGGER.warn("Cannot consume event {}, queue is probably full", event); + } + } + + public void stop() { + executor.shutdown(); + events.clear(); + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioEventConverter.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioEventConverter.java new file mode 100644 index 00000000..f59ae53d --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioEventConverter.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.hawtio; + +import org.osgi.service.component.annotations.Component; + +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.data.Outcome; +import ru.entaxy.audit.data.Severity; +import ru.entaxy.audit.service.EventConverter; +import ru.entaxy.audit.service.EventConverterInfo; +import ru.entaxy.audit.service.InterpretedEvent; + +@Component(service = EventConverter.class, immediate = true) +@EventConverterInfo(classes = {HawtioInterpretedEvent.class}) +public class HawtioEventConverter implements EventConverter { + + @Override + public AuditEvent convert(T event) { + if (!(event instanceof HawtioInterpretedEvent)) + return null; + + HawtioInterpretedEvent hawtioEvent = (HawtioInterpretedEvent) event; + + AuditEvent result = AuditEvent.AuditLoggingEventBuilder.getInstance() + .target("auth") + .outcome(hawtioEvent.isSuccessful ? Outcome.SUCCESS : Outcome.FAILURE) + .message(String.format("%s", hawtioEvent.getMessage())) + .severity(Severity.IMPORTANT) + .category(hawtioEvent.getAction()) + .suser(hawtioEvent.getUser()) + .src(hawtioEvent.getSrc()) + .build(); + + return result; + + } + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioEventInterpreter.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioEventInterpreter.java new file mode 100644 index 00000000..095c7c67 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioEventInterpreter.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.hawtio; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ConfigurationPolicy; +import org.osgi.service.event.Event; + +import ru.entaxy.audit.service.EventInterpreter; +import ru.entaxy.audit.service.InterpretedEvent; + +@Component(service = EventInterpreter.class, immediate = true, configurationPolicy = ConfigurationPolicy.OPTIONAL) +public class HawtioEventInterpreter implements EventInterpreter { + + private static final String HAWTIO_AUDIT_TOPIC = "entaxy/hawtio/audit"; + + @Override + public InterpretedEvent interpret(Event origin) { + + if (!HAWTIO_AUDIT_TOPIC.equals(origin.getTopic())) + return null; + + return new HawtioInterpretedEvent(origin); + + } + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioInterpretedEvent.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioInterpretedEvent.java new file mode 100644 index 00000000..47c4ccc3 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/hawtio/HawtioInterpretedEvent.java @@ -0,0 +1,74 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.hawtio; + +import org.osgi.service.event.Event; + +import ru.entaxy.audit.service.InterpretedEvent; + +public class HawtioInterpretedEvent extends InterpretedEvent { + + String action; + + String message; + + String user; + + String src; + + boolean isSuccessful; + + public HawtioInterpretedEvent(Event origin) { + super(origin); + action = origin.getProperty("category").toString(); + message = origin.getProperty("message").toString(); + user = origin.getProperty("user").toString(); + src = origin.getProperty("src").toString(); + isSuccessful = (Boolean) origin.getProperty("result"); + } + + public String getAction() { + return action; + } + + public String getMessage() { + return message; + } + + public String getUser() { + return user; + } + + public String getSrc() { + return src; + } + + public boolean isSuccessful() { + return isSuccessful; + } + + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/AuditServiceImpl.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/AuditServiceImpl.java new file mode 100644 index 00000000..d4736b74 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/AuditServiceImpl.java @@ -0,0 +1,143 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.impl; + +import javax.security.auth.Subject; +import javax.servlet.http.HttpServletRequest; + +import org.osgi.service.event.Event; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.data.Outcome; +import ru.entaxy.audit.service.AuditService; +import ru.entaxy.audit.service.InterpretedEvent; +import ru.entaxy.audit.utils.AuditHelper; + +public class AuditServiceImpl implements AuditService { + + private static final Logger LOG = LoggerFactory.getLogger(AuditServiceImpl.class); + + private final WebLoginModule webLoginModule = new WebLoginModule(); + private final OSGIEventModule osgiEventModule = new OSGIEventModule(); + + @Override + public void onAudit(AuditEvent record) { + throw new RuntimeException("Not implemented"); + } + + @Override + public void onLogin(String username, HttpServletRequest request, Outcome outcome) { + webLoginModule.onLogin(username, request, outcome); + } + + @Override + public void onLogout(String username, HttpServletRequest request) { + webLoginModule.onLogout(username, request); + } + + @Override + public void onOSGIEvent(Event event) { + osgiEventModule.onEvent(event); + } + + @Override + public void onFileChange(Event event) { + osgiEventModule.onFileChange(event); + } + + @Override + public boolean interpret(Event event) { + if (InterpreterService.INSTANCE == null) + return false; + InterpretedEvent result = InterpreterService.INSTANCE.interpret(event); + + if (result == null) { + if (LOG.isTraceEnabled()) + LOG.trace("Event from topic [{}] not interpreted", event.getTopic()); + return false; + } + + if (result.resolution.equals(InterpretedEvent.EventResolution.IGNORE)) { + if (LOG.isTraceEnabled()) + LOG.trace("Event from topic [{}] IGNORED; interpreted as [{}] -> [{}]", event.getTopic(), + result.getClass().getName()); + return false; + } + + + if (ConverterService.INSTANCE == null) + return false; + + AuditEvent convertedEvent = ConverterService.INSTANCE.convert(result); + + if (convertedEvent == null) { + if (LOG.isDebugEnabled()) + LOG.debug("NOT CONVERTED: Event from topic [{}] interpreted as [{}]", event.getTopic(), + result.getClass().getName()); + return false; + } + + Subject subject = (Subject) event.getProperty("subject"); + boolean processed = false; + + String suser = "local"; + String address = "localhost"; + + if (subject != null) { + suser = AuditHelper.findRemoteUser(subject); + address = AuditHelper.findAddress(subject); + } + + AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance() + .category(convertedEvent.getCategory()) + .duser(convertedEvent.getDuser()) + .message(convertedEvent.getMessage()) + .outcome(convertedEvent.getOutcome()) + .severity(convertedEvent.getSeverity()) + .src(convertedEvent.getSrc() != null ? convertedEvent.getSrc() : address) + .suser(convertedEvent.getSuser() != null ? convertedEvent.getSuser() : suser) + .target(convertedEvent.getTarget()) + .build(); + + + AuditHelper.log(auditEvent); + processed = true; + + return processed; + } + + @Override + public void setRequestAndSubject(Subject subject, HttpServletRequest request) { + webLoginModule.setMDC(subject, request); + } + + @Override + public void setRequestAndUser(String user, HttpServletRequest request) { + webLoginModule.setMDC(user, request); + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/ConverterService.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/ConverterService.java new file mode 100644 index 00000000..70fcc9b3 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/ConverterService.java @@ -0,0 +1,101 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.impl; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.service.EventConverter; +import ru.entaxy.audit.service.InterpretedEvent; + +@Component(service = ConverterService.class, immediate = true) +public class ConverterService { + + static public ConverterService INSTANCE = null; + + protected Map, Set> converters = new HashMap<>(); + + protected Object convertersLock = new Object(); + + @Activate + public void activate() { + INSTANCE = this; + } + + @Deactivate + public void deactivate() { + INSTANCE = null; + } + + @Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY, + policy = ReferencePolicy.DYNAMIC, unbind = "removeConverter") + public void addInterpreter(EventConverter converter) { + synchronized (convertersLock) { + for (Class clazz : converter.getAllowedClasses()) { + this.converters.putIfAbsent(clazz, new HashSet<>()); + this.converters.get(clazz).add(converter); + } + } + } + + public void removeConverter(EventConverter converter) { + synchronized (convertersLock) { + for (Class clazz : converter.getAllowedClasses()) { + if (converters.containsKey(clazz)) + converters.get(clazz).remove(converter); + } + } + + } + + public AuditEvent convert(T event) { + AuditEvent result = null; + if (converters.containsKey(event.getClass())) { + for (EventConverter converter : converters.get(event.getClass())) { + try { + result = converter.convert(event); + } catch (Exception ignore) { + // NOOP + } + if (result != null) + break; + } + + } + return result; + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/InterpreterService.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/InterpreterService.java new file mode 100644 index 00000000..bd602f15 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/InterpreterService.java @@ -0,0 +1,91 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.osgi.service.event.Event; + +import ru.entaxy.audit.service.EventInterpreter; +import ru.entaxy.audit.service.InterpretedEvent; + +@Component(service = InterpreterService.class, immediate = true) +public class InterpreterService { + + static public InterpreterService INSTANCE = null; + + protected List interpreters = new ArrayList<>(); + + protected Object interpretersLock = new Object(); + + @Activate + public void activate() { + INSTANCE = this; + } + + @Deactivate + public void deactivate() { + INSTANCE = null; + } + + @Reference(cardinality = ReferenceCardinality.MULTIPLE, policyOption = ReferencePolicyOption.GREEDY, + policy = ReferencePolicy.DYNAMIC, unbind = "removeInterpreter") + public void addInterpreter(EventInterpreter interpreter) { + synchronized (interpretersLock) { + if (!interpreters.contains(interpreter)) + interpreters.add(interpreter); + } + } + + public void removeInterpreter(EventInterpreter interpreter) { + synchronized (interpretersLock) { + interpreters.remove(interpreter); + } + + } + + public InterpretedEvent interpret(Event event) { + InterpretedEvent result = null; + for (EventInterpreter interpreter : interpreters) { + try { + result = interpreter.interpret(event); + } catch (Exception ignore) { + // NOOP + } + if (result != null) + break; + } + return result; + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/OSGIEventModule.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/OSGIEventModule.java new file mode 100644 index 00000000..b72d2196 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/OSGIEventModule.java @@ -0,0 +1,117 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.impl; + + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.LongAdder; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.security.auth.Subject; + +import org.osgi.service.event.Event; + +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.data.Severity; +import ru.entaxy.audit.utils.AuditHelper; +import ru.entaxy.audit.utils.CommandWeight; + +public class OSGIEventModule { + + private Map processedCommands = new ConcurrentHashMap<>(); + private Map skippedCommands = new ConcurrentHashMap<>(); + + private final Set targets = new HashSet() {{ + add("jaas"); + }}; + + private final static Pattern COMMAND_PATTERN = Pattern.compile("^(.+):([A-Za-z-]+)\\s?+(.+)?$"); + private final static Pattern FILE_PATTERN = Pattern.compile("^Updating ([a-zA-Z]+)\\s+(from)?\\s?(.+)$"); + + public void onEvent(Event event) { + String command = (String) event.getProperty("command"); + if (command == null) { + return; + } + Subject subject = (Subject) event.getProperty("subject"); + boolean processed = false; + Matcher m = checkCommand(command); + if (m != null && subject != null) { + String suser = AuditHelper.findRemoteUser(subject); + String address = AuditHelper.findAddress(subject); + String target = m.group(1); + String commandName = m.group(2); + String arguments = m.group(3); + if (targets.contains(target)) { + AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance() + .target(target) + .suser(suser) + .src(address) + .category(commandName) + .severity(CommandWeight.getByTarget(target)) + .message(arguments == null ? "" : arguments).build(); + AuditHelper.log(auditEvent); + processed = true; + } + } + Map target = processed ? processedCommands : skippedCommands; + target.computeIfAbsent(command, (s) -> new LongAdder()).increment(); + } + + private Matcher checkCommand(String command) { + Matcher m = COMMAND_PATTERN.matcher(command); + if (m.find()) { + return m; + } + return null; + } + + public void onFileChange(Event event) { + String message = (String) event.getProperty("message"); + Matcher m = FILE_PATTERN.matcher(message); + if (m.find()) { + String filename = m.group(3); + String changeSubject = m.group(1); + String target = "Update " + changeSubject; + if (changeSubject.equals("bundle") || changeSubject.equals("configuration")) { + AuditEvent auditEvent = AuditEvent.AuditLoggingEventBuilder.getInstance() + .target(target) + .suser("local") + .src("localhost") + .category(filename) + .severity(Severity.WARNING) + .message(message).build(); + AuditHelper.log(auditEvent); + processedCommands.computeIfAbsent(target, (s) -> new LongAdder()).increment(); + } + skippedCommands.computeIfAbsent(target, (s) -> new LongAdder()).increment(); + } + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/WebLoginModule.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/WebLoginModule.java new file mode 100644 index 00000000..a2137687 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/impl/WebLoginModule.java @@ -0,0 +1,93 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.impl; + +import org.slf4j.MDC; +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.utils.AuditHelper; +import ru.entaxy.audit.utils.Constants; +import ru.entaxy.audit.data.Outcome; +import ru.entaxy.audit.data.Severity; + +import javax.security.auth.Subject; +import javax.servlet.http.HttpServletRequest; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class WebLoginModule { + public void onLogin(String username, HttpServletRequest request, Outcome outcome) { + String remoteAddress = requestRemoteAddress(request); + AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance() + .suser(username) + .outcome(outcome) + .severity(outcome == Outcome.SUCCESS ? Severity.INFO : Severity.WARNING) + .src(remoteAddress) + .category(outcome == Outcome.SUCCESS ? "Login success" : "Login failed") + .target("auth") + .build(); + AuditHelper.log(event); + } + + public void onLogout(String username, HttpServletRequest request) { + String remoteAddress = requestRemoteAddress(request); + AuditEvent event = AuditEvent.AuditLoggingEventBuilder.getInstance() + .suser(username) + .outcome(Outcome.SUCCESS) + .severity(Severity.INFO) + .src(remoteAddress) + .category("Logout") + .target("auth") + .build(); + AuditHelper.log(event); + } + + private static String requestRemoteAddress(HttpServletRequest request) { + return Optional.ofNullable(request.getHeader(Constants.X_FORWARDER_FOR)) + .orElse(request.getRemoteHost()); + } + + public void setMDC(Subject subject, HttpServletRequest request) { + String remoteUser = AuditHelper.findRemoteUser(subject); + saveMDC(remoteUser, request); + } + + public void setMDC(String username, HttpServletRequest request) { + saveMDC(username, request); + } + + private void saveMDC(String username, HttpServletRequest request) { + Map contextMap = MDC.getCopyOfContextMap(); + if (contextMap == null) { + contextMap = new HashMap<>(); + } + contextMap.put(Constants.HTTP_REQUEST_USER, username); + contextMap.put(Constants.HTTP_REQUEST_REMOTE_IP, requestRemoteAddress(request)); + contextMap.put(Constants.HTTP_REQUEST_SERVER_IP, request.getServerName()); + MDC.setContextMap(contextMap); + } + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXEventInterpreter.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXEventInterpreter.java new file mode 100644 index 00000000..adb8b53c --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXEventInterpreter.java @@ -0,0 +1,140 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.jmx; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ConfigurationPolicy; +import org.osgi.service.component.annotations.Modified; +import org.osgi.service.event.Event; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.audit.service.EventInterpreter; +import ru.entaxy.audit.service.InterpretedEvent; +import ru.entaxy.audit.service.InterpretedEvent.EventResolution; + +@Component(service = EventInterpreter.class, immediate = true, configurationPid = "ru.entaxy.audit.interpreter.jmx", + configurationPolicy = ConfigurationPolicy.OPTIONAL) +public class JMXEventInterpreter implements EventInterpreter { + + private static final Logger LOG = LoggerFactory.getLogger(JMXEventInterpreter.class); + + public static final String JMX_AUDIT_TOPIC_PREFIX = "javax/management/MBeanServer"; + + public static final String JMX_AUDIT_INVOKE_SUBTOPIC = "INVOKE"; + + protected static final String PROP_IGNORE_TOPICS = "topics.ignore"; + + protected static final String PROP_PROCESS_TOPICS = "topics.process"; + + protected List topicsToIgnore = new ArrayList<>(); + + protected List topicsToProcess = new ArrayList<>(); + + @Activate + public void activate(Map properties) { + parseProperties(properties); + } + + @Modified + public void modified(Map properties) { + parseProperties(properties); + } + + protected void parseProperties(Map properties) { + if (properties == null) + return; + if (LOG.isDebugEnabled()) + LOG.debug("\n CONFIGURATION :: \n " + properties.toString()); + if (properties.containsKey(PROP_IGNORE_TOPICS)) { + String ignoreTopics = (String) properties.get(PROP_IGNORE_TOPICS); + if (ignoreTopics == null) + topicsToIgnore = new ArrayList<>(); + else { + topicsToIgnore = Arrays.asList(ignoreTopics.split(",")); + } + } else { + topicsToIgnore = new ArrayList<>(); + } + if (properties.containsKey(PROP_PROCESS_TOPICS)) { + String processTopics = (String) properties.get(PROP_PROCESS_TOPICS); + if (processTopics == null) + topicsToProcess = new ArrayList<>(); + else { + topicsToProcess = Arrays.asList(processTopics.split(",")); + } + } else { + topicsToProcess = new ArrayList<>(); + } + + } + + @Override + public InterpretedEvent interpret(Event origin) { + if (!origin.getTopic().startsWith(JMX_AUDIT_TOPIC_PREFIX)) + return null; + + JMXInterpretedEvent result; + + String subtopic = origin.getTopic().substring(JMX_AUDIT_TOPIC_PREFIX.length() + 1); + + if (subtopic.startsWith(JMX_AUDIT_INVOKE_SUBTOPIC)) + result = new JMXInvokeEvent(origin); + else + result = new JMXInterpretedEvent(origin); + + result.subtopic = subtopic; + + result.resolution = EventResolution.IGNORE; + + if (!topicsToProcess.isEmpty()) { + for (String process : topicsToProcess) + if (result.subtopic.startsWith(process)) { + result.resolution = EventResolution.PROCESS; + break; + } + + } else { + result.resolution = EventResolution.PROCESS; + } + + for (String ignore : topicsToIgnore) + if (result.subtopic.startsWith(ignore)) { + result.resolution = EventResolution.IGNORE; + break; + } + + return result; + } + + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXInterpretedEvent.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXInterpretedEvent.java new file mode 100644 index 00000000..0f463c96 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXInterpretedEvent.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.jmx; + +import org.osgi.service.event.Event; + +import ru.entaxy.audit.service.InterpretedEvent; + +public class JMXInterpretedEvent extends InterpretedEvent { + + protected String subtopic = null; + + public JMXInterpretedEvent(Event origin) { + super(origin); + this.eventEssense.put("event.source", "jmx"); + } + + public JMXInterpretedEvent subtopic(String value) { + setSubtopic(value); + return this; + } + + public String getSubtopic() { + return subtopic; + } + + public void setSubtopic(String subtopic) { + this.subtopic = subtopic; + this.eventEssense.put("event.subtopic", this.subtopic); + } + + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXInvokeEvent.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXInvokeEvent.java new file mode 100644 index 00000000..c5a490d3 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/jmx/JMXInvokeEvent.java @@ -0,0 +1,104 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.jmx; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.management.ObjectName; + +import org.osgi.service.event.Event; + +public class JMXInvokeEvent extends JMXInterpretedEvent { + + public static final String PROP_PARAMS = "params"; + + protected ObjectName objectName; + + protected String methodName; + + protected Object[] methodParams; + + protected Map objectNameData = new HashMap<>(); + + public JMXInvokeEvent(Event origin) { + super(origin); + if (this.originalEvent.containsProperty(PROP_PARAMS)) { + + Object[] data = (Object[]) this.originalEvent.getProperty(PROP_PARAMS); + + setObjectName((ObjectName) data[0]); + setMethodName((String) data[1]); + setMethodParams((Object[]) data[2]); + + } + } + + protected void parseObjectName() { + this.objectNameData.clear(); + this.objectNameData.put("jmx.domain", this.objectName.getDomain()); + Hashtable properties = this.objectName.getKeyPropertyList(); + for (Map.Entry entry : properties.entrySet()) { + this.objectNameData.put("jmx.property." + entry.getKey(), entry.getValue()); + } + + } + + public ObjectName getObjectName() { + return objectName; + } + + public void setObjectName(ObjectName objectName) { + this.objectName = objectName; + parseObjectName(); + } + + public String getMethodName() { + return methodName; + } + + public void setMethodName(String methodName) { + this.methodName = methodName; + this.eventEssense.put("jmx.methodName", methodName); + } + + public Object[] getMethodParams() { + return methodParams; + } + + public void setMethodParams(Object[] methodParams) { + this.methodParams = methodParams; + } + + @Override + public Map getEventEssense() { + Map result = new HashMap<>(super.getEventEssense()); + result.putAll(this.objectNameData); + return result; + } + +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/osgi/Activator.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/osgi/Activator.java new file mode 100644 index 00000000..1ee3dde9 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/service/osgi/Activator.java @@ -0,0 +1,115 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.service.osgi; + +import java.util.Dictionary; +import java.util.Hashtable; + +import org.osgi.framework.BundleActivator; +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.event.EventConstants; +import org.osgi.service.event.EventHandler; + +import ru.entaxy.audit.service.AuditService; +import ru.entaxy.audit.service.AuditServiceFactory; +import ru.entaxy.audit.service.EventSubscriber; +import ru.entaxy.audit.service.filter.EventRouter; +import ru.entaxy.audit.service.impl.AuditServiceImpl; + +public class Activator implements BundleActivator { + + private static final String LOGS_TOPIC = "org/osgi/service/*"; + private static final String COMMANDS_TOPIC = "org/apache/karaf/shell/console/*"; + private static final String JMX_AUDIT_TOPIC = "javax/management/MBeanServer/*"; + private static final String HAWTIO_AUDIT_TOPIC = "entaxy/hawtio/audit"; + + private ServiceRegistration listenerRegistration = null; + private ServiceRegistration serviceRegistration = null; + private ServiceRegistration commandRegistration = null; + private ServiceRegistration jmxRegistration = null; + private ServiceRegistration hawtioRegistration = null; + + private ServiceRegistration eventRouterRegistration = null; + + private EventRouter eventRouter; + + @Override + public void start(BundleContext bundleContext) throws Exception { + // System.err.println("I'm activating!"); + AuditService auditService = AuditServiceFactory.getAuditService(); + serviceRegistration = + bundleContext.registerService(AuditService.class.getName(), new AuditServiceImpl(), new Hashtable<>()); + eventRouter = new EventRouter(auditService); + eventRouterRegistration = bundleContext.registerService(EventRouter.class, eventRouter, new Hashtable<>()); + + EventHandler logSubscriber = new EventSubscriber(eventRouter); + EventHandler commandsSubscriber = new EventSubscriber(eventRouter); + EventHandler jmxSubscriber = new EventSubscriber(eventRouter); + EventHandler hawtioSubscriber = new EventSubscriber(eventRouter); + + Dictionary events = new Hashtable<>(); + events.put(EventConstants.EVENT_TOPIC, LOGS_TOPIC); + listenerRegistration = bundleContext.registerService(EventHandler.class.getName(), logSubscriber, events); + + Dictionary commandEvents = new Hashtable<>(); + commandEvents.put(EventConstants.EVENT_TOPIC, COMMANDS_TOPIC); + commandRegistration = + bundleContext.registerService(EventHandler.class.getName(), commandsSubscriber, commandEvents); + + Dictionary jmxEvents = new Hashtable<>(); + jmxEvents.put(EventConstants.EVENT_TOPIC, JMX_AUDIT_TOPIC); + jmxRegistration = + bundleContext.registerService(EventHandler.class.getName(), jmxSubscriber, jmxEvents); + + Dictionary hawtioEvents = new Hashtable<>(); + hawtioEvents.put(EventConstants.EVENT_TOPIC, HAWTIO_AUDIT_TOPIC); + hawtioRegistration = + bundleContext.registerService(EventHandler.class.getName(), hawtioSubscriber, hawtioEvents); + } + + @Override + public void stop(BundleContext bundleContext) throws Exception { + if (listenerRegistration != null) { + listenerRegistration.unregister(); + } + if (commandRegistration != null) { + commandRegistration.unregister(); + } + if (jmxRegistration != null) { + jmxRegistration.unregister(); + } + if (serviceRegistration != null) { + serviceRegistration.unregister(); + } + if (eventRouterRegistration != null) { + eventRouterRegistration.unregister(); + } + if (eventRouter != null) { + eventRouter.stop(); + } + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/AuditHelper.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/AuditHelper.java new file mode 100644 index 00000000..9085f49e --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/AuditHelper.java @@ -0,0 +1,103 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.utils; + +import com.google.gson.JsonObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.data.Severity; + +import javax.security.auth.Subject; +import java.lang.reflect.Method; +import java.security.Principal; +import java.util.Optional; +import java.util.Set; +import java.util.function.Function; + +public class AuditHelper { + public static final String TARGET_ACTION = "action"; + + public static final Severity DEFAULT_SEVERITY = Severity.IMPORTANT; + public static final String DEFAULT_TARGET = TARGET_ACTION; + private static final Logger AUDIT = LoggerFactory.getLogger(Constants.LOG_FACILITY_NAME); + + private static final Logger logger = LoggerFactory.getLogger(AuditHelper.class); + + public static void log(AuditEvent event) { + JsonObject logRecord = new JsonObject(); + logRecord.addProperty("isEmdevEvents", true); + logRecord.addProperty("typ", event.getTarget()); + logRecord.addProperty("action", event.getCategory()); + logRecord.addProperty("performedBy", event.getSuser()); + + JsonObject info = new JsonObject(); + if (event.getSrc() != null) { + info.addProperty("src", event.getSrc()); + } + if (event.getDuser() != null) { + info.addProperty("duser", event.getDuser()); + } + info.addProperty("suser", event.getSuser()); + info.addProperty("severity", event.getSeverity().getValue()); + info.addProperty("msg", event.getMessage()); + info.addProperty("outcome", event.getOutcome().getLabel()); + logRecord.add("info", info); + + AUDIT.info(logRecord.toString()); + } + + public static String findRemoteUser(Subject subject) { + return findAndProcessPrincipal(subject, "UserPrincipal", Principal::getName); + } + + private static String findAndProcessPrincipal(Subject subject, String principalName, Function mapping) { + Set principals = subject.getPrincipals(); + if (principals != null) { + Optional userName = principals.stream() + .filter(p -> p.getClass().getSimpleName().startsWith(principalName)).findFirst() + .map(mapping); + return userName.orElse(null); + } + return null; + } + + public static String findAddress(Subject subject) { + return findAndProcessPrincipal(subject, "ClientPrincipal", AuditHelper::getAddress); + } + + private static String getAddress(Principal p) { + //We're assumiming to process Karaf's ClientPrincipal. We need method getAddress(); + try { + Method m = p.getClass().getMethod("getAddress"); + Object result = m.invoke(p); + return (String) result; + } catch (Throwable t) { + logger.error("Cannot get address from principal {}:", p, t); + return null; + } + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/CommandWeight.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/CommandWeight.java new file mode 100644 index 00000000..cae3b4c2 --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/CommandWeight.java @@ -0,0 +1,57 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.utils; + +import ru.entaxy.audit.data.Severity; + +public enum CommandWeight { + JAAS("jaas", Severity.IMPORTANT); + + private final String target; + private final Severity severity; + + CommandWeight(String target, Severity severity) { + this.target = target; + this.severity = severity; + } + + public String getTarget() { + return target; + } + + public Severity getSeverity() { + return severity; + } + + public static Severity getByTarget(String target) { + for (CommandWeight value : values()) { + if (value.getTarget().equals(target)) { + return value.severity; + } + } + return Severity.INFO; + } +} diff --git a/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/Constants.java b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/Constants.java new file mode 100644 index 00000000..84094cfd --- /dev/null +++ b/platform/runtime/base/logging/entaxy-audit/src/main/java/ru/entaxy/audit/utils/Constants.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * entaxy-audit + * ========== + * 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~~~~~~ + */ +package ru.entaxy.audit.utils; + +public class Constants { + public static final String X_FORWARDER_FOR = "X-Forwarder-For"; + public static final String LOG_FACILITY_NAME = "AUDIT_LOGFILE"; + + public static final String HTTP_REQUEST_USER = "Audit-HTTP-Request-User"; + public static final String HTTP_REQUEST_REMOTE_IP = "Audit-HTTP-Request-Remote-IP"; + public static final String HTTP_REQUEST_SERVER_IP = "Audit-HTTP-Request-Server-IP"; + + private Constants() {} + +} diff --git a/platform/runtime/base/logging/pom.xml b/platform/runtime/base/logging/pom.xml new file mode 100644 index 00000000..39d8c9fe --- /dev/null +++ b/platform/runtime/base/logging/pom.xml @@ -0,0 +1,102 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime + base + 1.10.0 + + ru.entaxy.platform + logging + pom + ENTAXY :: LOGGING + ENTAXY :: LOGGING + + cef-logger-layout + entaxy-audit + + + + + + combine-logging-cfg + + false + + src/main/cfg/org.ops4j.pax.logging.cfg + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + + + copy-logging-from-underlying + prepare-package + + copy + + + + + ru.entaxy.esb.underlying + entaxy-underlying-configuration + ${project.version} + cfg + org.ops4j.pax.logging + true + ${project.build.directory}/combine-logging + 1.cfg + + + + + + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + + combine_logging_cfg + prepare-package + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/base/logging/src/main/cfg/generated/fragments.xml b/platform/runtime/base/logging/src/main/cfg/generated/fragments.xml new file mode 100644 index 00000000..ae37b1b9 --- /dev/null +++ b/platform/runtime/base/logging/src/main/cfg/generated/fragments.xml @@ -0,0 +1,5 @@ + + + mvn:ru.entaxy.platform/logging/1.10.0/cfg/org.ops4j.pax.logging + + \ No newline at end of file diff --git a/platform/runtime/base/logging/src/main/cfg/org.ops4j.pax.logging.cfg b/platform/runtime/base/logging/src/main/cfg/org.ops4j.pax.logging.cfg new file mode 100644 index 00000000..e4e0af04 --- /dev/null +++ b/platform/runtime/base/logging/src/main/cfg/org.ops4j.pax.logging.cfg @@ -0,0 +1,51 @@ +### +# ~~~~~~licensing~~~~~~ +# logging +# ========== +# 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~~~~~~ +### +# Entaxy CEF logger +log4j2.logger.AUDIT_FILE.name = AUDIT_LOGFILE +log4j2.logger.AUDIT_FILE.level = INFO +log4j2.logger.AUDIT_FILE.appenderRef.AUDIT_LOGFILE.ref = AuditCompositeLogger +log4j2.logger.AUDIT_FILE.additivity = false + +log4j2.appender.AUDIT_LOGFILE.type = CEFAggregate +log4j2.appender.AUDIT_LOGFILE.name = AuditCompositeLogger +log4j2.appender.AUDIT_LOGFILE.children = CefFile +log4j2.appender.AUDIT_LOGFILE.filter.threshold.type = ThresholdFilter +log4j2.appender.AUDIT_LOGFILE.filter.threshold.level = INFO + +log4j2.appender.AUDIT_LOGFILE_1.type = RollingRandomAccessFile +log4j2.appender.AUDIT_LOGFILE_1.name = CefFile +log4j2.appender.AUDIT_LOGFILE_1.append = true +log4j2.appender.AUDIT_LOGFILE_1.fileName = ${karaf.log}/cef-audit.log +log4j2.appender.AUDIT_LOGFILE_1.filePattern = ${karaf.log}/cef-audit-%d{MM-dd-yyyy}.log +log4j2.appender.AUDIT_LOGFILE_1.layout.type = CEFLayout +log4j2.appender.AUDIT_LOGFILE_1.layout.vendor = EMDEV +log4j2.appender.AUDIT_LOGFILE_1.layout.product = ENTAXY +log4j2.appender.AUDIT_LOGFILE_1.layout.productVersion = 1.1.10-SNAPSHOT +log4j2.appender.AUDIT_LOGFILE_1.policies.type = Policies +log4j2.appender.AUDIT_LOGFILE_1.policies.size.type = SizeBasedTriggeringPolicy +log4j2.appender.AUDIT_LOGFILE_1.policies.size.size = 10MB +log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.type = ThresholdFilter +log4j2.appender.AUDIT_LOGFILE_1.filter.threshold.level = INFO diff --git a/platform/runtime/base/objects-base/object-factory/src/main/java/ru/entaxy/platform/base/objects/factory/EntaxyFactoryRegistry.java b/platform/runtime/base/objects-base/object-factory/src/main/java/ru/entaxy/platform/base/objects/factory/EntaxyFactoryRegistry.java new file mode 100644 index 00000000..79cb7a9b --- /dev/null +++ b/platform/runtime/base/objects-base/object-factory/src/main/java/ru/entaxy/platform/base/objects/factory/EntaxyFactoryRegistry.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-factory + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.base.objects.factory; + +import java.util.Collection; + + +public interface EntaxyFactoryRegistry { + + Collection getAllFactories(); + + String getParentFactory(String factoryId); + +} diff --git a/platform/runtime/base/objects-base/object-factory/src/main/java/ru/entaxy/platform/base/objects/factory/impl/FactorySearchProvider.java b/platform/runtime/base/objects-base/object-factory/src/main/java/ru/entaxy/platform/base/objects/factory/impl/FactorySearchProvider.java new file mode 100644 index 00000000..1e2c59b3 --- /dev/null +++ b/platform/runtime/base/objects-base/object-factory/src/main/java/ru/entaxy/platform/base/objects/factory/impl/FactorySearchProvider.java @@ -0,0 +1,64 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-factory + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.base.objects.factory.impl; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.Filter; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.objects.factory.EntaxyFactoryRegistry; +import ru.entaxy.platform.base.objects.factory.EntaxyFactoryUtils; +import ru.entaxy.platform.search.AbstractSearchProvider; +import ru.entaxy.platform.search.SearchProvider; +import ru.entaxy.platform.search.SearchProviderInfo; + +@Component(service = SearchProvider.class, immediate = true) +@SearchProviderInfo(id = "factories", targetTypes = {"factory"}) +public class FactorySearchProvider extends AbstractSearchProvider { + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyFactoryRegistry factoryRegistry; + + @Override + public Map getStandardAttributes(String targetType) throws IllegalArgumentException { + return EntaxyFactory.SEARCH.STANDARD_ATTRIBUTES; + } + + @Override + public List> search(String targetType, Filter filter) throws IllegalArgumentException { + + return factoryRegistry.getAllFactories().stream().map(f -> EntaxyFactoryUtils.getFactoryEssence(f, "")) + .filter(es -> filter.matches(es)) + .collect(Collectors.toList()); + } + +} diff --git a/platform/runtime/base/resources/resources-api/src/main/java/ru/entaxy/esb/resources/EntaxyResourceURLFactory.java b/platform/runtime/base/resources/resources-api/src/main/java/ru/entaxy/esb/resources/EntaxyResourceURLFactory.java new file mode 100644 index 00000000..5a19da58 --- /dev/null +++ b/platform/runtime/base/resources/resources-api/src/main/java/ru/entaxy/esb/resources/EntaxyResourceURLFactory.java @@ -0,0 +1,96 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resources-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.resources; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +public class EntaxyResourceURLFactory { + + private EntaxyResourceURLFactory() { + + } + + public static final String DEFAULT_GLOBAL_PROTOCOL = "entaxy-resource"; + + public static URI getLocalUri(String resourceUrl) throws URISyntaxException { + return getLocalUri(resourceUrl, DEFAULT_GLOBAL_PROTOCOL); + } + + public static URI getLocalUri(String resourceUrl, String globalProtocol) throws URISyntaxException { + String prefix = globalProtocol.concat("://"); + String result = resourceUrl; + if (resourceUrl.startsWith(prefix)) + result = resourceUrl.substring(prefix.length()); + int index = result.indexOf(":"); + if (index > 0) + return new URI(result); + index = result.indexOf("/"); + if (index <= 0) + return new URI(result); + return new URI(result.substring(0, index).concat(":").concat(result.substring(index + 1))); + + } + + public static URL getGlobalUrl(EntaxyResource resource) throws MalformedURLException { + return getGlobalUrl(resource, DEFAULT_GLOBAL_PROTOCOL); + } + + public static URL getGlobalUrl(String resourceUrl) throws MalformedURLException { + return getGlobalUrl(resourceUrl, DEFAULT_GLOBAL_PROTOCOL); + } + + public static URL getGlobalUrl(EntaxyResource resource, String globalProtocol) throws MalformedURLException { + return getGlobalUrl(resource.getURL(), globalProtocol); + } + + public static URL getGlobalUrl(String resourceUrl, String globalProtocol) throws MalformedURLException { + if (resourceUrl.startsWith(globalProtocol + "://")) + return new URL(resourceUrl); + + String localProtocol = ""; + String resourcePath = resourceUrl; + + int index = resourceUrl.indexOf(':'); + if (index > 0) { + localProtocol = resourceUrl.substring(0, index); + resourcePath = resourceUrl.substring(index + 1); + } + + while (resourcePath.startsWith("/")) + resourcePath = resourcePath.substring(1); + + String resultPath = localProtocol.length() > 0 ? localProtocol.concat("/").concat(resourcePath) : resourcePath; + + while (resultPath.startsWith("/")) + resultPath = resultPath.substring(1); + + return new URL(globalProtocol.concat("://").concat(resultPath)); + } + +} diff --git a/platform/runtime/base/resources/resources-management/src/main/java/ru/entaxy/esb/resources/management/impl/ServiceHelper.java b/platform/runtime/base/resources/resources-management/src/main/java/ru/entaxy/esb/resources/management/impl/ServiceHelper.java new file mode 100644 index 00000000..03a9c18d --- /dev/null +++ b/platform/runtime/base/resources/resources-management/src/main/java/ru/entaxy/esb/resources/management/impl/ServiceHelper.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * resources-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.resources.management.impl; + +import org.osgi.service.component.annotations.*; +import ru.entaxy.esb.resources.EntaxyResourceService; + +@Component(service = ServiceHelper.class, immediate = true) +public class ServiceHelper { + + public static ServiceHelper INSTANCE; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public EntaxyResourceService entaxyResourceService; + + @Activate + public void activate() { + INSTANCE = this; + } + + @Deactivate + public void deactivate() { + INSTANCE = null; + } + +} diff --git a/platform/runtime/base/search-service/LICENSE.txt b/platform/runtime/base/search-service/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/base/search-service/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/base/search-service/pom.xml b/platform/runtime/base/search-service/pom.xml new file mode 100644 index 00000000..e83c7db5 --- /dev/null +++ b/platform/runtime/base/search-service/pom.xml @@ -0,0 +1,53 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime + base + 1.10.0 + + ru.entaxy.platform + search-service + bundle + ENTAXY :: PLATFORM :: SEARCH SERVICE + ENTAXY :: PLATFORM :: SEARCH SERVICE + + + + ru.entaxy.platform.search + + + ru.entaxy.platform.search.* + + none + + + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + ru.entaxy.esb.platform.runtime.base + management-core + ${project.version} + + + org.apache.karaf.shell + org.apache.karaf.shell.core + ${karaf.version} + + + + org.apache.commons + commons-collections4 + 4.4 + + + ru.entaxy.esb.platform.runtime.base + management-core + ${project.version} + + + + diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/AbstractSearchProvider.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/AbstractSearchProvider.java new file mode 100644 index 00000000..06978864 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/AbstractSearchProvider.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public abstract class AbstractSearchProvider implements SearchProvider { + + @Override + public String getProviderId() { + if (this.getClass().isAnnotationPresent(SearchProviderInfo.class)) + return this.getClass().getAnnotation(SearchProviderInfo.class).id(); + return null; + } + + @Override + public List getTargetTypes() { + if (this.getClass().isAnnotationPresent(SearchProviderInfo.class)) + return Arrays.asList(this.getClass().getAnnotation(SearchProviderInfo.class).targetTypes()); + return new ArrayList<>(); + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchProvider.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchProvider.java new file mode 100644 index 00000000..386f4b6a --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchProvider.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search; + +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; + +public interface SearchProvider { + + String getProviderId(); + + List getTargetTypes(); + + Map getStandardAttributes(String targetType) throws IllegalArgumentException; + + default List> search(String targetType, String filter) + throws InvalidSyntaxException, IllegalArgumentException { + if (!getTargetTypes().contains(targetType)) + throw new IllegalArgumentException( + String.format("Provider [%s]: target type [%s] not supported", getProviderId(), targetType)); + return search(targetType, FrameworkUtil.createFilter(filter)); + } + + List> search(String targetType, Filter filter) throws IllegalArgumentException; +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchProviderInfo.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchProviderInfo.java new file mode 100644 index 00000000..f252a6c1 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchProviderInfo.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface SearchProviderInfo { + + String id(); + + String[] targetTypes(); + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchService.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchService.java new file mode 100644 index 00000000..34a5acf7 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/SearchService.java @@ -0,0 +1,89 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; + +public interface SearchService { + + List getProviders(); + + SearchProvider getProviderForType(String targetType); + + default List getProvidedTypes() { + return getProviders().stream().map(p -> p.getTargetTypes()).flatMap(t -> t.stream()).distinct() + .collect(Collectors.toList()); + } + + default Map getStandardAttributes(String targetType) throws IllegalArgumentException { + SearchProvider provider = getProviderForType(targetType); + if (provider == null) + throw new IllegalArgumentException(String.format("Search provider for type [%s] not found", targetType)); + return provider.getStandardAttributes(targetType); + } + + default List getAttributes(String targetType, String filter) + throws InvalidSyntaxException, IllegalArgumentException { + return getAttributes(targetType, FrameworkUtil.createFilter(filter)); + } + + default List getAttributes(String targetType, Filter filter) + throws InvalidSyntaxException, IllegalArgumentException { + + List result = new ArrayList<>(); + + List> found = search(targetType, filter); + + if (found != null) { + result.addAll(found.stream().map(m -> m.keySet()).flatMap(ks -> ks.stream()).distinct() + .collect(Collectors.toList())); + } + + return result; + } + + default List> search(String targetType, String filter) + throws InvalidSyntaxException, IllegalArgumentException { + Filter osgiFilter = FrameworkUtil.createFilter(filter); + return search(targetType, osgiFilter); + } + + + default List> search(String targetType, Filter filter) + throws InvalidSyntaxException, IllegalArgumentException { + SearchProvider provider = getProviderForType(targetType); + if (provider == null) + throw new IllegalArgumentException(String.format("Search provider for type [%s] not found", targetType)); + return provider.search(targetType, filter); + }; +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/impl/SearchServiceImpl.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/impl/SearchServiceImpl.java new file mode 100644 index 00000000..6c6c428a --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/impl/SearchServiceImpl.java @@ -0,0 +1,143 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.impl; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.platform.search.SearchProvider; +import ru.entaxy.platform.search.SearchService; + +@Component(service = SearchService.class, immediate = true) +public class SearchServiceImpl implements SearchService { + + protected final Map> providers = new HashMap<>(); + + protected final Map containers = new HashMap<>(); + + protected Object providersLock = new Object(); + + protected BundleContext bundleContext; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + } + + @Reference(unbind = "unbindProvider", cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + public void bindProvider(SearchProvider provider, Map properties) { + synchronized (providersLock) { + SearchProviderContainer container = new SearchProviderContainer(provider, properties); + for (String s : provider.getTargetTypes()) { + if (!providers.containsKey(s)) + providers.put(s, new ArrayList<>()); + providers.get(s).add(container); + } + containers.put(provider, container); + } + } + + public void unbindProvider(SearchProvider provider) { + synchronized (providersLock) { + SearchProviderContainer container = containers.get(provider); + containers.remove(provider); + if (container != null) + for (String s : provider.getTargetTypes()) { + List list = providers.get(s); + if (list != null) + list.remove(container); + } + } + } + + @Override + public List getProviders() { + return this.providers.keySet().stream().map(t -> getProviderForType(t)).filter(p -> p != null).distinct() + .collect(Collectors.toList()); + } + + @Override + public SearchProvider getProviderForType(String targetType) { + if (providers.containsKey(targetType)) { + List list = providers.get(targetType); + if (list == null || list.isEmpty()) + return null; + + SearchProviderContainer targetContainer = list.stream().sorted(new Comparator() { + + @Override + public int compare(SearchProviderContainer o1, SearchProviderContainer o2) { + return Integer.compare(o1.ranking, o2.ranking); + } + }).findFirst().get(); + + return targetContainer.provider; + + } + return null; + } + + protected class SearchProviderContainer { + + int ranking = 0; + SearchProvider provider; + + protected SearchProviderContainer(SearchProvider provider, Map properties) { + this.provider = provider; + if (properties.containsKey(Constants.SERVICE_RANKING)) { + Object rankingValue = properties.get(Constants.SERVICE_RANKING); + if (rankingValue != null) + try { + if (rankingValue instanceof Number) + ranking = ((Number) rankingValue).intValue(); + } catch (Exception e1) { + try { + ranking = Integer.parseInt(rankingValue.toString()); + } catch (Exception ignore) { + // NOOP + } + } + } + } + + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/jmx/SearchMBean.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/jmx/SearchMBean.java new file mode 100644 index 00000000..625a056d --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/jmx/SearchMBean.java @@ -0,0 +1,81 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.jmx; + +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.management.MBeanOperationInfo; + +import org.osgi.framework.InvalidSyntaxException; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface SearchMBean { + + String SEARCH_KEY = "util"; + String SEARCH_KEY_VALUE = "search"; + + String JMX_OBJECT_NAME = ManagementCore.Q_PLATFORM_S + "," + + SearchMBean.SEARCH_KEY + "=" + SearchMBean.SEARCH_KEY_VALUE; + + @Operation(impact = MBeanOperationInfo.INFO, desc = "Lists available search providers") + List listProviders(); + + @Operation(impact = MBeanOperationInfo.INFO, desc = "Lists types available for search") + List listProvidedTypes(); + + @Operation(impact = MBeanOperationInfo.INFO, desc = "Lists standard attributes for selected type") + Map listStandardAttributes(@Parameter(name = "type") String type) + throws InvalidSyntaxException, IllegalArgumentException; + + @Operation(impact = MBeanOperationInfo.INFO, desc = "Lists attributes available for the target search") + default List listAttributes(@Parameter(name = "type") String type, + @Parameter(name = "filter") String filter) + throws InvalidSyntaxException, IllegalArgumentException { + + List result = new LinkedList<>(); + + for (Map item : search(type, filter)) + for (String attr : item.keySet()) + if (!result.contains(attr)) + result.add(attr); + + return result; + }; + + + @Operation(impact = MBeanOperationInfo.INFO, desc = "Executes search") + List> search(@Parameter(name = "type") String type, @Parameter(name = "filter") String filter) + throws InvalidSyntaxException, IllegalArgumentException; + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/jmx/impl/SearchMBeanImpl.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/jmx/impl/SearchMBeanImpl.java new file mode 100644 index 00000000..cf0c03fa --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/jmx/impl/SearchMBeanImpl.java @@ -0,0 +1,83 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.jmx.impl; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.management.DynamicMBean; +import javax.management.MBeanRegistration; +import javax.management.NotCompliantMBeanException; + +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ServiceScope; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean; +import ru.entaxy.platform.search.SearchService; +import ru.entaxy.platform.search.jmx.SearchMBean; + +@Component( + service = {SearchMBean.class, DynamicMBean.class, MBeanRegistration.class}, + property = {ManagementCore.JMX_OBJECTNAME + "=" + SearchMBean.JMX_OBJECT_NAME}, + scope = ServiceScope.SINGLETON, + immediate = true) +public class SearchMBeanImpl extends AnnotatedMBean implements SearchMBean { + + @Reference + SearchService searchService; + + public SearchMBeanImpl() throws NotCompliantMBeanException { + super(SearchMBean.class); + } + + @Override + public List listProviders() { + return searchService.getProviders().stream().map(p -> p.getProviderId()).collect(Collectors.toList()); + } + + @Override + public List listProvidedTypes() { + return searchService.getProvidedTypes(); + } + + @Override + public Map listStandardAttributes(String type) + throws InvalidSyntaxException, IllegalArgumentException { + return searchService.getStandardAttributes(type); + } + + @Override + public List> search(String type, String filter) + throws InvalidSyntaxException, IllegalArgumentException { + return searchService.search(type, FrameworkUtil.createFilter(filter)); + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/provider/OsgiSearchProvider.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/provider/OsgiSearchProvider.java new file mode 100644 index 00000000..7f7664f4 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/provider/OsgiSearchProvider.java @@ -0,0 +1,209 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.provider; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.collections4.MapUtils; +import org.apache.karaf.bundle.core.BundleInfo; +import org.apache.karaf.bundle.core.BundleService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.Constants; +import org.osgi.framework.Filter; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.platform.search.AbstractSearchProvider; +import ru.entaxy.platform.search.SearchProvider; +import ru.entaxy.platform.search.SearchProviderInfo; + +@Component(service = SearchProvider.class, immediate = true) +@SearchProviderInfo(id = "osgi", targetTypes = {OsgiSearchProvider.TYPE_BUNDLE, OsgiSearchProvider.TYPE_SERVICE}) +public class OsgiSearchProvider extends AbstractSearchProvider { + + public static final String TYPE_BUNDLE = "bundle"; + + public static final String TYPE_SERVICE = "service"; + + public interface BundleSearch { + + String ATTR_ID = "id"; + String ATTR_LOCATION = "location"; + String ATTR_SYMBOLIC_NAME = "symbolicName"; + String ATTR_LAST_MODIFIED = "lastModified"; + + String ATTR_HEADER_PREFIX = "header."; + String ATTR_HEADER = ATTR_HEADER_PREFIX + "*"; + + List STANDARD_ATTRIBUTES_LIST = Arrays.asList(new String[] { + ATTR_ID, ATTR_SYMBOLIC_NAME, ATTR_LOCATION, ATTR_LAST_MODIFIED + }); + + Map STANDARD_ATTRIBUTES = MapUtils.putAll(new LinkedHashMap<>(), new String[][] { + {ATTR_ID, "Bundle Id"}, + {ATTR_LOCATION, "Bundle location"}, + {ATTR_SYMBOLIC_NAME, "Bundle symbolic name"}, + {ATTR_LAST_MODIFIED, "Bundle last modified timestamp"}, + {ATTR_HEADER, "Bundle header value"} + }); + } + + public interface ServiceSearch { + + String ATTR_ID = "service.id"; + String ATTR_OBJECT_CLASS = "objectClass"; + String ATTR_BUNDLE_ID = "service.bundleId"; + + + List STANDARD_ATTRIBUTES_LIST = Arrays.asList(new String[] { + ATTR_ID, ATTR_OBJECT_CLASS, ATTR_BUNDLE_ID + }); + + Map STANDARD_ATTRIBUTES = MapUtils.putAll(new LinkedHashMap<>(), new String[][] { + {ATTR_ID, "Service Id"}, + {ATTR_OBJECT_CLASS, "Service object class"}, + {ATTR_BUNDLE_ID, "Service bundle id"} + }); + } + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + BundleService bundleService; + + protected BundleContext bundleContext; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + } + + @Override + public List> search(String targetType, Filter filter) throws IllegalArgumentException { + if (TYPE_BUNDLE.equalsIgnoreCase(targetType)) + return searchBundles(filter); + if (TYPE_SERVICE.equalsIgnoreCase(targetType)) + try { + return searchServices(filter); + } catch (InvalidSyntaxException e) { + throw new IllegalArgumentException(String.format("Invalid filter: [%s]", filter.toString())); + } + + + throw new IllegalArgumentException( + String.format("Provider [%s]: target type [%s] not supported", getProviderId(), targetType)); + + + } + + @Override + public Map getStandardAttributes(String targetType) throws IllegalArgumentException { + if (TYPE_BUNDLE.equalsIgnoreCase(targetType)) + return BundleSearch.STANDARD_ATTRIBUTES; + + if (TYPE_SERVICE.equalsIgnoreCase(targetType)) + return ServiceSearch.STANDARD_ATTRIBUTES; + + throw new IllegalArgumentException( + String.format("Provider [%s]: target type [%s] not supported", getProviderId(), targetType)); + + } + + protected List> searchBundles(Filter filter) { + List> result = new ArrayList<>(); + for (Bundle b : bundleContext.getBundles()) { + Map essence = getBundleEssence(b); + if (filter.matches(essence)) + result.add(essence); + } + + return result; + } + + protected Map getBundleEssence(Bundle bundle) { + Map result = new LinkedHashMap<>(); + + BundleInfo bi = bundleService.getInfo(bundle); + + result.put(BundleSearch.ATTR_ID, bundle.getBundleId()); + result.put(BundleSearch.ATTR_SYMBOLIC_NAME, bundle.getSymbolicName()); + result.put(BundleSearch.ATTR_LOCATION, bi.getUpdateLocation()); + result.put(BundleSearch.ATTR_LAST_MODIFIED, bundle.getLastModified()); + + + Dictionary headers = bundle.getHeaders(); + Enumeration keys = headers.keys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + result.put(BundleSearch.ATTR_HEADER_PREFIX + key, headers.get(key)); + } + + return result; + } + + protected List> searchServices(Filter filter) throws InvalidSyntaxException { + + ServiceReference[] refs = bundleContext.getAllServiceReferences(null, filter.toString()); + + List> result = new ArrayList<>(); + for (ServiceReference ref : refs) { + result.add(getServiceEssence(ref)); + } + + return result; + } + + protected Map getServiceEssence(ServiceReference ref) { + Map result = new LinkedHashMap<>(); + + result.put(ServiceSearch.ATTR_ID, ref.getProperty(Constants.SERVICE_ID)); + Object refObjectClass = ref.getProperty(Constants.OBJECTCLASS); + if (refObjectClass == null || !(refObjectClass instanceof String[])) + result.put(ServiceSearch.ATTR_OBJECT_CLASS, ""); + else + result.put(ServiceSearch.ATTR_OBJECT_CLASS, Arrays.asList((String[]) refObjectClass)); + + result.put(ServiceSearch.ATTR_BUNDLE_ID, ref.getBundle().getBundleId()); + + String[] keys = ref.getPropertyKeys(); + for (String key : keys) + if (!ServiceSearch.STANDARD_ATTRIBUTES_LIST.contains(key)) + result.put(key, ref.getProperty(key)); + + return result; + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/ProvidersList.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/ProvidersList.java new file mode 100644 index 00000000..34029e9f --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/ProvidersList.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell; + +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.search.SearchProvider; +import ru.entaxy.platform.search.shell.support.AbstractSearchCommand; + +@Service +@Command(scope = AbstractSearchCommand.COMMAND_SCOPE, name = "search-provider-list") +public class ProvidersList extends AbstractSearchCommand { + + @Override + protected void doExecute() throws Exception { + List list = searchService.getProviders(); + + ShellTableExt table = new ShellTableExt(); + table.column("Id"); + table.column("Supported types"); + + for (SearchProvider p : list) + table.addRow().addContent(p.getProviderId(), p.getTargetTypes().stream().collect(Collectors.joining("\n"))); + + // print output + table.print(System.out); + + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/Search.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/Search.java new file mode 100644 index 00000000..15696577 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/Search.java @@ -0,0 +1,122 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.RowExt; +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.search.shell.support.AbstractSearchCommand; +import ru.entaxy.platform.search.shell.support.ObjectTypeAwareCommand; + +@Service +@Command(scope = AbstractSearchCommand.COMMAND_SCOPE, name = "search") +public class Search extends ObjectTypeAwareCommand { + + @Option(name = "-d", aliases = {"--display-attributes"}) + List attributes = new ArrayList<>(); + + @Option(name = "-n", aliases = {"--attribute-names-only"}) + boolean attributeNamesOnly = false; + + @Option(name = "-s", aliases = {"--no-split-lists"}) + boolean noSplitLists = false; + + @Argument(index = 1, required = true) + String filter; + + @Override + protected void doExecute() throws Exception { + + if (attributeNamesOnly) { + listAttributeNames(); + return; + } + + List> result = searchService.search(type, filter); + + ShellTableExt table = new ShellTableExt(); + table.splitLists(!noSplitLists); + + if (!attributes.isEmpty()) { + // fixed attributes + + List attrs = attributes.stream().distinct().collect(Collectors.toList()); + + for (String s : attrs) + table.column(s); + + for (Map essence : result) { + RowExt row = table.addRow(); + List data = new ArrayList<>(); + for (String s : attrs) + data.add(essence.getOrDefault(s, "")); + row.addContent(data); + } + + } else { + + List attrs = result.stream().map(s -> s.keySet()).flatMap(ks -> ks.stream()).distinct() + .collect(Collectors.toList()); + + for (String attr : attrs) + table.column(attr); + + for (Map essence : result) { + RowExt row = table.addRow(); + + List data = new ArrayList<>(); + for (String s : attrs) + data.add(essence.getOrDefault(s, "")); + row.addContent(data); + } + + + } + + // output + table.print(System.out); + + } + + protected void listAttributeNames() throws Exception { + List list = searchService.getAttributes(type, filter); + + // output + for (String s : list) + System.out.println(s); + + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/StandardAttributes.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/StandardAttributes.java new file mode 100644 index 00000000..448239c7 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/StandardAttributes.java @@ -0,0 +1,57 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell; + +import java.util.Map; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.search.shell.support.ObjectTypeAwareCommand; +import ru.entaxy.platform.search.shell.support.AbstractSearchCommand; + +@Service +@Command(name = "search-standard-atributes", scope = AbstractSearchCommand.COMMAND_SCOPE) +public class StandardAttributes extends ObjectTypeAwareCommand { + + @Override + protected void doExecute() throws Exception { + + ShellTableExt table = new ShellTableExt(); + + table.column("Attribute"); + table.column("Description"); + + for (Map.Entry entry : searchService.getStandardAttributes(type).entrySet()) + table.addRow().addContent(entry.getKey(), entry.getValue()); + + // output + table.print(System.out); + + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/AbstractSearchCommand.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/AbstractSearchCommand.java new file mode 100644 index 00000000..d7952cd1 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/AbstractSearchCommand.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell.support; + +import org.apache.karaf.shell.api.action.Action; + +public abstract class AbstractSearchCommand extends SearchServiceSupport implements Action { + + public static final String COMMAND_SCOPE = "entaxy"; + + @Override + public Object execute() throws Exception { + + try { + doExecute(); + } catch (Exception e) { + + // output error + System.err.println(String.format("ERROR: [%s]\n --> %s", e.getClass().getName(), e.getMessage())); + + } + + return null; + } + + abstract protected void doExecute() throws Exception; + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/ObjectTypeAwareCommand.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/ObjectTypeAwareCommand.java new file mode 100644 index 00000000..00a098d2 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/ObjectTypeAwareCommand.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell.support; + +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Completion; + +public abstract class ObjectTypeAwareCommand extends AbstractSearchCommand { + + @Argument(index = 0, required = true) + @Completion(caseSensitive = false, value = ObjectTypeCompleter.class) + public String type; + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/ObjectTypeCompleter.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/ObjectTypeCompleter.java new file mode 100644 index 00000000..d8dcc7d8 --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/ObjectTypeCompleter.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell.support; + +import java.util.List; + +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.apache.karaf.shell.api.console.CommandLine; +import org.apache.karaf.shell.api.console.Completer; +import org.apache.karaf.shell.api.console.Session; + +@Service +public class ObjectTypeCompleter extends SearchServiceSupport implements Completer { + + @Override + public int complete(Session session, CommandLine commandLine, List candidates) { + candidates.addAll(searchService.getProvidedTypes()); + return 0; + } + +} diff --git a/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/SearchServiceSupport.java b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/SearchServiceSupport.java new file mode 100644 index 00000000..bc2aa4ae --- /dev/null +++ b/platform/runtime/base/search-service/src/main/java/ru/entaxy/platform/search/shell/support/SearchServiceSupport.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * search-service + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.search.shell.support; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; + +import ru.entaxy.platform.search.SearchService; + +public class SearchServiceSupport { + + @Reference + public SearchService searchService; + +} diff --git a/platform/runtime/core/artifact-management-extensions/LICENSE.txt b/platform/runtime/core/artifact-management-extensions/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/artifact-management-extensions/pom.xml b/platform/runtime/core/artifact-management-extensions/pom.xml new file mode 100644 index 00000000..2d306aa8 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/pom.xml @@ -0,0 +1,56 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime + core + 1.10.0 + + ru.entaxy.esb.platform.runtime.core + artifact-management-extensions + bundle + ENTAXY :: PLATFORM :: CORE :: ARTIFACT MANAGEMENT EXTENSIONS + ENTAXY :: PLATFORM :: CORE :: ARTIFACT MANAGEMENT EXTENSIONS + + + + ru.entaxy.platform.core.artifact.ext.binary, + ru.entaxy.platform.core.artifact.ext.features, + ru.entaxy.platform.core.artifact.ext.impl, + ru.entaxy.platform.core.artifact.ext + + + ru.entaxy.platform.core.artifact.ext.internal, + ru.entaxy.platform.core.artifact.ext.features.impl + + + + + + + ru.entaxy.esb.platform.runtime.core + artifact-management + ${project.version} + + + commons-io + commons-io + ${commons-io.version} + + + org.apache.karaf.features + org.apache.karaf.features.core + ${karaf.version} + + + org.apache.karaf.cellar + org.apache.karaf.cellar.features + ${cellar.version} + + + ru.entaxy.esb.platform.runtime.base + cellar-extensions + ${project.version} + + + + diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/ArtifactExtended.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/ArtifactExtended.java new file mode 100644 index 00000000..6dd7cd58 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/ArtifactExtended.java @@ -0,0 +1,33 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext; + +public interface ArtifactExtended { + + String ARTIFACT_CATEGORY_UNTYPED_BINARY = "UNTYPED_BINARY"; + String ARTIFACT_CATEGORY_FEATURE = "FEATURE"; + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/ExtTypedInstallerFactory.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/ExtTypedInstallerFactory.java new file mode 100644 index 00000000..32312c38 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/ExtTypedInstallerFactory.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext; + +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.ext.features.FeatureInstaller; +import ru.entaxy.platform.core.artifact.ext.features.FeaturesInstaller; +import ru.entaxy.platform.core.artifact.ext.features.impl.FeatureInstallerImpl; +import ru.entaxy.platform.core.artifact.ext.features.impl.FeaturesInstallerImpl; +import ru.entaxy.platform.core.artifact.installer.builder.typed.AbstractTypedInstallerFactory; +import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstaller; +import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstallerFactoryDescriptor; + +@TypedInstallerFactoryDescriptor(supportedClasses = {FeaturesInstaller.class, FeatureInstaller.class}, + supportedTypes = {Artifact.ARTIFACT_CATEGORY_FEATURES, ArtifactExtended.ARTIFACT_CATEGORY_FEATURE}) +public class ExtTypedInstallerFactory extends AbstractTypedInstallerFactory { + + @Override + protected TypedInstaller doCreate(String type) { + if (Artifact.ARTIFACT_CATEGORY_FEATURES.equalsIgnoreCase(type)) { + return new FeaturesInstallerImpl(); + } + return null; + } + + @Override + protected TypedInstaller doCreate(Class targetClass) { + if (FeaturesInstaller.class.equals(targetClass)) + return new FeaturesInstallerImpl(); + if (FeatureInstaller.class.equals(targetClass)) + return new FeatureInstallerImpl(); + return null; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/SequenceSupport.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/SequenceSupport.java new file mode 100644 index 00000000..388002e6 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/SequenceSupport.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext; + +public interface SequenceSupport { + + T inSequence(String sequenceId); + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/AbstractBinaryArtifact.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/AbstractBinaryArtifact.java new file mode 100644 index 00000000..bf61ca78 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/AbstractBinaryArtifact.java @@ -0,0 +1,135 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.binary; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.artifact.DefaultArtifact; + +/** + * Allowed content types: InputStream, File, byte[] + */ +public abstract class AbstractBinaryArtifact extends DefaultArtifact { + + private static final Logger LOG = LoggerFactory.getLogger(AbstractBinaryArtifact.class); + + @Override + public void setContent(Object content) { + super.setContent(content); + } + + @Override + public void toFile(File destination) { + if (content == null) + return; + + if (content instanceof File) { + try { + Files.copy(((File) content).getAbsoluteFile().toPath(), destination.getAbsoluteFile().toPath(), + StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + LOG.error("Error saving file", e); + } + return; + } + + if (content instanceof InputStream) { + try { + InputStream is = (InputStream) content; + if (is.markSupported()) { + is.mark(0); + } + Files.copy((InputStream) content, destination.getAbsoluteFile().toPath(), + StandardCopyOption.REPLACE_EXISTING); + if (is.markSupported()) { + is.reset(); + } + } catch (IOException e) { + LOG.error("Error saving file", e); + } + return; + } + + if (content instanceof byte[]) { + try (InputStream is = new ByteArrayInputStream((byte[]) content)) { + Files.copy(is, destination.getAbsoluteFile().toPath(), + StandardCopyOption.REPLACE_EXISTING); + } catch (IOException e) { + LOG.error("Error saving file", e); + } + return; + } + + super.toFile(destination); + } + + @Override + public byte[] asByteArray() { + if (content == null) + return new byte[0]; + + if (content instanceof byte[]) + return (byte[]) content; + + if (content instanceof InputStream) + try { + byte[] byteArray; + InputStream is = (InputStream) content; + if (is.markSupported()) { + is.mark(0); + } + byteArray = IOUtils.toByteArray(is); + if (is.markSupported()) { + is.reset(); + } + return byteArray; + } catch (IOException e) { + LOG.error("Error getting bytes", e); + return new byte[0]; + } + + if (content instanceof File) + try (InputStream is = new FileInputStream((File) content)) { + return IOUtils.toByteArray(is); + } catch (Exception e) { + LOG.error("Error getting bytes", e); + return new byte[0]; + } + + return super.asByteArray(); + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/JarArtifact.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/JarArtifact.java new file mode 100644 index 00000000..0087d06c --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/JarArtifact.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.binary; + +import java.io.File; +import java.io.InputStream; + +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.annotation.ArtifactSupport; + +@ArtifactSupport(supportedCategory = Artifact.ARTIFACT_CATEGORY_JAR, + supportedContentClasses = {File.class, InputStream.class, byte[].class}, + defaultArtifactType = "jar") +public class JarArtifact extends AbstractBinaryArtifact { + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/UntypedBinaryArtifact.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/UntypedBinaryArtifact.java new file mode 100644 index 00000000..2c9b54e0 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/binary/UntypedBinaryArtifact.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.binary; + +import java.io.File; +import java.io.InputStream; + +import ru.entaxy.platform.core.artifact.annotation.ArtifactSupport; +import ru.entaxy.platform.core.artifact.ext.ArtifactExtended; + +@ArtifactSupport(supportedCategory = ArtifactExtended.ARTIFACT_CATEGORY_UNTYPED_BINARY, + supportedContentClasses = {File.class, InputStream.class, byte[].class}, + defaultArtifactType = "jar") +public class UntypedBinaryArtifact extends AbstractBinaryArtifact { + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeatureInstaller.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeatureInstaller.java new file mode 100644 index 00000000..a6301e6f --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeatureInstaller.java @@ -0,0 +1,51 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features; + +import ru.entaxy.platform.core.artifact.ext.SequenceSupport; +import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstaller; + +public interface FeatureInstaller extends TypedInstaller, SequenceSupport { + + public interface FeatureInstallDescriptor extends TypedInstaller { + + FeatureInstallDescriptor version(String version); + + FeatureInstallDescriptor noRefresh(); + + FeatureInstallDescriptor noStart(); + + FeatureInstallDescriptor noManage(); + + FeatureInstallDescriptor upgrade(); + + + FeatureInstallDescriptor feature(String name); + } + + FeatureInstallDescriptor feature(String name); + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeaturesArtifact.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeaturesArtifact.java new file mode 100644 index 00000000..fa45efde --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeaturesArtifact.java @@ -0,0 +1,77 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; + +import ru.entaxy.platform.base.support.xml.CommonXMLUtils; +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.annotation.ArtifactSupport; +import ru.entaxy.platform.core.artifact.ext.binary.AbstractBinaryArtifact; + +@ArtifactSupport(supportedCategory = Artifact.ARTIFACT_CATEGORY_FEATURES, + supportedContentClasses = {File.class, InputStream.class, byte[].class, Document.class, String.class}, + defaultArtifactType = "xml") +public class FeaturesArtifact extends AbstractBinaryArtifact { + + private static final Logger LOG = LoggerFactory.getLogger(FeaturesArtifact.class); + + @Override + public void toFile(File destination) { + if (content == null) + return; + + if (content instanceof Document) { + String data = null; + try { + data = CommonXMLUtils.doc2string((Document) content); + } catch (Exception e) { + LOG.error("Error converting Document to String for artifact [" + getCoordinates().toMavenString() + "]", + e); + return; + } + try (InputStream is = new ByteArrayInputStream(data.getBytes())) { + Files.copy(is, destination.getAbsoluteFile().toPath(), + StandardCopyOption.REPLACE_EXISTING); + } catch (Exception e) { + LOG.error("Error saving to file for artifact [" + getCoordinates().toMavenString() + "]", e); + return; + } + return; + } + + super.toFile(destination); + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeaturesInstaller.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeaturesInstaller.java new file mode 100644 index 00000000..e3f4a4fb --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/FeaturesInstaller.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features; + +import ru.entaxy.platform.core.artifact.ext.SequenceSupport; +import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstaller; + +public interface FeaturesInstaller extends TypedInstaller, SequenceSupport { + + FeaturesInstaller installAllFeatures(); + + FeaturesInstaller refresh(); + + FeaturesInstaller installFeatures(String... features); + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/CellarFeaturesInstallerHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/CellarFeaturesInstallerHelper.java new file mode 100644 index 00000000..64a6b96f --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/CellarFeaturesInstallerHelper.java @@ -0,0 +1,121 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.karaf.cellar.features.management.CellarFeaturesMBean; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.osgi.OSGIUtils; +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; +import ru.entaxy.platform.core.artifact.installer.builder.impl.cluster.ClusterTypedInstallerHelper; +import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceManager; + +public class CellarFeaturesInstallerHelper extends ClusterTypedInstallerHelper + implements FeaturesInstallerConfigurableHelper { + + private static final Logger LOG = LoggerFactory.getLogger(CellarFeaturesInstallerHelper.class); + + protected FeaturesInstallerHelperConfig config; + + public FeaturesInstallerHelperConfig getConfig() { + return config; + } + + @Override + public void setConfig(FeaturesInstallerHelperConfig config) { + this.config = config; + } + + protected CellarFeaturesMBean getFeaturesService() throws Exception { + if (CommonUtils.isValid(config.getSequenceId())) { + CellarSequenceManager seqManager = + OSGIUtils.services().ofClass(CellarSequenceManager.class).waitService(2000).get(); + + return seqManager.getSequencedHelper(config.getSequenceId(), CellarFeaturesMBean.class); + + } + return OSGIUtils.services().ofClass(CellarFeaturesMBean.class).waitService(2000).get(); + } + + @Override + public InstallationResultImpl install(InstallationResultImpl installationResult) { + CellarFeaturesMBean featuresService; + try { + featuresService = getFeaturesService(); + } catch (Exception e) { + LOG.error("Error getting CellarFeaturesMBean service", e); + return installationResult.failed("Error getting CellarFeaturesMBean service").error(e); + } + + List groupsToInstall = new ArrayList<>(); + for (String groupName : getGroups()) + if (checkGroup(groupName)) + if (!groupsToInstall.contains(groupName)) + groupsToInstall.add(groupName); + + if (groupsToInstall.size() == 0) { + return installationResult.failed("No groups to install to"); + } + + // TODO decide if we really need several groups + // now we use only the first one + String groupToInstall = groupsToInstall.get(0); + + String repositoryUrl = config.getSourceLocation(); + if (repositoryUrl.indexOf(':') < 0) + repositoryUrl = "mvn:" + repositoryUrl; + + try { + if (featuresService.getRepositories(groupToInstall).contains(repositoryUrl)) { + if (config.isRefresh()) + featuresService.refreshRepository(groupToInstall, repositoryUrl); + } else { + featuresService.addRepository(groupToInstall, repositoryUrl, null, config.isInstallAllFetures()); + } + + if (!config.isInstallAllFetures()) + for (String feature : config.getFeaturesToInstall()) + featuresService.installFeature(groupToInstall, feature); + + return installationResult.installed(); + } catch (Exception e) { + LOG.error("Error installing repository [" + repositoryUrl + "]", e); + return installationResult.failed("Error installing repository [" + repositoryUrl + "]").error(e); + } + } + + @Override + public InstallationResultImpl uninstall(InstallationResultImpl installationResult) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerClusterHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerClusterHelper.java new file mode 100644 index 00000000..53fd153f --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerClusterHelper.java @@ -0,0 +1,192 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.karaf.cellar.features.management.CellarFeaturesMBean; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.osgi.OSGIUtils; +import ru.entaxy.platform.core.artifact.ext.features.impl.FeatureInstallerImpl.FeatureInstallDescriptorImpl; +import ru.entaxy.platform.core.artifact.ext.impl.ClusterTypedConfigurableHelper; +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; +import ru.entaxy.platform.runtime.cellar.sequence.CellarSequenceManager; + +public class FeatureInstallerClusterHelper extends ClusterTypedConfigurableHelper + implements FeatureInstallerConfigurableHelper { + + private static final Logger LOG = LoggerFactory.getLogger(FeatureInstallerClusterHelper.class); + + protected CellarFeaturesMBean getFeaturesService() throws Exception { + if (CommonUtils.isValid(config.sequenceId)) { + CellarSequenceManager seqManager = + OSGIUtils.services().ofClass(CellarSequenceManager.class).waitService(2000).get(); + + return seqManager.getSequencedHelper(config.sequenceId, CellarFeaturesMBean.class); + + } + return OSGIUtils.services().ofClass(CellarFeaturesMBean.class).waitService(2000).get(); + } + + @Override + public InstallationResultImpl install(InstallationResultImpl installationResult) { + CellarFeaturesMBean featuresService; + try { + featuresService = getFeaturesService(); + } catch (Exception e) { + LOG.error("Error getting CellarFeaturesMBean service", e); + return installationResult.failed("Error getting CellarFeaturesMBean service").error(e); + } + + List groupsToInstall = new ArrayList<>(); + for (String groupName : getGroups()) + if (checkGroup(groupName)) + if (!groupsToInstall.contains(groupName)) + groupsToInstall.add(groupName); + + if (groupsToInstall.size() == 0) { + return installationResult.failed("No groups to install to"); + } + + // TODO decide if we really need several groups + // now we use only the first one + String groupToInstall = groupsToInstall.get(0); + + boolean hasFailed = false; + boolean hasSuccessfull = false; + + + for (FeatureInstallDescriptorImpl descriptor : config.descriptors.values()) { + InstallationResultImpl subResult = InstallationResultImpl.create(); + subResult.object(descriptor.featureName); + try { + + // convert version to OSGI-style version + // mj.mn.p-q -> mj.mn.p.q + String finalFeatureVersion = descriptor.featureVersion; + if (CommonUtils.isValid(finalFeatureVersion)) { + finalFeatureVersion = finalFeatureVersion.replace('-', '.'); + } + + featuresService.installFeature(groupToInstall, descriptor.featureName, + finalFeatureVersion, + descriptor.noRefresh, + descriptor.noStart, + descriptor.noManage, + descriptor.upgrade); + subResult.installed(); + hasSuccessfull = true; + } catch (Exception e) { + LOG.error("Error installing repository [" + descriptor.featureName + "]", e); + subResult.failed("Error installing feature [" + descriptor.featureName + "]").error(e); + hasFailed = true; + } + installationResult.subResult(subResult); + } + + if (!hasFailed) + installationResult.installed(); + else { + if (hasSuccessfull) { + installationResult.message("HAS FAILED SUBRESULTS"); + installationResult.installed(); + } else { + installationResult.failed(); + } + } + return installationResult; + } + + @Override + public InstallationResultImpl uninstall(InstallationResultImpl installationResult) { + CellarFeaturesMBean featuresService; + try { + featuresService = getFeaturesService(); + } catch (Exception e) { + LOG.error("Error getting CellarFeaturesMBean service", e); + return installationResult.failed("Error getting CellarFeaturesMBean service").error(e); + } + + List groupsToUninstall = new ArrayList<>(); + for (String groupName : getGroups()) + if (checkGroup(groupName)) + if (!groupsToUninstall.contains(groupName)) + groupsToUninstall.add(groupName); + + if (groupsToUninstall.size() == 0) { + return installationResult.failed("No groups to uninstall from"); + } + + // TODO decide if we really need several groups + // now we use only the first one + String groupToUninstall = groupsToUninstall.get(0); + + boolean hasFailed = false; + boolean hasSuccessfull = false; + + + for (FeatureInstallDescriptorImpl descriptor : config.descriptors.values()) { + InstallationResultImpl subResult = InstallationResultImpl.create(); + subResult.object(descriptor.featureName); + try { + + // convert version to OSGI-style version + // mj.mn.p-q -> mj.mn.p.q + String finalFeatureVersion = descriptor.featureVersion; + if (CommonUtils.isValid(finalFeatureVersion)) { + finalFeatureVersion = finalFeatureVersion.replace('-', '.'); + } + + featuresService.uninstallFeature(groupToUninstall, descriptor.featureName, finalFeatureVersion, + descriptor.noRefresh); + subResult.uninstalled(); + hasSuccessfull = true; + } catch (Exception e) { + LOG.error("Error uninstalling repository [" + descriptor.featureName + "]", e); + subResult.failed("Error uninstalling feature [" + descriptor.featureName + "]").error(e); + hasFailed = true; + } + installationResult.subResult(subResult); + } + + if (!hasFailed) + installationResult.uninstalled(); + else { + if (hasSuccessfull) { + installationResult.message("HAS FAILED SUBRESULTS"); + installationResult.uninstalled(); + } else { + installationResult.failed(); + } + } + return installationResult; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerConfigurableHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerConfigurableHelper.java new file mode 100644 index 00000000..405cae02 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerConfigurableHelper.java @@ -0,0 +1,36 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import ru.entaxy.platform.core.artifact.ext.impl.InstallerConfigurableHelper; + +public interface FeatureInstallerConfigurableHelper extends InstallerConfigurableHelper { + + @Override + default Class getConfigClass() { + return FeatureInstallerImpl.class; + } +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerImpl.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerImpl.java new file mode 100644 index 00000000..8043ee5f --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerImpl.java @@ -0,0 +1,172 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import java.util.HashMap; +import java.util.Map; + +import ru.entaxy.platform.core.artifact.DeployedArtifact; +import ru.entaxy.platform.core.artifact.ext.features.FeatureInstaller; +import ru.entaxy.platform.core.artifact.ext.impl.ExtendedTypedInstallerImpl; +import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperImpl; + +public class FeatureInstallerImpl + extends ExtendedTypedInstallerImpl + implements FeatureInstaller { + + protected static class FeatureInstallDescriptorImpl implements FeatureInstallDescriptor { + + FeatureInstallerImpl featureInstaller; + + String featureName; + String featureVersion; + + boolean noStart = false; + boolean noRefresh = false; + boolean noManage = false; + boolean upgrade = false; + + protected FeatureInstallDescriptorImpl(FeatureInstallerImpl featureInstaller, String name) { + this.featureInstaller = featureInstaller; + this.featureName = name; + } + + @Override + public void clearInstaller() { + featureInstaller.clearInstaller(); + } + + @Override + public void setSourceLocation(String sourceLocation) {} + + @Override + public String getSourceLocation() { + return featureInstaller.getSourceLocation(); + } + + @Override + public void setArtifact(DeployedArtifact artifact) { + featureInstaller.setArtifact(artifact); + } + + @Override + public DeployedArtifact getArtifact() { + return featureInstaller.getArtifact(); + } + + @Override + public String getTypedName() { + return featureInstaller.getTypedName(); + } + + @Override + public void setTypedName(String typedName) { + featureInstaller.setTypedName(typedName); + } + + @Override + public InstallationResult install() { + return featureInstaller.install(); + } + + @Override + public InstallationResult uninstall() { + return featureInstaller.uninstall(); + } + + @Override + public FeatureInstallDescriptor version(String version) { + this.featureVersion = version; + return this; + } + + @Override + public FeatureInstallDescriptor noRefresh() { + this.noRefresh = true; + return this; + } + + @Override + public FeatureInstallDescriptor noStart() { + this.noStart = true; + return this; + } + + @Override + public FeatureInstallDescriptor noManage() { + this.noManage = true; + return this; + } + + @Override + public FeatureInstallDescriptor upgrade() { + this.upgrade = true; + return this; + } + + @Override + public FeatureInstallDescriptor feature(String name) { + return featureInstaller.feature(name); + } + + } + + protected final Map descriptors = new HashMap<>(); + + protected String sequenceId = null; + + @Override + public FeatureInstaller inSequence(String sequenceId) { + this.sequenceId = sequenceId; + return this; + } + + @Override + public FeatureInstallDescriptor feature(String name) { + if (descriptors.containsKey(name)) + return descriptors.get(name); + FeatureInstallDescriptorImpl descriptor = new FeatureInstallDescriptorImpl(this, name); + descriptors.put(name, descriptor); + return descriptor; + } + + @Override + protected Class getHelperClass() { + return FeatureInstallerConfigurableHelper.class; + } + + @Override + protected H createClusterHelper(Class targetClass) { + return (H) new FeatureInstallerClusterHelper(); + } + + @Override + protected H createLocalHelper(Class targetClass) { + return (H) new FeatureInstallerLocalHelper(); + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerLocalHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerLocalHelper.java new file mode 100644 index 00000000..910ee7ef --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeatureInstallerLocalHelper.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import ru.entaxy.platform.core.artifact.ext.impl.LocalTypedConfigurableHelper; +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; + +public class FeatureInstallerLocalHelper extends LocalTypedConfigurableHelper + implements FeatureInstallerConfigurableHelper { + + @Override + public InstallationResultImpl install(InstallationResultImpl installationResult) { + // TODO Auto-generated method stub + return null; + } + + @Override + public InstallationResultImpl uninstall(InstallationResultImpl installationResult) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerConfigurableHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerConfigurableHelper.java new file mode 100644 index 00000000..d5229de0 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerConfigurableHelper.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; + +public interface FeaturesInstallerConfigurableHelper { + + void setConfig(FeaturesInstallerHelperConfig config); + + public InstallationResultImpl install(InstallationResultImpl installationResult); + + public InstallationResultImpl uninstall(InstallationResultImpl installationResult); + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerHelperConfig.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerHelperConfig.java new file mode 100644 index 00000000..65a071d6 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerHelperConfig.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import java.util.List; + +public interface FeaturesInstallerHelperConfig { + + boolean isRefresh(); + + boolean isInstallAllFetures(); + + List getFeaturesToInstall(); + + String getSourceLocation(); + + String getSequenceId(); + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerHelperImpl.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerHelperImpl.java new file mode 100644 index 00000000..69183088 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerHelperImpl.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperImpl; + +public abstract class FeaturesInstallerHelperImpl extends TypedInstallerHelperImpl + implements FeaturesInstallerConfigurableHelper { + + protected FeaturesInstallerHelperConfig config; + + public FeaturesInstallerHelperConfig getConfig() { + return config; + } + + @Override + public void setConfig(FeaturesInstallerHelperConfig config) { + this.config = config; + } + + + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerImpl.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerImpl.java new file mode 100644 index 00000000..6904c149 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/FeaturesInstallerImpl.java @@ -0,0 +1,133 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import ru.entaxy.platform.core.artifact.ext.features.FeaturesInstaller; +import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult; +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; +import ru.entaxy.platform.core.artifact.installer.builder.impl.cluster.ClusterTypedInstallerHelper; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.HelperCreator; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperImpl; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerImpl; + +public class FeaturesInstallerImpl extends TypedInstallerImpl + implements FeaturesInstaller, HelperCreator, FeaturesInstallerHelperConfig { + + protected boolean isInstallAllFeatures = false; + + protected boolean isRefresh = false; + + protected List featuresToInstall = new ArrayList<>(); + + protected FeaturesInstallerConfigurableHelper featuresHelper; + + protected String sequenceId = null; + + @Override + public FeaturesInstaller inSequence(String sequenceId) { + this.sequenceId = sequenceId; + return this; + } + + @Override + public InstallationResult install() { + InstallationResultImpl result = InstallationResultImpl.create(); + if (this.featuresHelper == null) + result.failed("HELPER NOT FOUND"); + else + this.featuresHelper.install(result); + return result.property("artifact", this.artifact); + } + + @Override + public InstallationResult uninstall() { + InstallationResultImpl result = InstallationResultImpl.create(); + if (this.featuresHelper == null) + result.failed("HELPER NOT FOUND"); + else + this.featuresHelper.uninstall(result); + return result.property("artifact", this.artifact); + } + + @Override + public void setHelper(TypedInstallerHelperImpl helper) { + if (helper instanceof FeaturesInstallerConfigurableHelper) { + featuresHelper = (FeaturesInstallerConfigurableHelper) helper; + featuresHelper.setConfig(this); + } + super.setHelper(helper); + } + + @Override + public FeaturesInstaller installAllFeatures() { + isInstallAllFeatures = true; + return this; + } + + @Override + public FeaturesInstaller installFeatures(String... features) { + if (features != null) + this.featuresToInstall = new ArrayList<>(Arrays.asList(features)); + return this; + } + + @Override + public H createHelper(Class targetClass) { + if (ClusterTypedInstallerHelper.class.isAssignableFrom(targetClass)) + return (H) new CellarFeaturesInstallerHelper(); + return (H) new LocalFeaturesInstallerHelper(); + } + + @Override + public FeaturesInstaller refresh() { + isRefresh = true; + return this; + } + + @Override + public boolean isRefresh() { + return isRefresh; + } + + @Override + public boolean isInstallAllFetures() { + return isInstallAllFeatures; + } + + @Override + public List getFeaturesToInstall() { + return featuresToInstall; + } + + @Override + public String getSequenceId() { + return sequenceId; + } +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/LocalFeaturesInstallerHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/LocalFeaturesInstallerHelper.java new file mode 100644 index 00000000..b945f11e --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/features/impl/LocalFeaturesInstallerHelper.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.features.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; + +public class LocalFeaturesInstallerHelper extends FeaturesInstallerHelperImpl { + + @Override + public InstallationResultImpl install(InstallationResultImpl installationResult) { + // TODO Auto-generated method stub + return null; + } + + @Override + public InstallationResultImpl uninstall(InstallationResultImpl installationResult) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/ClusterTypedConfigurableHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/ClusterTypedConfigurableHelper.java new file mode 100644 index 00000000..5b564363 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/ClusterTypedConfigurableHelper.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.impl.cluster.ClusterTypedInstallerHelper; + +public abstract class ClusterTypedConfigurableHelper extends ClusterTypedInstallerHelper + implements InstallerConfigurableHelper { + + protected T config; + + @Override + public void setConfig(T config) { + this.config = config; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/ExtendedTypedInstallerImpl.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/ExtendedTypedInstallerImpl.java new file mode 100644 index 00000000..acac035f --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/ExtendedTypedInstallerImpl.java @@ -0,0 +1,82 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult; +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; +import ru.entaxy.platform.core.artifact.installer.builder.impl.cluster.ClusterTypedInstallerHelper; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.HelperCreator; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperImpl; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerImpl; + +public abstract class ExtendedTypedInstallerImpl, T> extends TypedInstallerImpl + implements HelperCreator { + + protected S localTypedHelper; + + protected abstract Class getHelperClass(); + + @Override + public InstallationResult install() { + InstallationResultImpl result = InstallationResultImpl.create(); + if (localTypedHelper == null) + result.failed("HELPER NOT FOUND"); + else + result = localTypedHelper.install(result); + return result; + } + + @Override + public InstallationResult uninstall() { + InstallationResultImpl result = InstallationResultImpl.create(); + if (localTypedHelper == null) + result.failed("HELPER NOT FOUND"); + else + result = localTypedHelper.uninstall(result); + return result; + } + + @Override + public void setHelper(TypedInstallerHelperImpl helper) { + if (getHelperClass().isInstance(helper)) { + this.localTypedHelper = (S) helper; + if (localTypedHelper.getConfigClass().isAssignableFrom(getClass())) + localTypedHelper.setConfig((T) this); + } + super.setHelper(helper); + } + + @Override + public H createHelper(Class targetClass) { + if (ClusterTypedInstallerHelper.class.isAssignableFrom(targetClass)) + return (H) createClusterHelper(targetClass); + return (H) createLocalHelper(targetClass); + } + + protected abstract H createClusterHelper(Class targetClass); + + protected abstract H createLocalHelper(Class targetClass); +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/InstallerConfigurableHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/InstallerConfigurableHelper.java new file mode 100644 index 00000000..621a43f6 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/InstallerConfigurableHelper.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallationResultImpl; + +public interface InstallerConfigurableHelper { + + void setConfig(T config); + + Class getConfigClass(); + + public InstallationResultImpl install(InstallationResultImpl installationResult); + + public InstallationResultImpl uninstall(InstallationResultImpl installationResult); + + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/LocalTypedConfigurableHelper.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/LocalTypedConfigurableHelper.java new file mode 100644 index 00000000..a3d7c636 --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/impl/LocalTypedConfigurableHelper.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.impl; + +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerHelperImpl; + +public abstract class LocalTypedConfigurableHelper extends TypedInstallerHelperImpl + implements InstallerConfigurableHelper { + + protected T config; + + @Override + public void setConfig(T config) { + this.config = config; + } + +} diff --git a/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/internal/Registrator.java b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/internal/Registrator.java new file mode 100644 index 00000000..7ba9fcde --- /dev/null +++ b/platform/runtime/core/artifact-management-extensions/src/main/java/ru/entaxy/platform/core/artifact/ext/internal/Registrator.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management-extensions + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.ext.internal; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.platform.core.artifact.Artifacts; +import ru.entaxy.platform.core.artifact.ext.ExtTypedInstallerFactory; +import ru.entaxy.platform.core.artifact.ext.binary.JarArtifact; +import ru.entaxy.platform.core.artifact.ext.binary.UntypedBinaryArtifact; +import ru.entaxy.platform.core.artifact.installer.builder.typed.TypedInstallerManager; +import ru.entaxy.platform.core.artifact.service.ArtifactService; + +@Component(service = Registrator.class, immediate = true) +public class Registrator { + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ArtifactService artifactService; + + @Activate + public void activate() { + Artifacts.registerSupport(JarArtifact.class); + Artifacts.registerSupport(UntypedBinaryArtifact.class); + + TypedInstallerManager.register(new ExtTypedInstallerFactory()); + + } + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/AbstractTypedInstallerFactory.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/AbstractTypedInstallerFactory.java new file mode 100644 index 00000000..67c323e8 --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/AbstractTypedInstallerFactory.java @@ -0,0 +1,74 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed; + +import java.util.Arrays; +import java.util.List; + +public abstract class AbstractTypedInstallerFactory implements TypedInstallerFactory { + + protected List> supportedClasses; + + protected List supportedTypes; + + protected AbstractTypedInstallerFactory() { + super(); + if (this.getClass().isAnnotationPresent(TypedInstallerFactoryDescriptor.class)) { + TypedInstallerFactoryDescriptor descriptor = + this.getClass().getAnnotation(TypedInstallerFactoryDescriptor.class); + this.supportedClasses = Arrays.asList(descriptor.supportedClasses()); + this.supportedTypes = Arrays.asList(descriptor.supportedTypes()); + } + } + + @Override + public List> getSupportedClasses() { + return supportedClasses; + } + + @Override + public List getSupportedTypes() { + return supportedTypes; + } + + @Override + public TypedInstaller create(String type) { + if (!supportedTypes.contains(type)) + return null; + return doCreate(type); + } + + protected abstract TypedInstaller doCreate(String type); + + @Override + public TypedInstaller create(Class targetClass) { + if (!supportedClasses.contains(targetClass)) + return null; + return doCreate(targetClass); + } + + protected abstract TypedInstaller doCreate(Class targetClass); +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/DefaultTypedInstallerFactory.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/DefaultTypedInstallerFactory.java new file mode 100644 index 00000000..ab128afa --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/DefaultTypedInstallerFactory.java @@ -0,0 +1,98 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.HashMap; +import java.util.Map; + +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.BlueprintInstallerImpl; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.BundleInstallerImpl; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.JarInstallerImpl; +import ru.entaxy.platform.core.artifact.installer.builder.typed.impl.TypedInstallerImpl; + +@TypedInstallerFactoryDescriptor(supportedTypes = {Artifact.ARTIFACT_CATEGORY_BLUEPRINT, + Artifact.ARTIFACT_CATEGORY_BUNDLE, Artifact.ARTIFACT_CATEGORY_JAR}, + supportedClasses = {BlueprintInstaller.class, BundleInstaller.class, JarInstaller.class}) +public class DefaultTypedInstallerFactory extends AbstractTypedInstallerFactory { + + protected static DefaultTypedInstallerFactory INSTANCE; + + public static DefaultTypedInstallerFactory getInstance() { + if (INSTANCE == null) + INSTANCE = new DefaultTypedInstallerFactory(); + return INSTANCE; + } + + protected static Map> typeToClassMap; + protected static Map, Class> classToClassMap; + + static { + + typeToClassMap = new HashMap<>(); + typeToClassMap.put(Artifact.ARTIFACT_CATEGORY_BLUEPRINT, BlueprintInstallerImpl.class); + typeToClassMap.put(Artifact.ARTIFACT_CATEGORY_BUNDLE, BundleInstallerImpl.class); + typeToClassMap.put(Artifact.ARTIFACT_CATEGORY_JAR, JarInstallerImpl.class); + + classToClassMap = new HashMap<>(); + classToClassMap.put(BlueprintInstaller.class, BlueprintInstallerImpl.class); + classToClassMap.put(BundleInstaller.class, BundleInstallerImpl.class); + classToClassMap.put(JarInstaller.class, JarInstallerImpl.class); + + } + + protected DefaultTypedInstallerFactory() { + super(); + } + + @Override + protected TypedInstaller doCreate(String type) { + Class clazz = typeToClassMap.get(type); + if (clazz == null) + return null; + return createOfClass(clazz); + } + + @Override + protected TypedInstaller doCreate(Class targetClass) { + Class clazz = classToClassMap.get(targetClass); + if (clazz == null) + return null; + return createOfClass(clazz); + } + + protected TypedInstaller createOfClass(Class clazz) { + try { + Constructor constructor = clazz.getConstructor(); + return (TypedInstaller) constructor.newInstance(); + } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException + | IllegalArgumentException | InvocationTargetException e) { + return null; + } + } +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerFactory.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerFactory.java new file mode 100644 index 00000000..7190b09d --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerFactory.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed; + +import java.util.List; + +public interface TypedInstallerFactory { + + List> getSupportedClasses(); + + List getSupportedTypes(); + + TypedInstaller create(String type); + + TypedInstaller create(Class targetClass); + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerFactoryDescriptor.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerFactoryDescriptor.java new file mode 100644 index 00000000..bac67a5e --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerFactoryDescriptor.java @@ -0,0 +1,42 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface TypedInstallerFactoryDescriptor { + + Class[] supportedClasses(); + + String[] supportedTypes(); + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerManager.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerManager.java new file mode 100644 index 00000000..ea437346 --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/TypedInstallerManager.java @@ -0,0 +1,192 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed; + +import java.util.HashMap; +import java.util.Map; + +import ru.entaxy.platform.core.artifact.installer.builder.ClusterInstaller; +import ru.entaxy.platform.core.artifact.installer.builder.Installer; +import ru.entaxy.platform.core.artifact.installer.builder.LocalInstaller; + +public class TypedInstallerManager { + + + protected static Map>, TypedInstallerStorage> storages = new HashMap<>(); + + protected static TypedInstallerStorage commonStorage = new TypedInstallerStorage(); + + static { + storages.put(LocalInstaller.class, new TypedInstallerStorage()); + storages.put(ClusterInstaller.class, new TypedInstallerStorage()); + } + + protected static Object storagesLock = new Object(); + + public static void register(String artifactType, + TypedInstallerFactory factory) { + + register(commonStorage, artifactType, factory); + } + + public static void register(TypedInstallerFactory factory) { + + register(commonStorage, factory); + } + + protected static TypedInstallerStorage getOrCreateStorage(Class> installerClass) { + if (!storages.containsKey(installerClass)) { + synchronized (storagesLock) { + storages.put(installerClass, new TypedInstallerStorage()); + } + } + return storages.get(installerClass); + } + + public static void register(Class> installerClass, String artifactType, + TypedInstallerFactory factory) { + register(getOrCreateStorage(installerClass), artifactType, factory); + } + + public static void register(Class> installerClass, + TypedInstallerFactory factory) { + register(getOrCreateStorage(installerClass), factory); + } + + protected static void register(TypedInstallerStorage storage, TypedInstallerFactory factory) { + for (String type : factory.getSupportedTypes()) + register(storage, type, factory); + } + + protected static void register(TypedInstallerStorage storage, String artifactType, + TypedInstallerFactory factory) { + storage.register(artifactType, factory); + } + + public static TypedInstaller create(Object owner, String type) { + return create(owner, type, false); + } + + public static TypedInstaller create(Object owner, String type, boolean strict) { + for (Class> installerClass : storages.keySet()) + if (installerClass.isInstance(owner)) + return create(installerClass, type, strict); + if (strict) + return null; + return create(null, type, strict); + } + + public static TypedInstaller create(Class> installerClass, String type) { + return create(installerClass, type, false); + } + + public static TypedInstaller create(Class> installerClass, String type, boolean strict) { + TypedInstallerStorage storage = installerClass == null ? null : storages.get(installerClass); + TypedInstaller result = null; + if (storage != null) { + result = storage.create(type); + } + if (result != null) + return result; + if (strict) + return null; + else + return commonStorage.create(type); + + } + + public static TypedInstaller create(Object owner, Class typedClass) { + return create(owner, typedClass, false); + } + + public static TypedInstaller create(Object owner, Class typedClass, boolean strict) { + for (Class> installerClass : storages.keySet()) + if (installerClass.isInstance(owner)) + return create(installerClass, typedClass, strict); + if (strict) + return null; + return create(null, typedClass, strict); + } + + public static TypedInstaller create(Class> installerClass, + Class typedClass) { + return create(installerClass, typedClass, false); + } + + public static TypedInstaller create(Class> installerClass, + Class typedClass, boolean strict) { + TypedInstallerStorage storage = installerClass == null ? null : storages.get(installerClass); + TypedInstaller result = null; + if (storage != null) { + result = storage.create(typedClass); + } + if (result != null) + return result; + if (strict) + return null; + else + return commonStorage.create(typedClass); + + } + + + protected static class TypedInstallerStorage { + + protected Map factories = new HashMap<>(); + + protected Object factoriesLock = new Object(); + + public void register(String type, TypedInstallerFactory factory) { + synchronized (factoriesLock) { + factories.put(type, factory); + } + } + + public TypedInstaller create(String type) { + if (!factories.containsKey(type)) + return null; + return factories.get(type).create(type); + } + + public TypedInstaller create(Class typedClass) { + + TypedInstallerFactory factory = null; + + for (TypedInstallerFactory f : factories.values()) + if (f.getSupportedClasses().contains(typedClass)) { + factory = f; + break; + } + + if (factory == null) + return null; + + return factory.create(typedClass); + } + + } + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/HelperCreator.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/HelperCreator.java new file mode 100644 index 00000000..e6b75e2e --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/HelperCreator.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed.impl; + +public interface HelperCreator { + + H createHelper(Class targetClass); + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/TypedInstallerHelperAware.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/TypedInstallerHelperAware.java new file mode 100644 index 00000000..8d2dc9a6 --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/TypedInstallerHelperAware.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed.impl; + +public interface TypedInstallerHelperAware { + + TypedInstallerHelperImpl getHelper(); + + void setHelper(TypedInstallerHelperImpl helper); + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/TypedInstallerHelperImpl.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/TypedInstallerHelperImpl.java new file mode 100644 index 00000000..2a0cfd1b --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/installer/builder/typed/impl/TypedInstallerHelperImpl.java @@ -0,0 +1,30 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.installer.builder.typed.impl; + +public class TypedInstallerHelperImpl { + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/RepositoryDescriptor.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/RepositoryDescriptor.java new file mode 100644 index 00000000..740c3342 --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/RepositoryDescriptor.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.repository; + + + +public interface RepositoryDescriptor { + + String getName(); + + String getLocation(); + + String getUrl(); + + boolean isProxy(); + + boolean isMirror(); + + boolean isSnapshots(); + + String getRemotes(); + + boolean isReadOnly(); + + boolean isCopyOnChange(); + + boolean isEnabled(); + + String getUsername(); + + String getPassword(); + + String getRemoteHostSuffix(); + + boolean isSystem(); + + boolean isLookupEnabled(); + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/RepositoryDescriptorCollector.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/RepositoryDescriptorCollector.java new file mode 100644 index 00000000..c1534c14 --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/RepositoryDescriptorCollector.java @@ -0,0 +1,35 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.repository; + +/* + * Internal interface to collect helpers managed by config files + */ +public interface RepositoryDescriptorCollector { + public void addRepositoryDescriptor(RepositoryDescriptor helper); + + public void removeRepositoryDescriptor(RepositoryDescriptor helper); +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/impl/RepositoryDescriptorImpl.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/impl/RepositoryDescriptorImpl.java new file mode 100644 index 00000000..f0935ab5 --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/impl/RepositoryDescriptorImpl.java @@ -0,0 +1,188 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.repository.impl; + +import ru.entaxy.platform.core.artifact.repository.RepositoryDescriptor; + +public class RepositoryDescriptorImpl implements RepositoryDescriptor { + + protected String name; + String location; + String url; + boolean isProxy; + boolean isMirror; + String remotes; + boolean isReadOnly = false; + boolean copyOnChange; + String username = ""; + String password = ""; + + boolean isSnapshots = false; + + boolean isEnabled = true; + + String remoteHostSuffix = ""; + + boolean isSystem = true; + + boolean isLookupEnabled = true; + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public String getLocation() { + return location; + } + + public void setLocation(String location) { + this.location = location; + } + + @Override + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + @Override + public boolean isProxy() { + return isProxy; + } + + public void setProxy(boolean isProxy) { + this.isProxy = isProxy; + } + + @Override + public boolean isMirror() { + return isMirror; + } + + public void setMirror(boolean isMirror) { + this.isMirror = isMirror; + } + + @Override + public boolean isSnapshots() { + return isSnapshots; + } + + public void setSnapshots(boolean isSnapshots) { + this.isSnapshots = isSnapshots; + } + + @Override + public String getRemotes() { + return remotes; + } + + public void setRemotes(String remotes) { + this.remotes = remotes; + } + + @Override + public boolean isReadOnly() { + return isReadOnly; + } + + public void setReadOnly(boolean isReadOnly) { + this.isReadOnly = isReadOnly; + } + + @Override + public boolean isCopyOnChange() { + return copyOnChange; + } + + public void setCopyOnChange(boolean copyOnChange) { + this.copyOnChange = copyOnChange; + } + + @Override + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean isEnabled) { + this.isEnabled = isEnabled; + } + + @Override + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + @Override + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public String getRemoteHostSuffix() { + return remoteHostSuffix; + } + + public void setRemoteHostSuffix(String remoteHostSuffix) { + this.remoteHostSuffix = remoteHostSuffix; + } + + @Override + public boolean isSystem() { + return isSystem; + } + + public void setSystem(boolean isSystem) { + this.isSystem = isSystem; + } + + @Override + public boolean isLookupEnabled() { + return isLookupEnabled; + } + + public void setLookupEnabled(boolean isLookupEnabled) { + this.isLookupEnabled = isLookupEnabled; + } + +} diff --git a/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/impl/RepositoryRegistrator.java b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/impl/RepositoryRegistrator.java new file mode 100644 index 00000000..632db9ef --- /dev/null +++ b/platform/runtime/core/artifact-management/src/main/java/ru/entaxy/platform/core/artifact/repository/impl/RepositoryRegistrator.java @@ -0,0 +1,158 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.artifact.repository.impl; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.commons.codec.digest.DigestUtils; +import org.apache.felix.utils.properties.TypedProperties; +import org.apache.karaf.config.core.ConfigRepository; +import org.osgi.framework.InvalidSyntaxException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.osgi.OSGIUtils; +import ru.entaxy.platform.core.artifact.repository.ArtifactRepository; + +public class RepositoryRegistrator { + + private static final Logger log = LoggerFactory.getLogger(RepositoryRegistrator.class); + + public static RepositoryRegistrator INSTANCE = new RepositoryRegistrator(); + + private static final String REPO_CONFIG_PID = "org.ops4j.pax.url.mvn"; + + private static final String PROP_ENTAXY_SYSTEM_REPO_LIST = "org.ops4j.pax.url.mvn.repositories.entaxy"; + private static final String PROP_ENTAXY_CUSTOM_REPO_LIST = "org.ops4j.pax.url.mvn.repositories.entaxy.custom"; + + private static final String ENTAXY_PROPERTY_HTTP_PORT = "entaxy.org.osgi.service.http.port"; + + private static final String URL_PREFIX = "http://localhost:${" + ENTAXY_PROPERTY_HTTP_PORT + "}"; + + protected Map systemRepos = new HashMap<>(); + protected Map customRepos = new HashMap<>(); + + private RepositoryRegistrator() { + + } + + public void addRepository(ArtifactRepository repository) { + addRepository(repository, true); + } + public void addRepository(ArtifactRepository repository, boolean httpEnabled) { + Map targetMap; + String propertyName; + if (repository.isSystem()) { + targetMap = systemRepos; + propertyName = PROP_ENTAXY_SYSTEM_REPO_LIST; + // TODO implement for initializer + return; + } else { + targetMap = customRepos; + propertyName = PROP_ENTAXY_CUSTOM_REPO_LIST; + } + + targetMap.put(repository.getName(), repository); + + String repositoryUrlsResult = calculatePropertyValue(targetMap, httpEnabled); + try { + setPropertyValue(propertyName, repositoryUrlsResult); + return; + } catch (IOException e) { + log.error("Error updating config", e); + } catch (InvalidSyntaxException e) { + log.error("Error updating config", e); + } catch (Exception e) { + log.error("Error updating config", e); + } + + targetMap.remove(repository.getName()); + } + + public void removeRepository(ArtifactRepository repository) { + if (repository.isSystem()) { + systemRepos.remove(repository.getName()); + } else { + customRepos.remove(repository.getName()); + } + } + + protected String calculatePropertyValue(Map repoMap, boolean httpEnabled) { + List list = new ArrayList<>(repoMap.values()); + Collections.sort(list, new Comparator() { + + @Override + public int compare(ArtifactRepository o1, ArtifactRepository o2) { + return o1.getName().compareToIgnoreCase(o2.getName()); + } + + }); + + String resultValue = ""; + List urlList = new ArrayList<>(); + for (ArtifactRepository repo : list) { + String url = URL_PREFIX.concat(repo.getUrl()) + .concat("@id=").concat(repo.getName()) + .concat("@checksum=ignore") + .concat(repo.isSnapshotsAllowed() ? "@snapshots" : ""); + if (!httpEnabled) { + url = url.replace("http:", "https:"); + } + urlList.add(url); + } + resultValue = urlList.stream().collect(Collectors.joining(", ")); + return resultValue; + } + + protected void setPropertyValue(String propertyName, String propertyValue) throws Exception { + ConfigRepository configRepository = + OSGIUtils.services().ofClass(ConfigRepository.class).waitService(20000).get(); + + TypedProperties properties = configRepository.getConfig(REPO_CONFIG_PID); + + String hashKey = propertyName + ".md5"; + + String newHash = DigestUtils.md5Hex(propertyValue); + String currentHash = properties.getOrDefault(hashKey, "").toString(); + + // To avoid extra config rewriting + // which may cause config loss while updating + if (!newHash.equals(currentHash)) { + properties.put(propertyName, propertyValue); + properties.put(hashKey, newHash); + configRepository.update(REPO_CONFIG_PID, properties); + } + + } + +} diff --git a/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalConfigurationEventHandler.java b/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalConfigurationEventHandler.java new file mode 100644 index 00000000..e0491faa --- /dev/null +++ b/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalConfigurationEventHandler.java @@ -0,0 +1,169 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cluster-persistence-service + * ========== + * 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~~~~~~ + */ +/* + * 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. + */ +package ru.entaxy.esb.platform.core.cluster.persistence.handler; + +import java.util.Map; +import java.util.Properties; + +import org.apache.karaf.cellar.config.ClusterConfigurationEvent; +import org.apache.karaf.cellar.config.ConfigurationEventHandler; +import org.apache.karaf.cellar.config.ConfigurationSupport; +import org.apache.karaf.cellar.config.Constants; +import org.apache.karaf.cellar.core.Configurations; +import org.apache.karaf.cellar.core.Group; +import org.apache.karaf.cellar.core.control.BasicSwitch; +import org.apache.karaf.cellar.core.control.Switch; +import org.apache.karaf.cellar.core.control.SwitchStatus; +import org.apache.karaf.cellar.core.event.EventHandler; +import org.apache.karaf.cellar.core.event.EventType; +import org.osgi.service.cm.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.cluster.persistence.PersistenceManager; + +/** + * LocalConfigurationEventHandler handles received configuration cluster event. + */ +public class LocalConfigurationEventHandler extends ConfigurationSupport + implements EventHandler { + + private static final transient Logger LOGGER = LoggerFactory.getLogger(LocalConfigurationEventHandler.class); + + public static final String SWITCH_ID = "org.apache.karaf.cellar.configuration.handler"; + + private final Switch eventSwitch = new BasicSwitch(SWITCH_ID); + + private PersistenceManager persistenceManager; + + @Override + public void handle(ClusterConfigurationEvent event) { + + // check if the handler is ON + if (this.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + LOGGER.debug("CELLAR CONFIG: {} switch is OFF, cluster event not handled", SWITCH_ID); + return; + } + + if (groupManager == null) { + // in rare cases for example right after installation this happens! + LOGGER.error("CELLAR CONFIG: retrieved event {} while groupManager is not available yet!", event); + return; + } + + // check if the group is local + if (!groupManager.isLocalGroup(event.getSourceGroup().getName())) { + LOGGER.debug("CELLAR CONFIG: node is not part of the event cluster group {}", + event.getSourceGroup().getName()); + return; + } + + // @ENTAXY:SKIP check if it's not a "local" event + //if (event.getLocal() != null && event.getLocal().getId().equalsIgnoreCase(clusterManager.getNode().getId())) { + // LOGGER.trace("CELLAR CONFIG: cluster event is local (coming from local synchronizer or listener)"); + // return; + //} + + Group group = event.getSourceGroup(); + String groupName = group.getName(); + + Map clusterConfigurations = + clusterManager.getMap(Constants.CONFIGURATION_MAP + Configurations.SEPARATOR + groupName); + + String pid = event.getId(); + + if (isAllowed(event.getSourceGroup(), Constants.CATEGORY, pid, EventType.INBOUND)) { + try { + // TODO mark cluster state as needed to be saved + LOGGER.debug("-->> WE NEED TO SAVE CLUSTER STATE"); + this.persistenceManager.updated(); + } catch (Exception ex) { + LOGGER.error("CELLAR CONFIG: failed to read cluster configuration", ex); + } + } else + LOGGER.trace("CELLAR CONFIG: configuration PID {} is marked BLOCKED INBOUND for cluster group {}", pid, + groupName); + } + + public void init() { + // nothing to do + } + + public void destroy() { + // nothing to do + } + + /** + * Get the cluster configuration event handler switch. + * + * @return the cluster configuration event handler switch. + */ + @Override + public Switch getSwitch() { + // load the switch status from the config + try { + Configuration configuration = configurationAdmin.getConfiguration(Configurations.NODE, null); + if (configuration != null) { + Boolean status = new Boolean((String) configuration.getProperties() + .get(Configurations.HANDLER + "." + ConfigurationEventHandler.class.getName())); + if (status) { + eventSwitch.turnOn(); + } else { + eventSwitch.turnOff(); + } + } + } catch (Exception e) { + // nothing to do + } + return eventSwitch; + } + + /** + * Get the cluster event type. + * + * @return the cluster configuration event type. + */ + @Override + public Class getType() { + return ClusterConfigurationEvent.class; + } + + public void setPersistenceManager(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + +} diff --git a/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalFeaturesEventHandler.java b/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalFeaturesEventHandler.java new file mode 100644 index 00000000..0017dc5b --- /dev/null +++ b/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalFeaturesEventHandler.java @@ -0,0 +1,174 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cluster-persistence-service + * ========== + * 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~~~~~~ + */ +/* + * 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. + */ +package ru.entaxy.esb.platform.core.cluster.persistence.handler; + +import org.apache.karaf.cellar.core.Configurations; +import org.apache.karaf.cellar.core.control.BasicSwitch; +import org.apache.karaf.cellar.core.control.Switch; +import org.apache.karaf.cellar.core.control.SwitchStatus; +import org.apache.karaf.cellar.core.event.EventHandler; +import org.apache.karaf.cellar.core.event.EventType; +import org.apache.karaf.cellar.features.ClusterFeaturesEvent; +import org.apache.karaf.cellar.features.Constants; +import org.apache.karaf.cellar.features.FeatureState; +import org.apache.karaf.cellar.features.FeaturesEventHandler; +import org.apache.karaf.cellar.features.FeaturesSupport; +import org.apache.karaf.cellar.features.FeaturesSynchronizer; +import org.apache.karaf.features.FeatureEvent; +import org.osgi.framework.BundleContext; +import org.osgi.service.cm.Configuration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.cluster.persistence.PersistenceManager; + +/** + * Handler for cluster features event. + */ +public class LocalFeaturesEventHandler extends FeaturesSupport implements EventHandler { + + private static final transient Logger LOGGER = LoggerFactory.getLogger(FeaturesSynchronizer.class); + + public static final String SWITCH_ID = "org.apache.karaf.cellar.event.features.handler"; + + private final Switch eventSwitch = new BasicSwitch(SWITCH_ID); + + private PersistenceManager persistenceManager; + + public PersistenceManager getPersistenceManager() { + return persistenceManager; + } + + public void setPersistenceManager(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + + @Override + public void init(BundleContext bundleContext) { + super.init(bundleContext); + } + + @Override + public void destroy() { + super.destroy(); + } + + /** + * Handle a received cluster features event. + * + * @param event the received cluster feature event. + */ + public void handle(ClusterFeaturesEvent event) { + + if (this.getSwitch().getStatus().equals(SwitchStatus.OFF)) { + LOGGER.debug("CELLAR FEATURE: {} switch is OFF, cluster event is not handled", SWITCH_ID); + return; + } + + if (groupManager == null) { + // in rare cases for example right after installation this happens! + LOGGER.error("CELLAR FEATURE: retrieved event {} while groupManager is not available yet!", event); + return; + } + + // check if the group is local + if (!groupManager.isLocalGroup(event.getSourceGroup().getName())) { + LOGGER.debug("CELLAR FEATURE: node is not part of the event cluster group {}", + event.getSourceGroup().getName()); + return; + } + + // check if it's not a "local" event + if (event.getLocal() != null && event.getLocal().getId().equalsIgnoreCase(clusterManager.getNode().getId())) { + LOGGER.trace("CELLAR FEATURE: cluster event is local (coming from local synchronizer or listener)"); + return; + } + + String name = event.getName(); + String version = event.getVersion(); + if (isAllowed(event.getSourceGroup(), Constants.CATEGORY, name, EventType.INBOUND) || event.getForce()) { + FeatureEvent.EventType type = event.getType(); + Boolean isInstalled = isFeatureInstalledLocally(name, version); + try { + + persistenceManager.updated(); + + } catch (Exception e) { + LOGGER.error("CELLAR FEATURE: failed to handle cluster feature event", e); + } + } else + LOGGER.trace("CELLAR FEATURE: feature {} is marked BLOCKED INBOUND for cluster group {}", name, + event.getSourceGroup().getName()); + } + + /** + * Get the event type that this handler is able to handle. + * + * @return the cluster features event type. + */ + @Override + public Class getType() { + return ClusterFeaturesEvent.class; + } + + /** + * Get the handler switch. + * + * @return the handler switch. + */ + @Override + public Switch getSwitch() { + // load the switch status from the config + try { + Configuration configuration = configurationAdmin.getConfiguration(Configurations.NODE, null); + if (configuration != null) { + Boolean status = new Boolean((String) configuration.getProperties() + .get(Configurations.HANDLER + "." + + FeaturesEventHandler.class.getName())); + if (status) { + eventSwitch.turnOn(); + } else { + eventSwitch.turnOff(); + } + } + } catch (Exception e) { + // ignore + } + return eventSwitch; + } + +} diff --git a/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalRepositoryEventHandler.java b/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalRepositoryEventHandler.java new file mode 100644 index 00000000..63b07698 --- /dev/null +++ b/platform/runtime/core/cluster/cluster-persistence-service/src/main/java/ru/entaxy/esb/platform/core/cluster/persistence/handler/LocalRepositoryEventHandler.java @@ -0,0 +1,135 @@ +/*- + * ~~~~~~licensing~~~~~~ + * cluster-persistence-service + * ========== + * 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~~~~~~ + */ +/* + * 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. + */ +package ru.entaxy.esb.platform.core.cluster.persistence.handler; + +import org.apache.karaf.cellar.core.control.BasicSwitch; +import org.apache.karaf.cellar.core.control.Switch; +import org.apache.karaf.cellar.core.control.SwitchStatus; +import org.apache.karaf.cellar.core.event.EventHandler; +import org.apache.karaf.cellar.features.ClusterRepositoryEvent; +import org.apache.karaf.cellar.features.FeaturesSupport; +import org.apache.karaf.features.RepositoryEvent; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.cluster.persistence.PersistenceManager; + +/** + * Handler for cluster features repository event. + */ +public class LocalRepositoryEventHandler extends FeaturesSupport implements EventHandler { + + private static final transient Logger LOGGER = LoggerFactory.getLogger(LocalRepositoryEventHandler.class); + + public static final String SWITCH_ID = "org.apache.karaf.cellar.event.repository.handler"; + + private final Switch eventSwitch = new BasicSwitch(SWITCH_ID); + + private PersistenceManager persistenceManager; + + @Override + public void init(BundleContext bundleContext) { + super.init(bundleContext); + } + + @Override + public void destroy() { + super.destroy(); + } + + /** + * Handle cluster features repository event. + * + * @param event the cluster event to handle. + */ + @Override + public void handle(ClusterRepositoryEvent event) { + + // check if the handler is ON + if (eventSwitch.getStatus().equals(SwitchStatus.OFF)) { + LOGGER.debug("CELLAR FEATURE: {} switch is OFF, cluster event is not handled", SWITCH_ID); + return; + } + + if (groupManager == null) { + // in rare cases for example right after installation this happens! + LOGGER.error("CELLAR FEATURE: retrieved event {} while groupManager is not available yet!", event); + return; + } + + // check if the group is local + if (!groupManager.isLocalGroup(event.getSourceGroup().getName())) { + LOGGER.debug("CELLAR FEATURE: node is not part of the event cluster group"); + return; + } + + // check if the event is not "local" + if (event.getLocal() != null && event.getLocal().getId().equals(clusterManager.getNode().getId())) { + LOGGER.trace("CELLAR FEATURE: event is local (coming from synchronizer or listener)"); + return; + } + + String uri = event.getId(); + RepositoryEvent.EventType type = event.getType(); + try { + + // TODO mark cluster state as needed to be saved + LOGGER.debug("-->> WE NEED TO SAVE CLUSTER STATE"); + this.persistenceManager.updated(); + + } catch (Exception e) { + LOGGER.error("CELLAR FEATURE: failed to add/remove repository URL {}", uri, e); + } + } + + @Override + public Class getType() { + return ClusterRepositoryEvent.class; + } + + @Override + public Switch getSwitch() { + return eventSwitch; + } + + public void setPersistenceManager(PersistenceManager persistenceManager) { + this.persistenceManager = persistenceManager; + } + + +} diff --git a/platform/runtime/core/core-support/cfg/ignite.cfg b/platform/runtime/core/core-support/cfg/ignite.cfg new file mode 100644 index 00000000..e8ec5e68 --- /dev/null +++ b/platform/runtime/core/core-support/cfg/ignite.cfg @@ -0,0 +1,6 @@ +ignite.work.directory.path=data/ignite +ignite.common.cache.name=entaxy +ignite.common.cache.cacheMode=REPLICATED +ignite.common.cache.rebalanceMode=SYNC +ignite.common.cache.atomicityMode=TRANSACTIONAL +ignite.common.cache.backups=2 \ No newline at end of file diff --git a/platform/runtime/core/core-support/cfg/jgroups.locking.xml b/platform/runtime/core/core-support/cfg/jgroups.locking.xml new file mode 100644 index 00000000..a3391afc --- /dev/null +++ b/platform/runtime/core/core-support/cfg/jgroups.locking.xml @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/EntaxyOpenApiGeneratorDeprecated.java b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/EntaxyOpenApiGeneratorDeprecated.java new file mode 100644 index 00000000..efa8401e --- /dev/null +++ b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/EntaxyOpenApiGeneratorDeprecated.java @@ -0,0 +1,658 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-design + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.design.openapi; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.stream.JsonGenerator; + +import org.apache.commons.io.FileUtils; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.Generator; +import org.openapitools.codegen.config.CodegenConfigurator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.github.javaparser.ast.CompilationUnit; +import com.github.javaparser.serialization.JavaParserJsonSerializer; +import com.github.javaparser.utils.SourceRoot; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.OpenAPIV3Parser; +import io.swagger.v3.parser.core.models.SwaggerParseResult; +import javassist.CtClass; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.support.design.classgen.Cu2JaConverter; + +@Deprecated(since = "1.10", forRemoval = true) +public class EntaxyOpenApiGeneratorDeprecated { + + private static final Logger log = LoggerFactory.getLogger(EntaxyOpenApiGeneratorDeprecated.class); + + public enum GENERATION_STATUS { + NONE, + IN_PROGRESS, + OK, + FAILED + } + + public enum GENERATION_PHASE { + NONE, + CHECK, + GENERATE_JAVA, + PARSE_JAVA, + GENERATE_CLASSES + } + + public enum GENERATION_PHASE_STATE { + PRE_EXECUTE, + IN_PROGRESS, + DONE + } + + public static interface GenerationCallback { + + public void event(GenerationResult generationResult); + + } + + public static abstract class AbstractResult { + public GENERATION_STATUS status = GENERATION_STATUS.NONE; + public List exceptions = new ArrayList<>();; + public Map properties = new HashMap<>(); + + public AbstractResult status(GENERATION_STATUS newStatus) { + this.status = newStatus; + return this; + } + + public boolean isOk() { + return GENERATION_STATUS.OK.equals(status); + } + + public boolean isFailed() { + return GENERATION_STATUS.FAILED.equals(status); + } + + public boolean isInProgress() { + return GENERATION_STATUS.IN_PROGRESS.equals(status); + } + + public boolean isFinished() { + return isOk() || isFailed(); + } + } + + public static class GenerationResult extends AbstractResult { + + public GENERATION_PHASE currentPhase = GENERATION_PHASE.NONE; + public Map phases = new LinkedHashMap<>(); + + public EntaxyOpenApiGeneratorDeprecated generator; + + public GenerationResult phase(GENERATION_PHASE phase) { + return this.phase(phase, new PhaseResult()); + } + + public GenerationResult phase(GENERATION_PHASE phase, PhaseResult phaseResult) { + phases.put(phase, phaseResult); + currentPhase = phase; + return this; + } + + public GenerationResult phaseStatus(GENERATION_STATUS newStatus) { + this.currentPhaseResult().status = newStatus; + this.generator.callback(this); + return this; + } + + public GenerationResult phaseInProgress() { + this.currentPhaseResult().state(GENERATION_PHASE_STATE.IN_PROGRESS); + return this.phaseStatus(GENERATION_STATUS.IN_PROGRESS); + } + + public GenerationResult phaseOk() { + this.currentPhaseResult().state(GENERATION_PHASE_STATE.DONE); + return this.phaseStatus(GENERATION_STATUS.OK); + } + + public GenerationResult phaseFailed() { + this.currentPhaseResult().state(GENERATION_PHASE_STATE.DONE); + return this.phaseStatus(GENERATION_STATUS.FAILED); + } + + public PhaseResult currentPhaseResult() { + return this.phases.get(currentPhase); + } + + public boolean isCurrentPhaseOk() { + return (currentPhase!=null) + && currentPhaseResult().status.equals(GENERATION_STATUS.OK); + } + + } + + public static class PhaseResult extends AbstractResult { + public List resultObjects = new ArrayList<>(); + public GENERATION_PHASE_STATE currentState = GENERATION_PHASE_STATE.PRE_EXECUTE; + public PhaseResult state(GENERATION_PHASE_STATE state) { + this.currentState = state; + return this; + } + } + + protected static abstract class PhaseProcessor { + + protected EntaxyOpenApiGeneratorDeprecated generator; + protected GenerationResult generationResult; + + public void process(EntaxyOpenApiGeneratorDeprecated generator, GenerationResult generationResult) { + this.generator = generator; + this.generationResult = generationResult; + this.generationResult.phase(getPhase()); + this.generator.callback(this.generationResult); + execute(); + } + + protected abstract GENERATION_PHASE getPhase(); + + protected void execute() { + this.generationResult.currentPhaseResult().state(GENERATION_PHASE_STATE.IN_PROGRESS); + this.generator.callback(this.generationResult); + doExecute(); + this.generationResult.currentPhaseResult().state(GENERATION_PHASE_STATE.DONE); + this.generator.callback(this.generationResult); + }; + + protected abstract void doExecute(); + + protected void failWithException(Throwable e) { + generationResult.exceptions.add(e); + generationResult.currentPhaseResult().exceptions.add(e); + generationResult.currentPhaseResult().state(GENERATION_PHASE_STATE.DONE); + generationResult.phaseFailed(); + generator.callback(generationResult); + } + } + + protected static class CheckPhaseProcessor extends PhaseProcessor { + + public CheckPhaseProcessor() { + super(); + } + + @Override + protected GENERATION_PHASE getPhase() { + return GENERATION_PHASE.CHECK; + } + + @Override + protected void doExecute() { + this.generationResult.currentPhaseResult().status(GENERATION_STATUS.IN_PROGRESS); + SwaggerParseResult result = (new OpenAPIV3Parser()).readLocation( + this.generator.getUrl() + , null + , null); + OpenAPI api = result.getOpenAPI(); + if (api != null) { + this.generationResult.currentPhaseResult().properties.put("api", api); + this.generationResult.properties.put("api", api); + this.generationResult.currentPhaseResult().status(GENERATION_STATUS.OK); + } else { + this.generationResult.currentPhaseResult().status(GENERATION_STATUS.FAILED); + } + } + + } + + protected static class GenerateJavaPhaseProcessor extends PhaseProcessor { + + public GenerateJavaPhaseProcessor() { + super(); + } + + @Override + protected GENERATION_PHASE getPhase() { + return GENERATION_PHASE.GENERATE_JAVA; + } + + @Override + protected void doExecute() { + this.generationResult.generator.initializeRootFolder(); + this.generationResult.phaseInProgress(); + + CodegenConfigurator configurator = new CodegenConfigurator(); + Generator codeGenerator; + + if (!CommonUtils.isValid(generator.getApiPackage())) { + generator.setApiPackage("entaxy.openapi." + + generator.apiTitleConverted + + ".v_" + generator.apiVersionConverted); + } + if (!CommonUtils.isValid(generator.getModelPackage())) { + generator.setModelPackage(generator.apiPackage + ".model"); + } + + configurator.setApiPackage(generator.apiPackage); + configurator.setModelPackage(generator.modelPackage); + + configurator.setGeneratorName("jaxrs-cxf"); + + configurator.setOutputDir( + Paths.get(generator.targetDir.getAbsolutePath(), "sources") + .toFile() + .getAbsolutePath()); + + configurator.setInputSpec(generator.getUrl()); + + try { + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + + codeGenerator = new DefaultGenerator(false); + + codeGenerator.opts(clientOptInput); + codeGenerator.generate(); + + generationResult.properties.put("generator.java.source.path", "sources/src/gen/java"); + + generationResult.phaseOk(); + + } catch (Exception e) { + + log.error("openapi-generator finished with exception", e); + failWithException(e); + } + + } + + } + + protected static class ParseJavaPhaseProcessor extends PhaseProcessor { + + public ParseJavaPhaseProcessor() { + super(); + } + + @Override + protected GENERATION_PHASE getPhase() { + return GENERATION_PHASE.PARSE_JAVA; + } + + @Override + protected void doExecute() { + + List apiCUs; + List modelCUs; + + String sourceRootFolder = Paths.get( generator.targetDir.getAbsolutePath() + ,generationResult.properties.get("generator.java.source.path") + .toString()).toAbsolutePath().toString(); + + String apiPackageFolder = generator.apiPackage.replace('.', '/'); + String modelPackageFolder = generator.modelPackage.replace('.', '/'); + + String apiFolder = Paths.get(sourceRootFolder, apiPackageFolder).toAbsolutePath().toString(); + String modelFolder = Paths.get(sourceRootFolder, modelPackageFolder).toAbsolutePath().toString(); + + File apiFolderFile = new File(apiFolder); + File[] apis = apiFolderFile.listFiles((dir, name)->dir.getAbsolutePath().equals(apiFolderFile.getAbsolutePath()) && name.endsWith(".java")); + File modelFolderFile = new File(modelFolder); + File[] models = modelFolderFile.listFiles((dir, name)->dir.getAbsolutePath().equals(modelFolderFile.getAbsolutePath()) && name.endsWith(".java")); + + String parsedRootFolder = Paths.get(generator.targetDir.getAbsolutePath(), "parsed").toAbsolutePath().toString(); + try { + Files.createDirectories(Paths.get(parsedRootFolder)); + Files.createDirectories(Paths.get(parsedRootFolder, "model")); + } catch (IOException e) { + log.error("Error creating directories", e); + } + + SourceRoot sourceRoot = new SourceRoot(Paths.get(sourceRootFolder)); + + JavaParserJsonSerializer serializer = new JavaParserJsonSerializer(); + + apiCUs = new ArrayList<>(); + modelCUs = new ArrayList<>(); + + for (int i=0; i0) { + for (int i=0; i apiCUs = (List)generationResult.properties + .getOrDefault("parser.cu.api", Collections.emptyList()); + @SuppressWarnings("unchecked") + List modelCUs = (List)generationResult.properties + .getOrDefault("parser.cu.model", Collections.emptyList()); + + try { + String classesRootFolder = Paths.get(generator.targetDir.getAbsolutePath(), "classes").toString(); + + Files.createDirectories(Paths.get(classesRootFolder)); + + Cu2JaConverter converter = new Cu2JaConverter(); + + List modelClassesImports = new ArrayList<>(); + for (CompilationUnit cu: modelCUs) + modelClassesImports.add(cu.getPackageDeclaration().get().getName().asString() + + "." + cu.getPrimaryType().get().getNameAsString()); + + List modelClasses = new ArrayList<>(); + List apiClasses = new ArrayList<>(); + + for (CompilationUnit cu: modelCUs) { + converter.clearImports(); + for (String s: modelClassesImports) + converter.addImport(s); + modelClasses.add(converter.convert(cu)); + } + + for (CompilationUnit cu: apiCUs) { + converter.clearImports(); + for (String s: modelClassesImports) + converter.addImport(s); + apiClasses.add(converter.convert(cu)); + } + + List apiClassesFinal = new ArrayList<>(); + List modelClassesFinal = new ArrayList<>(); + + for (CtClass ctClass: modelClasses) { + if (ctClass == null) + continue; + ctClass.writeFile(classesRootFolder); + modelClassesFinal.add(ctClass.getName()); + } + + for (CtClass ctClass: apiClasses) { + if (ctClass == null) + continue; + ctClass.writeFile(classesRootFolder); + apiClassesFinal.add(ctClass.getName()); + } + + generationResult.properties.put("classes.path", classesRootFolder); + generationResult.properties.put("classes.api", apiClassesFinal); + generationResult.properties.put("classes.model", modelClassesFinal); + + generationResult.phaseOk(); + + + } catch (Exception e) { + log.error("javassist finished with exception", e); + failWithException(e); + return; + } + + } + } + + protected static Map> processorMap = new HashMap<>(); + + protected static List defaultPlan = new LinkedList<>(); + + static { + + processorMap.put(GENERATION_PHASE.CHECK, CheckPhaseProcessor.class); + processorMap.put(GENERATION_PHASE.GENERATE_JAVA, GenerateJavaPhaseProcessor.class); + processorMap.put(GENERATION_PHASE.PARSE_JAVA, ParseJavaPhaseProcessor.class); + processorMap.put(GENERATION_PHASE.GENERATE_CLASSES, GenerateClassesPhaseProcessor.class); + + defaultPlan.add(GENERATION_PHASE.CHECK); + defaultPlan.add(GENERATION_PHASE.GENERATE_JAVA); + defaultPlan.add(GENERATION_PHASE.PARSE_JAVA); + defaultPlan.add(GENERATION_PHASE.GENERATE_CLASSES); + + } + + + + protected String url; + + protected String rootFolder = UUID.randomUUID().toString(); + + protected SwaggerParseResult parseResult; + + protected String apiTitleConverted = "unknown_api"; + protected String apiVersionConverted = "1_0_0"; + + protected String apiPackage; + protected String modelPackage; + + protected List executionPlan = defaultPlan; + + protected GenerationCallback callback; + + protected GenerationResult result = new GenerationResult(); + + protected File targetDir = null; + + public GenerationResult generate() { + + result.generator = this; + + result.phase(GENERATION_PHASE.NONE).status(GENERATION_STATUS.NONE); + callback(result); + if (executionPlan != null) { + result.status(GENERATION_STATUS.IN_PROGRESS); + callback(result); + for (GENERATION_PHASE phase: executionPlan) { + PhaseProcessor processor = null; + try { + processor = processorMap.get(phase).getConstructor().newInstance(); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException + | InvocationTargetException | NoSuchMethodException | SecurityException e) { + result.currentPhaseResult().exceptions.add(e); + result.exceptions.add(e); + result.status(GENERATION_STATUS.FAILED); + callback(result); + return result; + } + processor.process(this, result); + if (result.currentPhaseResult().status.equals(GENERATION_STATUS.FAILED)) + return result; + } + result.status(GENERATION_STATUS.OK); + callback(result); + } + return result; + } + + protected void initializeRootFolder() { + if (this.targetDir != null) + return; + Path target = Paths.get( + System.getProperty("karaf.home") + , "temp" + , rootFolder); + this.targetDir = target.toFile(); + if (!this.targetDir.exists()) + this.targetDir.mkdirs(); + } + + public void clean() { + try { + FileUtils.deleteDirectory(targetDir); + } catch (IOException e) { + log.error("Failed deleting [" + targetDir.getAbsolutePath() + "]", e); + } + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public String getRootFolder() { + return rootFolder; + } + + public void setRootFolder(String rootFolder) { + this.rootFolder = rootFolder; + } + + public SwaggerParseResult getParseResult() { + return parseResult; + } + + public GenerationCallback getCallback() { + return callback; + } + + public void setCallback(GenerationCallback callback) { + this.callback = callback; + } + + public void callback(GenerationResult generationResult) { + if (callback != null) + callback.event(generationResult); + } + + public List getExecutionPlan() { + return executionPlan; + } + + public void setExecutionPlan(List executionPlan) { + this.executionPlan = executionPlan; + } + + public String getApiTitleConverted() { + return apiTitleConverted; + } + + public void setApiTitleConverted(String apiTitleConverted) { + this.apiTitleConverted = apiTitleConverted; + } + + public String getApiVersionConverted() { + return apiVersionConverted; + } + + public void setApiVersionConverted(String apiVersionConverted) { + this.apiVersionConverted = apiVersionConverted; + } + + public String getApiPackage() { + return apiPackage; + } + + public void setApiPackage(String apiPackage) { + this.apiPackage = apiPackage; + } + + public String getModelPackage() { + return modelPackage; + } + + public void setModelPackage(String modelPackage) { + this.modelPackage = modelPackage; + } + + public File getTargetDir() { + return targetDir; + } + +} diff --git a/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/CompilationUnit.java b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/CompilationUnit.java new file mode 100644 index 00000000..296fe398 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/CompilationUnit.java @@ -0,0 +1,121 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-design + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.design.openapi.utils; + +import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.util.StringTokenizer; + +public class CompilationUnit implements ICompilationUnit { + + public static final int BUFFER_SIZE = 8192; + private final String className; + private final String sourceFile; + private final String ignoredPart; + + private static final Logger log = LoggerFactory.getLogger(CompilationUnit.class); + + public CompilationUnit(String sourceFile, String className, String ignoredPart) { + this.className = className; + this.sourceFile = sourceFile; + this.ignoredPart = ignoredPart; + } + + @Override + public char[] getFileName() { + int i = sourceFile.indexOf(ignoredPart); + String result = sourceFile; + if (i >= 0) { + result = result.substring(i + ignoredPart.length()); + } + return result.toCharArray(); + } + + @Override + public char[] getContents() { + char[] result = null; + try (FileInputStream is = new FileInputStream(sourceFile); + InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8); + Reader reader = new BufferedReader(isr)) { + char[] chars = new char[BUFFER_SIZE]; + StringBuilder source = new StringBuilder(); + int count; + while ((count = reader.read(chars, 0, chars.length)) > 0) { + source.append(chars, 0, count); + } + result = new char[source.length()]; + source.getChars(0, result.length, result, 0); + } catch (IOException e) { + log.error("Failed to get source file {} contents", sourceFile, e); + } + return result; + } + + @Override + public char[] getMainTypeName() { + int dot = className.lastIndexOf('.'); + if (dot > 0) { + return className.substring(dot + 1).toCharArray(); + } + return className.toCharArray(); + } + + @Override + public char[][] getPackageName() { + StringTokenizer st = new StringTokenizer(className, "."); + char[][] result = new char[st.countTokens() - 1][]; + for (int i = 0; i < result.length; i++) { + String token = st.nextToken(); + result[i] = token.toCharArray(); + } + return result; + } + + public static ICompilationUnit build(Path fullPath, String containingDir) { + Path name = fullPath.getFileName(); + String directory = fullPath.toString(); + int i = directory.indexOf(containingDir); + if (i != -1) { + String packageDir = directory + .substring(i + containingDir.length()) + .replace(name.toString(), "").replace('\\', '/'); + String className = name.toString().replaceAll(".java$", ""); + if (!packageDir.endsWith("/")) { + packageDir = packageDir + "/"; + } + if (packageDir.startsWith("/")) { + packageDir = packageDir.substring(1); + } + return new CompilationUnit(fullPath.toString(), packageDir.replaceAll("/", ".") + className, containingDir); + } + return null; + } +} diff --git a/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/CompilerRequestor.java b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/CompilerRequestor.java new file mode 100644 index 00000000..662a8e84 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/CompilerRequestor.java @@ -0,0 +1,115 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-design + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.design.openapi.utils; + +import com.google.common.base.Joiner; +import org.eclipse.jdt.core.compiler.IProblem; +import org.eclipse.jdt.internal.compiler.ClassFile; +import org.eclipse.jdt.internal.compiler.CompilationResult; +import org.eclipse.jdt.internal.compiler.ICompilerRequestor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class CompilerRequestor implements ICompilerRequestor { + private static final Logger log = LoggerFactory.getLogger(CompilerRequestor.class); + + private final Map> problemList = new HashMap<>(); + + private final String outputDir; + + public CompilerRequestor(String outputDir) { + this.outputDir = outputDir; + } + + @Override + public void acceptResult(CompilationResult result) { + if (result.hasProblems()) { + IProblem[] problems = result.getProblems(); + for (IProblem problem : problems) { + if (problem.isError()) { + String fileName = + new String(problem.getOriginatingFileName()); + List errors = problemList.getOrDefault(fileName, new ArrayList<>()); + errors.add(String.format("%s %d: %s", fileName, problem.getSourceLineNumber(), problem.getMessage())); + problemList.put(fileName, errors); + } + } + } + if (problemList.isEmpty()) { + createOutDirIfNotExist(this.outputDir); + ClassFile[] classFiles = result.getClassFiles(); + for (ClassFile classFile : classFiles) { + char[][] compoundName = + classFile.getCompoundName(); + StringBuilder classFileName = new StringBuilder(outputDir).append('/'); + for (int j = 0; j < compoundName.length; j++) { + if (j > 0) { + classFileName.append('/'); + } + classFileName.append(compoundName[j]); + if (j == compoundName.length - 2) { + createOutDirIfNotExist(classFileName.toString()); + } + } + + byte[] bytes = classFile.getBytes(); + classFileName.append(".class"); + try (FileOutputStream classStream = new FileOutputStream(classFileName.toString()); + BufferedOutputStream bos = new BufferedOutputStream(classStream)) { + bos.write(bytes); + } catch (IOException e) { + log.error("Error writing classfile {}", classFileName, e); + } + } + } else { + problemList.forEach((file, errors) -> log.error("Error compiling {}:\n {}", file, Joiner.on("\n\t").join(errors))); + } + } + + private void createOutDirIfNotExist(String directory) { + File f = new File(directory); + if (! f.exists()) { + if (! f.mkdirs()) { + throw new RuntimeException("Cannot create output directory " + directory); + } + } else if (! f.isDirectory()) { + throw new RuntimeException("File " + directory + " is not directory"); + } + } + + public Map> getProblemList() { + return problemList; + } +} diff --git a/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/INameEnvironmentImpl.java b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/INameEnvironmentImpl.java new file mode 100644 index 00000000..df9ecdc8 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-design/src/main/java/ru/entaxy/platform/core/support/design/openapi/utils/INameEnvironmentImpl.java @@ -0,0 +1,155 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-design + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.design.openapi.utils; + +import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; +import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; +import org.eclipse.jdt.internal.compiler.env.INameEnvironment; +import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +public class INameEnvironmentImpl implements INameEnvironment { + private static final Logger log = LoggerFactory.getLogger(INameEnvironmentImpl.class); + private final ClassLoader classLoader; + + public INameEnvironmentImpl(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + @Override + public NameEnvironmentAnswer findType(char[][] compoundTypeName) { + StringBuilder result = new StringBuilder(); + for(int i = 0; i < compoundTypeName.length; i++) { + if (i > 0) { + result.append("."); + } + result.append(compoundTypeName[i]); + } + String typeName = result.toString(); + log.debug("Searching for any package type {}", typeName); + return findType(typeName); + } + + @Override + public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) { + StringBuilder buffer = new StringBuilder(); + int i=0; + for (; i < packageName.length; i++) { + if (i > 0) { + buffer.append('.'); + } + buffer.append(packageName[i]); + } + if (i > 0) { + buffer.append('.'); + } + buffer.append(typeName); + String result = buffer.toString(); + log.debug("Searching for type {} in package {}", new String(typeName), result); + return findType(result); + } + + private NameEnvironmentAnswer findType(String className) { + String resourceName = className.replace('.', '/') + ".class"; + + try (InputStream is = classLoader.getResourceAsStream(resourceName)) { + if (is != null) { + byte[] classBytes; + byte[] buf = new byte[8192]; + ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length); + int count; + while ((count = is.read(buf, 0, buf.length)) > 0) { + baos.write(buf, 0, count); + } + baos.flush(); + classBytes = baos.toByteArray(); + char[] fileName = className.toCharArray(); + ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true); + log.debug("Found type {}", className); + return new NameEnvironmentAnswer(classFileReader, null); + } else { + log.error("Class {} not found ", className); + } + } catch (IOException | ClassFormatException e) { + log.error("Failed to get class {}", className, e); + } + return null; + } + + private boolean isPackage(String resource) { + boolean result = false; + String resourceName = resource.replace('.', '/') + ".class"; + try (InputStream is = classLoader.getResourceAsStream(resourceName)) { + result = is == null; + } catch (IOException e) { + result = false; + } + log.debug("isPackage({}) result: {}", resource, result); + return result; + } + + @Override + public boolean isPackage(char[][] parentPackageName, char[] packageName) { + StringBuilder result = new StringBuilder(); + //fast hack: package are seldom start from uppercase + String lp = new String(packageName); + if (lp.matches("^[A-Z].*?") || lp.contains("$")) { + log.debug("Skipping package check for resource {}", packageName); + return false; + } + int i = 0; + if (parentPackageName != null) { + for (; i < parentPackageName.length; i++) { + if (i > 0) { + result.append('.'); + } + result.append(parentPackageName[i]); + } + } + + if (Character.isUpperCase(packageName[0])) { + if (!isPackage(result.toString())) { + return false; + } + } + if (i > 0) { + result.append('.'); + } + result.append(packageName); + + return isPackage(result.toString()); + } + + @Override + public void cleanup() { + + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/LICENSE.txt b/platform/runtime/core/core-support/core-support-runtime-legacy/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/pom.xml b/platform/runtime/core/core-support/core-support-runtime-legacy/pom.xml new file mode 100644 index 00000000..098f685e --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/pom.xml @@ -0,0 +1,166 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + core-support + 1.10.0 + + core-support-runtime-legacy + bundle + ENTAXY :: PLATFORM :: CORE :: SUPPORT :: RUNTIME LEGACY + ENTAXY :: PLATFORM :: CORE :: SUPPORT :: RUNTIME LEGACY + + + + ru.entaxy.esb.system.common.aggregation, + ru.entaxy.esb.system.common.aggregation.hazelcast, + ru.entaxy.esb.system.common.aggregation.repo, + ru.entaxy.esb.system.common.exception, + ru.entaxy.esb.system.common.interceptor, + ru.entaxy.esb.system.common.util, + ru.entaxy.esb.system.common.validator + + + com.google.gson, + org.osgi.service.blueprint.container, + javax.xml.soap*;version="[1.3,2)", + javax.jws.*;version="[2.0.0,3.0.0)", + javax.jws.soap.*;version="[2.0.0,3.0.0)", + javax.xml.ws.*;version="[2.2.0,3.0.0)", + !com.sun.xml.*, + javax.xml.bind;version="[2,3)", + javax.xml.bind.annotation;version="[2,3)", + javax.persistence;version="[2,3)", + org.hibernate, + org.hibernate.cfg, + org.hibernate.service, + org.hibernate.jpa, + org.hibernate.proxy, + org.apache.ignite, + org.apache.ignite.internal.processors.cluster, + org.apache.ignite.internal.processors.marshaller, + org.apache.ignite.internal.util.lang.gridfunc, + org.apache.ignite.spi.discovery.tcp.internal, + org.apache.ignite.transactions, + org.apache.ignite.internal.*, + javassist.util.proxy, + org.apache.commons.lang3, + * + + + + + + + com.google.code.gson + gson + + + xerces + xercesImpl + ${xerces.version} + + + xml-apis + xml-apis + + + + + org.osgi + org.osgi.core + ${osgi.version} + + + commons-collections + commons-collections + + + commons-lang + commons-lang + ${commons-lang.version} + + + org.apache.aries.blueprint + org.apache.aries.blueprint.cm + + + org.osgi + osgi.core + provided + + + org.eclipse.persistence + javax.persistence + ${jpa.version} + + + org.hibernate + hibernate-core + ${hibernate.version} + + + javax.transaction + javax.transaction-api + ${javax.transaction.version} + + + javax.interceptor + javax.interceptor-api + ${javax.interceptor.version} + + + org.apache.cxf + cxf-rt-transports-http + + + org.apache.cxf + cxf-rt-transports-http-jetty + + + org.apache.commons + commons-lang3 + ${commons-lang3.version} + + + org.apache.ignite + ignite-core + ${ignite.version} + + + + org.apache.ignite + ignite-jcl + ${ignite.version} + + + + com.hazelcast + hazelcast + ${hazelcast.version} + + + org.apache.camel + camel-core + + + org.apache.camel + camel-jms + + + org.apache.camel + camel-sql + + + org.apache.camel + camel-cxf + + + org.apache.camel + camel-base + ${camel.version}-ENTAXY + + + + + diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/HeaderMergeAggregatorImpl.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/HeaderMergeAggregatorImpl.java new file mode 100644 index 00000000..8560054e --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/HeaderMergeAggregatorImpl.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation; + +import java.util.Map; +import java.util.stream.Collectors; + +import org.apache.camel.AggregationStrategy; +import org.apache.camel.Exchange; + +public class HeaderMergeAggregatorImpl implements AggregationStrategy { + + @Override + public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { + if (oldExchange != null && newExchange != null) { + Map oldHeaders = oldExchange.getIn().getHeaders(); + Map newHeaders = newExchange.getIn().getHeaders(); + + oldHeaders = oldHeaders.entrySet().stream() + .filter(e -> !newHeaders.containsKey(e.getKey())) + .collect(Collectors.toMap(e->e.getKey(), e->e.getValue())); + newExchange.getIn().getHeaders().putAll(oldHeaders); + } + return newExchange; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/JdbcCamelCodec.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/JdbcCamelCodec.java new file mode 100644 index 00000000..8b6d6693 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/JdbcCamelCodec.java @@ -0,0 +1,122 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime-legacy + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation; + +import java.util.ArrayList; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OutputStream; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.Exchange; +import org.apache.camel.ExtendedExchange; +import org.apache.camel.processor.aggregate.jdbc.ClassLoadingAwareObjectInputStream; +import org.apache.camel.support.DefaultExchange; +import org.apache.camel.support.DefaultExchangeHolder; +import org.apache.camel.util.IOHelper; + +/** + * Adapted from HawtDBCamelCodec + */ +public class JdbcCamelCodec { + + public byte[] marshallExchange(CamelContext camelContext, Exchange exchange, boolean allowSerializedHeaders) throws IOException { + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + marshallExchange(camelContext, exchange, allowSerializedHeaders, bytesOut); + return bytesOut.toByteArray(); + } + + public void marshallExchange(CamelContext camelContext, Exchange exchange, boolean allowSerializedHeaders, OutputStream outputStream) throws IOException { + // use DefaultExchangeHolder to marshal to a serialized object + DefaultExchangeHolder pe = DefaultExchangeHolder.marshal(exchange, false, allowSerializedHeaders); + // add the aggregated size and timeout property as the only properties we want to retain + DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_SIZE, exchange.getProperty(Exchange.AGGREGATED_SIZE, Integer.class)); + DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_TIMEOUT, exchange.getProperty(Exchange.AGGREGATED_TIMEOUT, Long.class)); + // add the aggregated completed by property to retain + DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_COMPLETED_BY, exchange.getProperty(Exchange.AGGREGATED_COMPLETED_BY, String.class)); + // add the aggregated correlation key property to retain + DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_CORRELATION_KEY, exchange.getProperty(Exchange.AGGREGATED_CORRELATION_KEY, String.class)); + DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_CORRELATION_KEY, exchange.getProperty(Exchange.AGGREGATED_CORRELATION_KEY, String.class)); + // and a guard property if using the flexible toolbox aggregator + DefaultExchangeHolder.addProperty(pe, Exchange.AGGREGATED_COLLECTION_GUARD, exchange.getProperty(Exchange.AGGREGATED_COLLECTION_GUARD, String.class)); + // @ENTAXY-FIX GROUPED_EXCHANGE isn't marshaling + if (exchange.getProperty(Exchange.GROUPED_EXCHANGE) != null && exchange.getProperty(Exchange.GROUPED_EXCHANGE) instanceof ArrayList) { + DefaultExchangeHolder.addProperty(pe, Exchange.GROUPED_EXCHANGE, exchange.getProperty(Exchange.GROUPED_EXCHANGE, ArrayList.class)); + } else if (exchange.getProperty(Exchange.GROUPED_EXCHANGE) != null && exchange.getProperty(Exchange.GROUPED_EXCHANGE) instanceof StringBuffer) { + DefaultExchangeHolder.addProperty(pe, Exchange.GROUPED_EXCHANGE, exchange.getProperty(Exchange.GROUPED_EXCHANGE, StringBuffer.class)); + } + // persist the from endpoint as well + if (exchange.getFromEndpoint() != null) { + DefaultExchangeHolder.addProperty(pe, "CamelAggregatedFromEndpoint", exchange.getFromEndpoint().getEndpointUri()); + } + encode(pe, outputStream); + } + + public Exchange unmarshallExchange(CamelContext camelContext, byte[] buffer) throws IOException, ClassNotFoundException { + return unmarshallExchange(camelContext, new ByteArrayInputStream(buffer)); + } + + public Exchange unmarshallExchange(CamelContext camelContext, InputStream inputStream) throws IOException, ClassNotFoundException { + DefaultExchangeHolder pe = decode(camelContext, inputStream); + Exchange answer = new DefaultExchange(camelContext); + DefaultExchangeHolder.unmarshal(answer, pe); + // restore the from endpoint + String fromEndpointUri = (String) answer.removeProperty("CamelAggregatedFromEndpoint"); + if (fromEndpointUri != null) { + Endpoint fromEndpoint = camelContext.hasEndpoint(fromEndpointUri); + if (fromEndpoint != null) { + answer.adapt(ExtendedExchange.class).setFromEndpoint(fromEndpoint); + } + } + return answer; + } + + private void encode(Object object, OutputStream bytesOut) throws IOException { + try (ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut)) { + objectOut.writeObject(object); + } + } + + private DefaultExchangeHolder decode(CamelContext camelContext, InputStream bytesIn) throws IOException, ClassNotFoundException { + ObjectInputStream objectIn = null; + Object obj = null; + try { + objectIn = new ClassLoadingAwareObjectInputStream(camelContext, bytesIn); + obj = objectIn.readObject(); + } finally { + IOHelper.close(objectIn); + } + + return (DefaultExchangeHolder)obj; + } + +} + diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/TimeoutAwareAggregationStrategyImpl.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/TimeoutAwareAggregationStrategyImpl.java new file mode 100644 index 00000000..603f5382 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/TimeoutAwareAggregationStrategyImpl.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation; + +import org.apache.camel.AggregationStrategy; +import org.apache.camel.Exchange; + +public class TimeoutAwareAggregationStrategyImpl implements AggregationStrategy { + + private static final String ACK_MESSAGE_HEADER = "NTX_AckMessage"; + + private final String nameHeaderAcknowledge; + + public TimeoutAwareAggregationStrategyImpl(String nameHeaderAcknowledge) { + this.nameHeaderAcknowledge = nameHeaderAcknowledge; + } + + @Override + public Exchange aggregate(Exchange oldExchange, Exchange newExchange) { + if (oldExchange == null) { + return newExchange; + } else { + oldExchange.getMessage().setHeader(nameHeaderAcknowledge, checkOnCorrectPair(oldExchange, newExchange)); + return oldExchange; + } + } + + private boolean checkOnCorrectPair(Exchange oldExchange, Exchange newExchange) { + return (oldExchange != null && oldExchange.getMessage().getHeader(ACK_MESSAGE_HEADER) == null && + (newExchange == null || newExchange.getMessage().getHeader(ACK_MESSAGE_HEADER) == null)); + } + + @Override + public void timeout(Exchange oldExchange, int index, int total, long timeout) { + oldExchange.getMessage().setHeader(nameHeaderAcknowledge, + (oldExchange.getMessage().getHeader(ACK_MESSAGE_HEADER) == null)); + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/hazelcast/DisconnectedMembershipListener.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/hazelcast/DisconnectedMembershipListener.java new file mode 100644 index 00000000..aecaac6e --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/hazelcast/DisconnectedMembershipListener.java @@ -0,0 +1,74 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation.hazelcast; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.MemberAttributeEvent; +import com.hazelcast.core.MembershipEvent; +import com.hazelcast.core.MembershipListener; +import org.apache.camel.CamelContext; +import org.apache.camel.processor.aggregate.AggregateProcessorSetter; +import org.apache.camel.processor.aggregate.EntaxyAggregateProcessor; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class DisconnectedMembershipListener implements MembershipListener, AggregateProcessorSetter { + + protected static final Logger log = LoggerFactory.getLogger(DisconnectedMembershipListener.class); + private CamelContext camelContext; + private EntaxyAggregateProcessor aggregateProcessor; + + @Override + public void memberAdded(MembershipEvent membershipEvent) { + } + + @Override + public void memberRemoved(MembershipEvent membershipEvent) { + try { + aggregateProcessor.recoverCompletedMessageFromAggregationRepository(camelContext); + aggregateProcessor.restoreTimeoutMapFromAggregationRepository(); + } catch (Exception e) { + log.error("Can't restore Timeout from Aggregator. Please restart bundle.", e); + } + } + + @Override + public void memberAttributeChanged(MemberAttributeEvent memberAttributeEvent) { + } + + @Override + public void setAggregateProcessor(EntaxyAggregateProcessor aggregateProcessor) { + this.aggregateProcessor = aggregateProcessor; + } + + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + hazelcastInstance.getCluster().addMembershipListener(this); + } + + public void setCamelContext(CamelContext camelContext) { + this.camelContext = camelContext; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/IgniteAggregationRepository.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/IgniteAggregationRepository.java new file mode 100644 index 00000000..d3df6bb3 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/IgniteAggregationRepository.java @@ -0,0 +1,380 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation.repo; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.processor.aggregate.jdbc.DefaultJdbcOptimisticLockingExceptionMapper; +import org.apache.camel.processor.aggregate.jdbc.JdbcOptimisticLockingExceptionMapper; +import org.apache.camel.spi.OptimisticLockingAggregationRepository; +import org.apache.camel.spi.RecoverableAggregationRepository; +import org.apache.camel.support.service.ServiceSupport; +import org.apache.camel.util.ObjectHelper; +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.IgniteTransactions; +import org.apache.ignite.cache.CacheAtomicityMode; +import org.apache.ignite.cache.CacheMode; +import org.apache.ignite.cache.CacheRebalanceMode; +import org.apache.ignite.cache.query.ScanQuery; +import org.apache.ignite.configuration.CacheConfiguration; +import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; +import org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder; +import org.apache.ignite.transactions.Transaction; +import org.jetbrains.annotations.NotNull; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.EmptyResultDataAccessException; +import ru.entaxy.esb.system.common.aggregation.JdbcCamelCodec; + +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.TimeUnit; + + +public class IgniteAggregationRepository extends ServiceSupport implements RecoverableAggregationRepository, OptimisticLockingAggregationRepository { + + private static final Logger LOG = LoggerFactory.getLogger(IgniteAggregationRepository.class); + public static final String AGGREGATION = "aggregation"; + public static final String AGGREGATION_COMPLETED = "aggregationCompleted"; + public static final int MAX_ATTEMPT_COUNT = 3; + + private JdbcOptimisticLockingExceptionMapper jdbcOptimisticLockingExceptionMapper = new DefaultJdbcOptimisticLockingExceptionMapper(); + private boolean returnOldExchange; + private final JdbcCamelCodec codec = new JdbcCamelCodec(); + private long recoveryInterval = 5000; + private boolean useRecovery = true; + private int maximumRedeliveries; + private String deadLetterUri; + private boolean allowSerializedHeaders; + private int backups = 2; + + private Ignite ignite; + private IgniteTransactions transactions; + + private IgniteCache aggregationCache; + private CacheConfiguration aggregationCfg; + + private IgniteCache aggregationCompleted; + private CacheConfiguration aggregationCompletedCfg; + + private BundleContext bundleContext; + + /** + * Creates an ignite aggregation repository + */ + public IgniteAggregationRepository() { + } + + /** + * Creates an ignite aggregation repository with the two mandatory parameters + */ + public IgniteAggregationRepository(BundleContext bundleContext, Ignite ignite) { + this.setBundleContext(bundleContext); + this.setIgnite(ignite); + } + + @Override + public Exchange add(final CamelContext camelContext, final String correlationId, + final Exchange oldExchange, final Exchange newExchange) throws OptimisticLockingException { + + try { + return add(camelContext, correlationId, newExchange); + } catch (Exception e) { + if (jdbcOptimisticLockingExceptionMapper != null && jdbcOptimisticLockingExceptionMapper.isOptimisticLocking(e)) { + throw new OptimisticLockingException(); + } else { + throw RuntimeCamelException.wrapRuntimeCamelException(e); + } + } + } + + @Override + public Exchange add(final CamelContext camelContext, final String correlationId, final Exchange exchange) { + Exchange result = null; + final String key = correlationId; + + try { + LOG.debug("Adding exchange with key: [{}]", key); + + boolean present = aggregationCache.get(key) != null; + + // Recover existing exchange with that ID + if (isReturnOldExchange() && present) { + result = get(key, camelContext); + } + + final byte[] data = codec.marshallExchange(camelContext, exchange, allowSerializedHeaders); + try (Transaction tx = transactions.txStart()) { + aggregationCache.put(key, data); + tx.commit(); + } + + } catch (Exception e) { + throw new RuntimeException("Error adding with key " + key, e); + } + + return result; + } + + public Exchange insert(final CamelContext camelContext, final String correlationId, final Exchange exchange) throws IOException { + Exchange result = null; + LOG.debug("Adding exchange with key: [{}]", correlationId); + + final byte[] data = codec.marshallExchange(camelContext, exchange, allowSerializedHeaders); + aggregationCompleted.put(correlationId, data); + + return result; + } + + @Override + public Exchange get(final CamelContext camelContext, final String correlationId) { + Exchange result = get(correlationId, camelContext); + + LOG.debug("Getting key [{}] -> {}", correlationId, result); + + return result; + } + + private Exchange get(final String key, final CamelContext camelContext) { + try { + final byte[] data = aggregationCache.get(key); + return codec.unmarshallExchange(camelContext, data); + } catch (EmptyResultDataAccessException | NullPointerException ex) { + return null; + } catch (IOException | ClassNotFoundException e) { + throw new RuntimeException(e); + } + } + + @Override + public void remove(final CamelContext camelContext, final String correlationId, final Exchange exchange) { + final String confirmKey = exchange.getExchangeId(); + try (Transaction tx = transactions.txStart()) { + insert(camelContext, confirmKey, exchange); + if (!aggregationCache.remove(correlationId)) { + throw new RuntimeException("Error removing key " + correlationId + " from repository " + AGGREGATION); + } + tx.commit(); + } catch (Exception exception) { + throw new RuntimeException("Error removing key " + correlationId + " from repository " + AGGREGATION, exception); + } + } + + @Override + public void confirm(final CamelContext camelContext, final String exchangeId) { + confirm(camelContext, exchangeId, 0); + } + + private void confirm(final CamelContext camelContext, final String exchangeId, int attemptCount) { + if (attemptCount <= MAX_ATTEMPT_COUNT) { + try (Transaction tx = transactions.txStart()) { + aggregationCompleted.remove(exchangeId); + tx.commit(); + } catch (Exception exception) { + confirm(camelContext, exchangeId, ++attemptCount); + } + } + } + + @Override + public Set getKeys() { + Set keys = new HashSet<>(); + aggregationCache.query(new ScanQuery<>(null)).forEach(entry -> keys.add((String) entry.getKey())); + return keys; + } + + @Override + public Set scan(CamelContext camelContext) { + Set keys = new HashSet<>(); + aggregationCompleted.query(new ScanQuery<>(null)).forEach(entry -> keys.add((String) entry.getKey())); + return keys; + } + + @Override + public Exchange recover(CamelContext camelContext, String exchangeId) { + final byte[] data = aggregationCompleted.get(exchangeId); + Exchange answer = null; + try { + answer = codec.unmarshallExchange(camelContext, data); + } catch (IOException | ClassNotFoundException e) { + LOG.error("Exception in recovering exchangeId {}", exchangeId, e); + } + + LOG.debug("Recovering exchangeId [{}] -> {}", exchangeId, answer); + + return answer; + } + + /** + * If recovery is enabled then a background task is run every x'th time to scan for failed exchanges to recover + * and resubmit. By default this interval is 5000 millis. + * + * @param interval the interval + * @param timeUnit the time unit + */ + public void setRecoveryInterval(long interval, TimeUnit timeUnit) { + this.recoveryInterval = timeUnit.toMillis(interval); + } + + public void setRecoveryInterval(long interval) { + this.recoveryInterval = interval; + } + + public long getRecoveryIntervalInMillis() { + return recoveryInterval; + } + + public boolean isUseRecovery() { + return useRecovery; + } + + /** + * @param useRecovery Whether or not recovery is enabled. This option is by default true. When enabled the Camel + * Aggregator automatic recover failed aggregated exchange and have them resubmittedd + */ + public void setUseRecovery(boolean useRecovery) { + this.useRecovery = useRecovery; + } + + public int getMaximumRedeliveries() { + return maximumRedeliveries; + } + + public void setMaximumRedeliveries(int maximumRedeliveries) { + this.maximumRedeliveries = maximumRedeliveries; + } + + public String getDeadLetterUri() { + return deadLetterUri; + } + + /** + * @param deadLetterUri An endpoint uri for a Dead Letter Channel where exhausted recovered Exchanges will be + * moved. If this option is used then the maximumRedeliveries option must also be provided. + * Important note : if the deadletter route throws an exception, it will be send again to DLQ + * until it succeed ! + */ + public void setDeadLetterUri(String deadLetterUri) { + this.deadLetterUri = deadLetterUri; + } + + public boolean isReturnOldExchange() { + return returnOldExchange; + } + + /** + * @param returnOldExchange Whether the get operation should return the old existing Exchange if any existed. + * By default this option is false to optimize as we do not need the old exchange when + * aggregating + */ + public void setReturnOldExchange(boolean returnOldExchange) { + this.returnOldExchange = returnOldExchange; + } + + public boolean isAllowSerializedHeaders() { + return allowSerializedHeaders; + } + + public void setAllowSerializedHeaders(boolean allowSerializedHeaders) { + this.allowSerializedHeaders = allowSerializedHeaders; + } + + public JdbcOptimisticLockingExceptionMapper getJdbcOptimisticLockingExceptionMapper() { + return jdbcOptimisticLockingExceptionMapper; + } + + public void setJdbcOptimisticLockingExceptionMapper(JdbcOptimisticLockingExceptionMapper jdbcOptimisticLockingExceptionMapper) { + this.jdbcOptimisticLockingExceptionMapper = jdbcOptimisticLockingExceptionMapper; + } + + @Override + protected void doStart() throws Exception { + ObjectHelper.notNull(bundleContext, "BundleContext"); + ObjectHelper.notNull(ignite, "Ignite"); + + settingsIgnite(); + + // log number of existing exchanges + int current = getKeys().size(); + int completed = scan(null).size(); + + if (current > 0) { + LOG.info("On startup there are " + current + " aggregate exchanges (not completed) in repository: " + AGGREGATION); + } else { + LOG.info("On startup there are no existing aggregate exchanges (not completed) in repository: {}", AGGREGATION); + } + if (completed > 0) { + LOG.warn("On startup there are " + completed + " completed exchanges to be recovered in repository: " + AGGREGATION_COMPLETED); + } else { + LOG.info("On startup there are no completed exchanges to be recovered in repository: {}", AGGREGATION_COMPLETED); + } + } + + private void settingsIgnite() { + aggregationCfg = getCacheConfiguration(AGGREGATION); + aggregationCompletedCfg = getCacheConfiguration(AGGREGATION_COMPLETED); + + transactions = ignite.transactions(); + + aggregationCache = ignite.getOrCreateCache(aggregationCfg); + aggregationCompleted = ignite.getOrCreateCache(aggregationCompletedCfg); + } + + @NotNull + private CacheConfiguration getCacheConfiguration(String cacheName) { + CacheConfiguration cacheCfg = new CacheConfiguration<>(); + cacheCfg.setName(cacheName); + cacheCfg.setRebalanceMode(CacheRebalanceMode.SYNC); + cacheCfg.setCacheMode(CacheMode.REPLICATED); + cacheCfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL); + cacheCfg.setBackups(backups); + return cacheCfg; + } + + @NotNull + private TcpDiscoverySpi getTcpDiscoverySpi() { + TcpDiscoverySpi spi = new TcpDiscoverySpi(); + spi.setIpFinder(new TcpDiscoveryMulticastIpFinder()); + return spi; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + public void setBackups(int backups) { + this.backups = backups; + } + + public void setIgnite(Ignite ignite) { + this.ignite = ignite; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/JdbcAggregationRepository.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/JdbcAggregationRepository.java new file mode 100644 index 00000000..7e465a7a --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/JdbcAggregationRepository.java @@ -0,0 +1,655 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation.repo; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.RuntimeCamelException; +import org.apache.camel.processor.aggregate.jdbc.DefaultJdbcOptimisticLockingExceptionMapper; +import org.apache.camel.processor.aggregate.jdbc.JdbcOptimisticLockingExceptionMapper; +import org.apache.camel.spi.OptimisticLockingAggregationRepository; +import org.apache.camel.spi.RecoverableAggregationRepository; +import org.apache.camel.support.service.ServiceSupport; +import org.apache.camel.util.ObjectHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.Constants; +import org.springframework.dao.EmptyResultDataAccessException; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.core.support.AbstractLobCreatingPreparedStatementCallback; +import org.springframework.jdbc.support.lob.DefaultLobHandler; +import org.springframework.jdbc.support.lob.LobCreator; +import org.springframework.jdbc.support.lob.LobHandler; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.DefaultTransactionDefinition; +import org.springframework.transaction.support.TransactionCallbackWithoutResult; +import org.springframework.transaction.support.TransactionTemplate; +import ru.entaxy.esb.system.common.aggregation.JdbcCamelCodec; + +import javax.sql.DataSource; +import java.io.IOException; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Types; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * JDBC based {@link org.apache.camel.spi.AggregationRepository} JdbcAggregationRepository will only preserve any + * Serializable compatible data types. If a data type is not such a type its dropped and a WARN is logged. And it only + * persists the Message body and the Message headers. The Exchange properties are not persisted. + */ +public class JdbcAggregationRepository extends ServiceSupport + implements RecoverableAggregationRepository, OptimisticLockingAggregationRepository { + + protected static final String EXCHANGE = "exchange"; + protected static final String ID = "id"; + protected static final String BODY = "body"; + + // optimistic locking: version identifier needed to avoid the lost update problem + private static final String VERSION = "version"; + private static final String VERSION_PROPERTY = "CamelOptimisticLockVersion"; + + private static final Logger LOG = LoggerFactory.getLogger(JdbcAggregationRepository.class); + private static final Constants PROPAGATION_CONSTANTS = new Constants(TransactionDefinition.class); + + private JdbcOptimisticLockingExceptionMapper jdbcOptimisticLockingExceptionMapper + = new DefaultJdbcOptimisticLockingExceptionMapper(); + private PlatformTransactionManager transactionManager; + private DataSource dataSource; + private TransactionTemplate transactionTemplate; + private TransactionTemplate transactionTemplateReadOnly; + private int propagationBehavior = TransactionDefinition.PROPAGATION_REQUIRED; + private JdbcTemplate jdbcTemplate; + private LobHandler lobHandler = new DefaultLobHandler(); + private String repositoryName; + private boolean returnOldExchange; + private JdbcCamelCodec codec = new JdbcCamelCodec(); + private long recoveryInterval = 5000; + private boolean useRecovery = true; + private int maximumRedeliveries; + private String deadLetterUri; + private List headersToStoreAsText; + private boolean storeBodyAsText; + private boolean allowSerializedHeaders; + + /** + * Creates an aggregation repository + */ + public JdbcAggregationRepository() { + } + + /** + * Creates an aggregation repository with the three mandatory parameters + */ + public JdbcAggregationRepository(PlatformTransactionManager transactionManager, String repositoryName, + DataSource dataSource) { + this.setRepositoryName(repositoryName); + this.setTransactionManager(transactionManager); + this.setDataSource(dataSource); + } + + /** + * Sets the name of the repository + */ + public final void setRepositoryName(String repositoryName) { + this.repositoryName = repositoryName; + } + + public final void setTransactionManager(PlatformTransactionManager transactionManager) { + this.transactionManager = transactionManager; + } + + /** + * Sets the DataSource to use for accessing the database + */ + public void setDataSource(DataSource dataSource) { + this.dataSource = dataSource; + + jdbcTemplate = new JdbcTemplate(dataSource); + } + + @Override + public Exchange add( + final CamelContext camelContext, final String correlationId, + final Exchange oldExchange, final Exchange newExchange) + throws OptimisticLockingException { + + try { + return add(camelContext, correlationId, newExchange); + } catch (Exception e) { + if (jdbcOptimisticLockingExceptionMapper != null && jdbcOptimisticLockingExceptionMapper.isOptimisticLocking(e)) { + throw new OptimisticLockingException(); + } else { + throw RuntimeCamelException.wrapRuntimeCamelException(e); + } + } + } + + @Override + public Exchange add(final CamelContext camelContext, final String correlationId, final Exchange exchange) { + return transactionTemplate.execute(status -> { + Exchange result = null; + final String key = correlationId; + + try { + LOG.debug("Adding exchange with key {}", key); + + boolean present = jdbcTemplate.queryForObject( + "SELECT COUNT(1) FROM " + getRepositoryName() + " WHERE " + ID + " = ?", Integer.class, key) != 0; + + // Recover existing exchange with that ID + if (isReturnOldExchange() && present) { + result = get(key, getRepositoryName(), camelContext); + } + + if (present) { + long version = exchange.getProperty(VERSION_PROPERTY, Long.class); + LOG.debug("Updating record with key {} and version {}", key, version); + update(camelContext, correlationId, exchange, getRepositoryName(), version); + } else { + LOG.debug("Inserting record with key {}", key); + insert(camelContext, correlationId, exchange, getRepositoryName(), 1L); + } + + } catch (Exception e) { + throw new RuntimeException("Error adding to repository " + repositoryName + " with key " + key, e); + } + + return result; + }); + } + + /** + * Updates the current exchange details in the given repository table. + * + * @param camelContext Current CamelContext + * @param key Correlation key + * @param exchange Aggregated exchange + * @param repositoryName Table's name + * @param version Version identifier + */ + protected void update( + final CamelContext camelContext, final String key, final Exchange exchange, String repositoryName, Long version) + throws Exception { + StringBuilder queryBuilder = new StringBuilder() + .append("UPDATE ").append(repositoryName) + .append(" SET ") + .append(EXCHANGE).append(" = ?") + .append(", ") + .append(VERSION).append(" = ?"); + if (storeBodyAsText) { + queryBuilder.append(", ").append(BODY).append(" = ?"); + } + + if (hasHeadersToStoreAsText()) { + for (String headerName : headersToStoreAsText) { + queryBuilder.append(", ").append(headerName).append(" = ?"); + } + } + + queryBuilder.append(" WHERE ") + .append(ID).append(" = ?") + .append(" AND ") + .append(VERSION).append(" = ?"); + + String sql = queryBuilder.toString(); + updateHelper(camelContext, key, exchange, sql, version); + } + + /** + * Inserts a new record into the given repository table. Note: the exchange properties are NOT persisted. + * + * @param camelContext Current CamelContext + * @param correlationId Correlation key + * @param exchange Aggregated exchange to insert + * @param repositoryName Table's name + * @param version Version identifier + */ + protected void insert( + final CamelContext camelContext, final String correlationId, final Exchange exchange, String repositoryName, + Long version) + throws Exception { + // The default totalParameterIndex is 3 for ID, Exchange and version. Depending on logic this will be increased. + int totalParameterIndex = 3; + StringBuilder queryBuilder = new StringBuilder() + .append("INSERT INTO ").append(repositoryName) + .append('(').append(EXCHANGE) + .append(", ").append(ID) + .append(", ").append(VERSION); + + if (storeBodyAsText) { + queryBuilder.append(", ").append(BODY); + totalParameterIndex++; + } + + if (hasHeadersToStoreAsText()) { + for (String headerName : headersToStoreAsText) { + queryBuilder.append(", ").append(headerName); + totalParameterIndex++; + } + } + + queryBuilder.append(") VALUES ("); + + for (int i = 0; i < totalParameterIndex - 1; i++) { + queryBuilder.append("?, "); + } + queryBuilder.append("?)"); + + String sql = queryBuilder.toString(); + + insertHelper(camelContext, correlationId, exchange, sql, version); + } + + protected int insertHelper( + final CamelContext camelContext, final String key, final Exchange exchange, String sql, final Long version) + throws Exception { + final byte[] data = codec.marshallExchange(camelContext, exchange, allowSerializedHeaders); + Integer insertCount = jdbcTemplate.execute(sql, + new AbstractLobCreatingPreparedStatementCallback(getLobHandler()) { + @Override + protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { + int totalParameterIndex = 0; + lobCreator.setBlobAsBytes(ps, ++totalParameterIndex, data); + ps.setString(++totalParameterIndex, key); + ps.setLong(++totalParameterIndex, version); + if (storeBodyAsText) { + ps.setString(++totalParameterIndex, exchange.getIn().getBody(String.class)); + } + if (hasHeadersToStoreAsText()) { + for (String headerName : headersToStoreAsText) { + String headerValue = exchange.getIn().getHeader(headerName, String.class); + ps.setString(++totalParameterIndex, headerValue); + } + } + } + }); + return insertCount == null ? 0 : insertCount; + } + + protected int updateHelper( + final CamelContext camelContext, final String key, final Exchange exchange, String sql, final Long version) + throws Exception { + final byte[] data = codec.marshallExchange(camelContext, exchange, allowSerializedHeaders); + Integer updateCount = jdbcTemplate.execute(sql, + new AbstractLobCreatingPreparedStatementCallback(getLobHandler()) { + @Override + protected void setValues(PreparedStatement ps, LobCreator lobCreator) throws SQLException { + int totalParameterIndex = 0; + lobCreator.setBlobAsBytes(ps, ++totalParameterIndex, data); + ps.setLong(++totalParameterIndex, version + 1); + if (storeBodyAsText) { + ps.setString(++totalParameterIndex, exchange.getIn().getBody(String.class)); + } + if (hasHeadersToStoreAsText()) { + for (String headerName : headersToStoreAsText) { + String headerValue = exchange.getIn().getHeader(headerName, String.class); + ps.setString(++totalParameterIndex, headerValue); + } + } + ps.setString(++totalParameterIndex, key); + ps.setLong(++totalParameterIndex, version); + } + }); + if (updateCount == 1) { + return updateCount; + } else { + // Found stale version while updating record + throw new OptimisticLockingException(); + } + } + + @Override + public Exchange get(final CamelContext camelContext, final String correlationId) { + final String key = correlationId; + Exchange result = get(key, getRepositoryName(), camelContext); + LOG.debug("Getting key {} -> {}", key, result); + return result; + } + + private Exchange get(final String key, final String repositoryName, final CamelContext camelContext) { + return transactionTemplateReadOnly.execute(status -> { + try { + + Map columns = jdbcTemplate.queryForMap( + String.format("SELECT %1$s, %2$s FROM %3$s WHERE %4$s=?", EXCHANGE, VERSION, repositoryName, ID), + new Object[]{key}, new int[]{Types.VARCHAR}); + + byte[] marshalledExchange = (byte[]) columns.get(EXCHANGE); + long version = (long) columns.get(VERSION); + + Exchange result = codec.unmarshallExchange(camelContext, marshalledExchange); + result.setProperty(VERSION_PROPERTY, version); + return result; + + } catch (EmptyResultDataAccessException ex) { + return null; + } catch (IOException ex) { + // Rollback the transaction + throw new RuntimeException("Error getting key " + key + " from repository " + repositoryName, ex); + } catch (ClassNotFoundException ex) { + // Rollback the transaction + throw new RuntimeException(ex); + } + }); + } + + + @Override + public void remove(final CamelContext camelContext, final String correlationId, final Exchange exchange) { + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + protected void doInTransactionWithoutResult(TransactionStatus status) { + final String key = correlationId; + final String confirmKey = exchange.getExchangeId(); + final long version = exchange.getProperty(VERSION_PROPERTY, Long.class); + try { + LOG.debug("Removing key {}", key); + + // добавлена проверка на корректное удаление из таблицы, т к возникала ситуация гонки на узлах. + // один узел уже удалил из completed, а второй в процессе, соответственно ошибки дублирования + // не появляется появляется дубликат в очереди + if (jdbcTemplate.update("DELETE FROM " + getRepositoryName() + " WHERE " + ID + " = ? AND " + VERSION + " = ?", + key, version) == 1) { + insert(camelContext, confirmKey, exchange, getRepositoryNameCompleted(), version); + } else { + throw new RuntimeException("Error removing key " + key + " from repository " + repositoryName); + } + + } catch (Exception e) { + throw new RuntimeException("Error removing key " + key + " from repository " + repositoryName, e); + } + } + }); + } + + @Override + public void confirm(final CamelContext camelContext, final String exchangeId) { + transactionTemplate.execute(new TransactionCallbackWithoutResult() { + protected void doInTransactionWithoutResult(TransactionStatus status) { + LOG.debug("Confirming exchangeId {}", exchangeId); + final String confirmKey = exchangeId; + + jdbcTemplate.update("DELETE FROM " + getRepositoryNameCompleted() + " WHERE " + ID + " = ?", + confirmKey); + + } + }); + } + + @Override + public Set getKeys() { + return getKeys(getRepositoryName()); + } + + @Override + public Set scan(CamelContext camelContext) { + return getKeys(getRepositoryNameCompleted()); + } + + /** + * Returns the keys in the given repository + * + * @param repositoryName The name of the table + * @return Set of keys in the given repository name + */ + protected Set getKeys(final String repositoryName) { + return transactionTemplateReadOnly.execute(status -> { + List keys = jdbcTemplate.query("SELECT " + ID + " FROM " + repositoryName, + (rs, rowNum) -> { + String id = rs.getString(ID); + LOG.trace("getKey {}", id); + return id; + }); + return new LinkedHashSet<>(keys); + }); + } + + @Override + public Exchange recover(CamelContext camelContext, String exchangeId) { + final String key = exchangeId; + Exchange answer = get(key, getRepositoryNameCompleted(), camelContext); + LOG.debug("Recovering exchangeId {} -> {}", key, answer); + return answer; + } + + /** + * If recovery is enabled then a background task is run every x'th time to scan for failed exchanges to recover and + * resubmit. By default this interval is 5000 millis. + */ + @Override + public void setRecoveryInterval(long interval, TimeUnit timeUnit) { + this.recoveryInterval = timeUnit.toMillis(interval); + } + + @Override + public void setRecoveryInterval(long interval) { + this.recoveryInterval = interval; + } + + @Override + public long getRecoveryIntervalInMillis() { + return recoveryInterval; + } + + @Override + public boolean isUseRecovery() { + return useRecovery; + } + + /** + * Whether or not recovery is enabled. This option is by default true. When enabled the Camel Aggregator automatic + * recover failed aggregated exchange and have them resubmitted. + */ + @Override + public void setUseRecovery(boolean useRecovery) { + this.useRecovery = useRecovery; + } + + @Override + public int getMaximumRedeliveries() { + return maximumRedeliveries; + } + + @Override + public void setMaximumRedeliveries(int maximumRedeliveries) { + this.maximumRedeliveries = maximumRedeliveries; + } + + @Override + public String getDeadLetterUri() { + return deadLetterUri; + } + + /** + * An endpoint uri for a Dead Letter Channel where exhausted recovered Exchanges will be moved. If this option is + * used then the maximumRedeliveries option must also be provided. Important note : if the deadletter route throws + * an exception, it will be send again to DLQ until it succeed ! + */ + @Override + public void setDeadLetterUri(String deadLetterUri) { + this.deadLetterUri = deadLetterUri; + } + + public boolean isReturnOldExchange() { + return returnOldExchange; + } + + /** + * Whether the get operation should return the old existing Exchange if any existed. By default this option is false + * to optimize as we do not need the old exchange when aggregating. + */ + public void setReturnOldExchange(boolean returnOldExchange) { + this.returnOldExchange = returnOldExchange; + } + + public void setJdbcCamelCodec(JdbcCamelCodec codec) { + this.codec = codec; + } + + public boolean hasHeadersToStoreAsText() { + return this.headersToStoreAsText != null && !this.headersToStoreAsText.isEmpty(); + } + + public List getHeadersToStoreAsText() { + return headersToStoreAsText; + } + + /** + * Allows to store headers as String which is human readable. By default this option is disabled, storing the + * headers in binary format. + * + * @param headersToStoreAsText the list of headers to store as String + */ + public void setHeadersToStoreAsText(List headersToStoreAsText) { + this.headersToStoreAsText = headersToStoreAsText; + } + + public boolean isStoreBodyAsText() { + return storeBodyAsText; + } + + /** + * Whether to store the message body as String which is human readable. By default this option is false storing the + * body in binary format. + */ + public void setStoreBodyAsText(boolean storeBodyAsText) { + this.storeBodyAsText = storeBodyAsText; + } + + public boolean isAllowSerializedHeaders() { + return allowSerializedHeaders; + } + + public void setAllowSerializedHeaders(boolean allowSerializedHeaders) { + this.allowSerializedHeaders = allowSerializedHeaders; + } + + public int getPropagationBehavior() { + return propagationBehavior; + } + + /** + * Sets propagation behavior to use with spring transaction templates which are used for database access. The + * default is TransactionDefinition.PROPAGATION_REQUIRED. + */ + public void setPropagationBehavior(int propagationBehavior) { + this.propagationBehavior = propagationBehavior; + } + + /** + * Sets propagation behavior to use with spring transaction templates which are used for database access. The + * default is TransactionDefinition.PROPAGATION_REQUIRED. This setter accepts names of the constants, like + * "PROPAGATION_REQUIRED". + * + * @param propagationBehaviorName + */ + public void setPropagationBehaviorName(String propagationBehaviorName) { + if (!propagationBehaviorName.startsWith(DefaultTransactionDefinition.PREFIX_PROPAGATION)) { + throw new IllegalArgumentException("Only propagation constants allowed"); + } + setPropagationBehavior(PROPAGATION_CONSTANTS.asNumber(propagationBehaviorName).intValue()); + } + + public LobHandler getLobHandler() { + return lobHandler; + } + + /** + * Sets a custom LobHandler to use + */ + public void setLobHandler(LobHandler lobHandler) { + this.lobHandler = lobHandler; + } + + public JdbcOptimisticLockingExceptionMapper getJdbcOptimisticLockingExceptionMapper() { + return jdbcOptimisticLockingExceptionMapper; + } + + public void setJdbcOptimisticLockingExceptionMapper( + JdbcOptimisticLockingExceptionMapper jdbcOptimisticLockingExceptionMapper) { + this.jdbcOptimisticLockingExceptionMapper = jdbcOptimisticLockingExceptionMapper; + } + + public String getRepositoryName() { + return repositoryName; + } + + public String getRepositoryNameCompleted() { + return getRepositoryName() + "_completed"; + } + + @Override + protected void doInit() throws Exception { + super.doInit(); + + ObjectHelper.notNull(repositoryName, "RepositoryName"); + ObjectHelper.notNull(transactionManager, "TransactionManager"); + ObjectHelper.notNull(dataSource, "DataSource"); + + transactionTemplate = new TransactionTemplate(transactionManager); + transactionTemplate.setPropagationBehavior(propagationBehavior); + + transactionTemplateReadOnly = new TransactionTemplate(transactionManager); + transactionTemplateReadOnly.setPropagationBehavior(propagationBehavior); + transactionTemplateReadOnly.setReadOnly(true); + } + + @Override + protected void doStart() throws Exception { + super.doStart(); + + // log number of existing exchanges + int current = getKeys().size(); + int completed = scan(null).size(); + + if (current > 0) { + LOG.info("On startup there are " + current + " aggregate exchanges (not completed) in repository: " + + getRepositoryName()); + } else { + LOG.info("On startup there are no existing aggregate exchanges (not completed) in repository: {}", + getRepositoryName()); + } + if (completed > 0) { + LOG.warn("On startup there are " + completed + " completed exchanges to be recovered in repository: " + + getRepositoryNameCompleted()); + } else { + LOG.info("On startup there are no completed exchanges to be recovered in repository: {}", + getRepositoryNameCompleted()); + } + } + + @Override + protected void doStop() throws Exception { + // noop + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/PostgresAggregationRepository.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/PostgresAggregationRepository.java new file mode 100644 index 00000000..91b10920 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/aggregation/repo/PostgresAggregationRepository.java @@ -0,0 +1,103 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.aggregation.repo; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.transaction.PlatformTransactionManager; + +import javax.sql.DataSource; + +/** + * PostgreSQL specific {@link JdbcAggregationRepository} that deals with SQL Violation Exceptions using special + * {@code INSERT INTO .. ON CONFLICT DO NOTHING} claues. + */ +public class PostgresAggregationRepository extends JdbcAggregationRepository { + + /** + * Creates an aggregation repository + */ + public PostgresAggregationRepository() { + } + + /** + * Creates an aggregation repository with the three mandatory parameters + */ + public PostgresAggregationRepository(PlatformTransactionManager transactionManager, String repositoryName, + DataSource dataSource) { + super(transactionManager, repositoryName, dataSource); + } + + /** + * Inserts a new record into the given repository table + * + * @param camelContext the current CamelContext + * @param correlationId the correlation key + * @param exchange the aggregated exchange + * @param repositoryName The name of the table + */ + protected void insert( + final CamelContext camelContext, final String correlationId, final Exchange exchange, String repositoryName) + throws Exception { + // The default totalParameterIndex is 2 for ID and Exchange. Depending on logic this will be increased + int totalParameterIndex = 2; + StringBuilder queryBuilder = new StringBuilder() + .append("INSERT INTO ").append(repositoryName) + .append('(') + .append(EXCHANGE).append(", ") + .append(ID); + + if (isStoreBodyAsText()) { + queryBuilder.append(", ").append(BODY); + totalParameterIndex++; + } + + if (hasHeadersToStoreAsText()) { + for (String headerName : getHeadersToStoreAsText()) { + queryBuilder.append(", ").append(headerName); + totalParameterIndex++; + } + } + + queryBuilder.append(") VALUES ("); + + for (int i = 0; i < totalParameterIndex - 1; i++) { + queryBuilder.append("?, "); + } + queryBuilder.append("?)"); + + queryBuilder.append(" ON CONFLICT DO NOTHING"); + + String sql = queryBuilder.toString(); + + int updateCount = insertHelper(camelContext, correlationId, exchange, sql, 1L); + if (updateCount == 0 && getRepositoryName().equals(repositoryName)) { + throw new DataIntegrityViolationException("No row was inserted due to data violation"); + } + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/BundleNotFound.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/BundleNotFound.java new file mode 100644 index 00000000..c31371d2 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/BundleNotFound.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.exception; + +public class BundleNotFound extends RuntimeException { + + public BundleNotFound() { + super(); + } + + public BundleNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public BundleNotFound(String message, Throwable cause) { + super(message, cause); + } + + public BundleNotFound(String message) { + super(message); + } + + public BundleNotFound(Throwable cause) { + super(cause); + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/ConnectorNotFound.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/ConnectorNotFound.java new file mode 100644 index 00000000..849f3411 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/ConnectorNotFound.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.exception; + +public class ConnectorNotFound extends RuntimeException { + + public ConnectorNotFound() { + super(); + } + + public ConnectorNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public ConnectorNotFound(String message, Throwable cause) { + super(message, cause); + } + + public ConnectorNotFound(String message) { + super(message); + } + + public ConnectorNotFound(Throwable cause) { + super(cause); + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/EsbNotFound.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/EsbNotFound.java new file mode 100644 index 00000000..24b97a20 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/EsbNotFound.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.exception; + +public class EsbNotFound extends RuntimeException { + + public EsbNotFound() { + super(); + } + + public EsbNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public EsbNotFound(String message, Throwable cause) { + super(message, cause); + } + + public EsbNotFound(String message) { + super(message); + } + + public EsbNotFound(Throwable cause) { + super(cause); + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/ProfileNotFound.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/ProfileNotFound.java new file mode 100644 index 00000000..55736530 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/ProfileNotFound.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.exception; + +public class ProfileNotFound extends RuntimeException { + + private static final long serialVersionUID = 6701844035750412423L; + + public ProfileNotFound() { + super(); + } + + public ProfileNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public ProfileNotFound(String message, Throwable cause) { + super(message, cause); + } + + public ProfileNotFound(String message) { + super(message); + } + + public ProfileNotFound(Throwable cause) { + super(cause); + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/TemplateNotFound.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/TemplateNotFound.java new file mode 100644 index 00000000..8bdfda99 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/exception/TemplateNotFound.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.exception; + +public class TemplateNotFound extends RuntimeException { + + public TemplateNotFound() { + super(); + } + + public TemplateNotFound(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } + + public TemplateNotFound(String message, Throwable cause) { + super(message, cause); + } + + public TemplateNotFound(String message) { + super(message); + } + + public TemplateNotFound(Throwable cause) { + super(cause); + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/interceptor/SoapHeaderInterceptor.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/interceptor/SoapHeaderInterceptor.java new file mode 100644 index 00000000..5bce75a1 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/interceptor/SoapHeaderInterceptor.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.interceptor; + +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.headers.Header; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.jaxb.JAXBDataBinding; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.Phase; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.xml.bind.JAXBException; +import javax.xml.namespace.QName; +import java.util.List; +import java.util.Map; + +public class SoapHeaderInterceptor extends AbstractSoapInterceptor { + + private static final Logger log = LoggerFactory.getLogger(SoapHeaderInterceptor.class); + + private static final String HEADER_USER_LOGIN = "X-ForwardedUser"; + private static final String HEADER_CREATED_BY = "createdBy"; + private String namespaceUri = ""; + + public SoapHeaderInterceptor() { + super(Phase.READ); + } + + public void handleMessage(SoapMessage message) throws Fault { + try { + Map> headers = (Map>) message.get(Message.PROTOCOL_HEADERS); + List
soapHeaders = message.getHeaders(); + soapHeaders.add(new Header(new QName(namespaceUri, HEADER_CREATED_BY), + getSystemName(headers), new JAXBDataBinding(String.class))); + message.put(Header.HEADER_LIST, soapHeaders); + } catch (JAXBException e) { + log.error("Error", e); + throw new Fault(e); + } + } + + private String getSystemName(Map> headers) { + List list = headers.get(HEADER_USER_LOGIN); + return list != null && !list.isEmpty() ? headers.get(HEADER_USER_LOGIN).get(0) : null; + } + + public void setNamespaceUri(String namespaceUri) { + this.namespaceUri = namespaceUri; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/CustomHeader.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/CustomHeader.java new file mode 100644 index 00000000..d42c9a5f --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/CustomHeader.java @@ -0,0 +1,66 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.util; + +public class CustomHeader { + + private String id; + private String type; + private String value; + + public CustomHeader() { + } + + public CustomHeader(String id, String type, String value) { + this.id = id; + this.type = type; + this.value = value; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/HeadersConverter.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/HeadersConverter.java new file mode 100644 index 00000000..43bf4296 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/HeadersConverter.java @@ -0,0 +1,189 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.util; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import org.apache.camel.Exchange; +import org.apache.xerces.dom.DocumentImpl; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class HeadersConverter { + protected static final Logger log = LoggerFactory.getLogger(HeadersConverter.class); + + private String customHeaders; + private String customHeaderPrefix; + private String namespace; + + public void xml2camelHeaders(Exchange exchange) { + NodeList nodes = exchange.getIn().getHeader(customHeaders, NodeList.class); + + if (nodes == null) { + log.warn(customHeaders + " not found"); + return; + } + + for (int i = 0; i < nodes.getLength(); ++i) { + Node child = nodes.item(i).getFirstChild(); + String headerName = ""; + String headerValue = ""; + while (child != null) { + if ("id".equals(child.getLocalName())) { + headerName = customHeaderPrefix + child.getTextContent(); + } else if ("value".equals(child.getLocalName())) { + headerValue = child.getTextContent(); + } + child = child.getNextSibling(); + } + if (!headerName.isEmpty()) { + exchange.getIn().setHeader(headerName, headerValue); + } + } + + log.debug("Parsed xml custom headers count {}", nodes.getLength()); + } + + public void camelHeaders2xml(Exchange exchange) { + Node item = null; + Node child = null; + Document xmlDoc = new DocumentImpl(); + Node list = xmlDoc.createElement("list"); + + for (Map.Entry entry : exchange.getIn().getHeaders().entrySet()) { + if (entry.getKey().startsWith(customHeaderPrefix)) { + String name = entry.getKey().substring(customHeaderPrefix.length()); + if (entry.getValue() == null) break; + String value = entry.getValue().toString(); + + item = xmlDoc.createElementNS(namespace, "customHeader"); + + child = xmlDoc.createElementNS(namespace, "id"); + child.appendChild(xmlDoc.createTextNode(name)); + item.appendChild(child); + + child = xmlDoc.createElementNS(namespace, "value"); + child.appendChild(xmlDoc.createTextNode(value)); + item.appendChild(child); + + list.appendChild(item); + } + } + + exchange.getIn().setHeader(customHeaders, list); + } + + public void xml2Json(Exchange exchange) { + NodeList nodes = exchange.getIn().getHeader(customHeaders, NodeList.class); + + if (nodes == null) { + log.warn(customHeaders + " not found"); + return; + } + + List customHeaders = new ArrayList<>(); + for (int i = 0; i < nodes.getLength(); ++i) { + Node child = nodes.item(i).getFirstChild(); + String headerName = ""; + String headerValue = ""; + String headerType = ""; + while (child != null) { + if ("id".equals(child.getLocalName())) { + headerName = child.getTextContent(); + } else if ("value".equals(child.getLocalName())) { + headerValue = child.getTextContent(); + } else if ("type".equals(child.getLocalName())) { + headerType = child.getTextContent(); + } + child = child.getNextSibling(); + } + if (!headerName.isEmpty()) { + customHeaders.add(new CustomHeader(headerName, headerType, headerValue)); + } + } + Gson gson = new Gson(); + exchange.getIn().setHeader(this.customHeaders, gson.toJson(customHeaders)); + + log.debug("Parsed xml custom headers count {}", nodes.getLength()); + } + + public void json2xml(Exchange exchange) { + String headers = exchange.getIn().getHeader(customHeaders, String.class); + + if (headers == null) { + log.warn(customHeaders + " not found"); + return; + } + + Gson gson = new Gson(); + List customHeaders = gson.fromJson(headers, new TypeToken>() { + }.getType()); + + Node item = null; + Node child = null; + Document xmlDoc = new DocumentImpl(); + Node list = xmlDoc.createElement("list"); + + for (CustomHeader customHeader : customHeaders) { + item = xmlDoc.createElementNS(namespace, "customHeader"); + + child = xmlDoc.createElementNS(namespace, "id"); + child.appendChild(xmlDoc.createTextNode(customHeader.getId())); + item.appendChild(child); + + child = xmlDoc.createElementNS(namespace, "type"); + child.appendChild(xmlDoc.createTextNode(customHeader.getType())); + item.appendChild(child); + + child = xmlDoc.createElementNS(namespace, "value"); + child.appendChild(xmlDoc.createTextNode(customHeader.getValue())); + item.appendChild(child); + + list.appendChild(item); + } + + exchange.getIn().setHeader(this.customHeaders, list); + } + + public void setCustomHeaderPrefix(String customHeaderPrefix) { + this.customHeaderPrefix = customHeaderPrefix; + } + + public void setCustomHeaders(String customHeaders) { + this.customHeaders = customHeaders; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/PropertiesHelper.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/PropertiesHelper.java new file mode 100644 index 00000000..06ecdfae --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/PropertiesHelper.java @@ -0,0 +1,157 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +public class PropertiesHelper { + + private static final Log LOG = LogFactory.getLog(PropertiesHelper.class.getName()); + + private static final String EMPTY_STRING = ""; + + private String configPath; + private static final String karafEtcPath = System.getProperty("karaf.etc"); + private String configFile; + + private Properties properties; + + public PropertiesHelper() { + } + + public PropertiesHelper(String configPath) { + LOG.debug("Set custom path: " + configPath + " file: " + configFile); + this.configPath = configPath; + } + + public PropertiesHelper(String configPath, String configFile) { + LOG.debug("Load properties from custom path: " + configPath + " file: " + configFile); + this.configPath = configPath; + this.configFile = configFile; + loadProperties(configPath, configFile); + } + + public PropertiesHelper(String configFile, boolean loadKarafEtc) { + this.configFile = configFile; + LOG.debug("Load properties from karaf etc: " + karafEtcPath + " file: " + configFile); + if (loadKarafEtc) { + loadProperties(karafEtcPath, configFile); + LOG.debug("Loaded properties: " + (properties != null ? properties.size() : "null")); + } + } + + public Properties load() { + if (this.configPath != null && !this.configPath.isEmpty() + && this.configFile != null && !this.configFile.isEmpty()) { + return loadProperties(configPath, configFile); + } else if (this.configFile != null && !this.configFile.isEmpty()) { + return loadProperties(karafEtcPath, configFile); + } else { + throw new IllegalArgumentException("configPath OR configFile NOT SETTED"); + } + } + + protected Properties loadProperties(String path, String configFile) { + try (InputStream input = new FileInputStream(path + File.separator + configFile)) { + properties = new Properties(); + properties.load(input); + } catch (IOException ex) { + LOG.error(ex); + } + return properties; + } + + public long getInteger(String name) { + return getInteger(name, 0); + } + + public long getInteger(String name, int defaultValue) { + String value = this.properties.getProperty(name); + return value != null && !EMPTY_STRING.equals(value) ? Integer.valueOf(value) : defaultValue; + } + + public int getInteger(String name, String defaultValue) { + return Integer.valueOf(this.properties.getProperty(name, defaultValue)); + } + + public long getLong(String name) { + return getLong(name, 0L); + } + + public long getLong(String name, long defaultValue) { + String value = this.properties.getProperty(name); + return value != null && !EMPTY_STRING.equals(value) ? Long.valueOf(value) : defaultValue; + } + + public long getLong(String name, String defaultValue) { + return Long.valueOf(this.properties.getProperty(name, defaultValue)); + } + + public String getString(String name) { + return this.properties.getProperty(name, EMPTY_STRING); + } + + public String getString(String name, String defaultValue) { + return this.properties.getProperty(name, defaultValue); + } + + public String[] getStringArray(String name, String[] defaultValue) { + String value = this.properties.getProperty(name, EMPTY_STRING); + return !value.equals(EMPTY_STRING) ? value.split(",") : defaultValue; + } + + public String getConfigPath() { + return configPath; + } + + public void setConfigPath(String configPath) { + this.configPath = configPath; + } + + public String getConfigFile() { + return configFile; + } + + public void setConfigFile(String configFile) { + this.configFile = configFile; + } + + public Properties getProperties() { + return properties; + } + + public void setProperties(Properties properties) { + this.properties = properties; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/SimpleOutHeaderFilterStrategy.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/SimpleOutHeaderFilterStrategy.java new file mode 100644 index 00000000..3ef1d210 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/SimpleOutHeaderFilterStrategy.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.util; + +import org.apache.camel.Exchange; +import org.apache.camel.spi.HeaderFilterStrategy; + +import java.util.HashSet; +import java.util.Set; + +public class SimpleOutHeaderFilterStrategy implements HeaderFilterStrategy { + + private Set outFilter; + + public void setOutFilter(Set value) { + if (value == null) { + outFilter = new HashSet<>(); + } else { + outFilter = value; + } + } + + @Override + public boolean applyFilterToCamelHeaders(String headerName, Object headerValue, Exchange exchange) { + return !outFilter.contains(headerName); + } + + @Override + public boolean applyFilterToExternalHeaders(String headerName, Object headerValue, Exchange exchange) { + return false; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/SystemHeadersConstants.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/SystemHeadersConstants.java new file mode 100644 index 00000000..9c4c9266 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/util/SystemHeadersConstants.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.util; + +public class SystemHeadersConstants { + public static final String HEADER_USER_LOGIN = "X-ForwardedUser"; + public static final String HEADER_USER_ID = "X-ForwardedUserId"; + public static final String HEADER_SYSTEM_NAME = "X-SystemName"; + public static final String HEADER_SYSTEM_UUID = "X-SystemUuid"; + public static final String HEADER_SYSTEM_ID = "X-SystemId"; + public static final String HEADER_IS_DISPLAY_SERVICE_SERVICE = "NTX_IsDisplayServiceSchema"; + + private SystemHeadersConstants() { + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/validator/ValidateInterceptor.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/validator/ValidateInterceptor.java new file mode 100644 index 00000000..418f2936 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/validator/ValidateInterceptor.java @@ -0,0 +1,126 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.validator; + +import java.io.IOException; +import java.util.List; + +import javax.xml.soap.SOAPMessage; +import javax.xml.stream.XMLStreamException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; +import javax.xml.xpath.XPathExpressionException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.service.Service; +import org.apache.cxf.service.model.ServiceModelUtil; +import org.apache.cxf.ws.addressing.EndpointReferenceUtils; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +@Deprecated(since = "1.10", forRemoval = true) +public class ValidateInterceptor extends AbstractPhaseInterceptor { + + private static final Log LOG = LogFactory.getLog(ValidateInterceptor.class); + + private final SAAJInInterceptor saajIn; + private final XmlParser xmlParser; + private boolean schemaValidationEnabled; + + public ValidateInterceptor() { + super(Phase.PRE_PROTOCOL); + saajIn = new SAAJInInterceptor(); + xmlParser = new XmlParser(); + + getAfter().add(SAAJInInterceptor.class.getName()); + } + + @Override + public void handleMessage(SoapMessage message) throws Fault { + try { + Node body = getMessageBody((DOMSource) getSOAPMessage(message).getSOAPPart().getContent()); + if (body != null) + validate(body, message); + else + throw new XMLStreamException("Can't find the tag \"Body\""); + } catch (RuntimeException re) { + throw re; + } catch (Exception e) { + throw new Fault(e); + } + } + + private Node getMessageBody(DOMSource source) throws XPathExpressionException { + Node node = source.getNode().cloneNode(true); + List nodeList = xmlParser.getNodes(node.getLastChild(), "Body"); + return !nodeList.isEmpty() ? nodeList.get(0) : null; + } + + private void validate(Node node, SoapMessage soapMessage) + throws IOException, SAXException, XPathExpressionException { + Validator validator = getValidator(soapMessage); + validator.validate(new DOMSource(getNodeForValidate(node))); + } + + private Node getNodeForValidate(Node node) throws XPathExpressionException { + if (schemaValidationEnabled && node.getLocalName().contains("packets")) { + Element element = (Element) node; + for (Node content : xmlParser.getNodes(element, "content")) { + content.getParentNode().removeChild(content); + } + return element; + } + return node; + } + + private Validator getValidator(SoapMessage soapMessage) { + Service service = ServiceModelUtil.getService(soapMessage.getExchange()); + Schema schema = + EndpointReferenceUtils.getSchema(service.getServiceInfos().get(0), soapMessage.getExchange().getBus()); + return schema.newValidator(); + } + + private SOAPMessage getSOAPMessage(SoapMessage smsg) { + SOAPMessage soapMessage = smsg.getContent(SOAPMessage.class); + if (soapMessage == null) { + saajIn.handleMessage(smsg); + soapMessage = smsg.getContent(SOAPMessage.class); + } + return soapMessage; + } + + public void setSchemaValidationEnabled(boolean schemaValidationEnabled) { + this.schemaValidationEnabled = schemaValidationEnabled; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/validator/XmlParser.java b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/validator/XmlParser.java new file mode 100644 index 00000000..a29d2ce1 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime-legacy/src/main/java/ru/entaxy/esb/system/common/validator/XmlParser.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.common.validator; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.xpath.*; +import java.util.ArrayList; +import java.util.List; + +public class XmlParser { + + public List getNodes(Node node, String elementName) throws XPathExpressionException { + XPath xpath = XPathFactory.newInstance().newXPath(); + + XPathExpression expr = xpath.compile("//*[local-name()='" + elementName + "']/child::node()"); + NodeList nodeList = (NodeList) expr.evaluate(node.getOwnerDocument(), XPathConstants.NODESET); + + return getNotNullNodes(nodeList); + } + + private List getNotNullNodes(NodeList nodeList) { + List result = new ArrayList<>(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getLocalName() != null) { + result.add(node); + } + } + return result; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/camel/aggregation/JmsCamelAggregateExtension.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/camel/aggregation/JmsCamelAggregateExtension.java new file mode 100644 index 00000000..f6f51ed8 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/camel/aggregation/JmsCamelAggregateExtension.java @@ -0,0 +1,59 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.camel.aggregation; + +import org.apache.camel.Exchange; +import org.apache.camel.component.jms.JmsMessage; +import org.apache.camel.processor.aggregate.AggregateExtension; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.jms.JMSException; +import javax.jms.Session; + +public class JmsCamelAggregateExtension implements AggregateExtension { + + private static final Log LOG = LogFactory.getLog(JmsCamelAggregateExtension.class); + + @Override + public boolean checkExtension(Exchange exchange) { + return exchange instanceof JmsMessage; + } + + @Override + public Exchange doExtension(Exchange exchange) { + JmsMessage jms = exchange.getIn(JmsMessage.class); + Session session = jms.getJmsSession(); + try { + if (session != null && Session.CLIENT_ACKNOWLEDGE == session.getAcknowledgeMode()) { + jms.getJmsMessage().acknowledge(); + } + } catch (JMSException e) { + LOG.error("Error in CLIENT_ACKNOWLEDGE.", e); + } + return exchange; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/ClusterBundleDataProvider.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/ClusterBundleDataProvider.java new file mode 100644 index 00000000..3b8a22fe --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/ClusterBundleDataProvider.java @@ -0,0 +1,109 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cluster; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import org.apache.karaf.cellar.bundle.BundleState; +import org.apache.karaf.cellar.bundle.Constants; +import org.apache.karaf.cellar.core.ClusterManager; +import org.apache.karaf.cellar.core.Configurations; +import org.apache.karaf.cellar.core.GroupManager; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Component(service = ClusterBundleDataProvider.class, immediate = true) +public class ClusterBundleDataProvider { + + protected static ClusterBundleDataProvider INSTANCE = null; + + private static final Logger LOG = LoggerFactory.getLogger(ClusterBundleDataProvider.class); + + protected BundleContext bundleContext; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile protected ClusterManager clusterManager; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile protected GroupManager groupManager; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + INSTANCE = this; + } + + public List getGroups(Bundle bundle) { + + List result = new ArrayList<>(); + + String symbolicName = bundle.getSymbolicName(); +// Изменено, потому что bundle.getVersion() съедает ведущие нули + String version = bundle.getHeaders().get(org.osgi.framework.Constants.BUNDLE_VERSION); + + Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); + + try { + Set groupNames = groupManager.listGroupNames(groupManager.getNode()); + for (String groupName : groupNames) { + @SuppressWarnings("unchecked") + Map clusterBundles = + clusterManager.getMap(Constants.BUNDLE_MAP + Configurations.SEPARATOR + groupName); + Optional bundleState = clusterBundles.values().stream() + .filter(state -> state.getSymbolicName().equals(symbolicName)) + .filter(state -> state.getVersion().equals(version)).findFirst(); + if (bundleState.isPresent()) { + result.add(groupName); + } else { + Optional bundleStateWithoutVersionFiltering = clusterBundles.values().stream() + .filter(state -> state.getSymbolicName().equals(symbolicName)).findFirst(); + if (bundleStateWithoutVersionFiltering.isPresent()) { + result.add("?" + groupName); + } + } + } + } catch (Exception e) { + LOG.error(String.format("Error getting groups for bundle [%s/%s]", symbolicName, version), e); + } + return result; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/HazelcastLockClusterService.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/HazelcastLockClusterService.java new file mode 100644 index 00000000..6d83fbd6 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/HazelcastLockClusterService.java @@ -0,0 +1,169 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cluster; + +import java.util.concurrent.TimeUnit; + +import org.apache.camel.cluster.CamelClusterView; +import org.apache.camel.support.cluster.AbstractCamelClusterService; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + + +@Deprecated(since = "1.10") +public class HazelcastLockClusterService extends AbstractCamelClusterService { + + private static final String DEFAULT_CACHE_NAME = "entaxy"; + private static final String DEFAULT_ID = "entaxy"; + + private HazelcastInstance hazelcastInstance; + private IMap cache; + private String cacheName; + + private long acquireLockDelay = 1; + private TimeUnit acquireLockDelayUnit = TimeUnit.SECONDS; + private long acquireLockInterval = 10; + private TimeUnit acquireLockIntervalUnit = TimeUnit.SECONDS; + private long healthInterval = 60; + private TimeUnit healthIntervalUnit = TimeUnit.SECONDS; + + public HazelcastLockClusterService(HazelcastInstance hazelcastInstance) { + this(hazelcastInstance, DEFAULT_CACHE_NAME); + } + + public HazelcastLockClusterService(HazelcastInstance hazelcastInstance, String cacheName) { + this.hazelcastInstance = hazelcastInstance; + this.cacheName = cacheName; + this.cache = hazelcastInstance.getMap(cacheName); + setId(DEFAULT_ID); + } + + @Override + protected CamelClusterView createView(String namespace) throws Exception { + return new HazelcastValueLockClusterView(this, namespace); + } + + public String getCacheName() { + return cacheName; + } + + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } + + public HazelcastInstance getHazelcastInstance() { + return hazelcastInstance; + } + + public void setHazelcastInstance(HazelcastInstance hazelcastInstance) { + this.hazelcastInstance = hazelcastInstance; + } + + public IMap getCache() { + return cache; + } + + public void setCache(IMap cache) { + this.cache = cache; + } + + public long getAcquireLockDelay() { + return acquireLockDelay; + } + + /** + * The time to wait before starting to try to acquire lock, default 1. + */ + public void setAcquireLockDelay(long acquireLockDelay) { + this.acquireLockDelay = acquireLockDelay; + } + + public void setAcquireLockDelay(long pollDelay, TimeUnit pollDelayUnit) { + setAcquireLockDelay(pollDelay); + setAcquireLockDelayUnit(pollDelayUnit); + } + + public TimeUnit getAcquireLockDelayUnit() { + return acquireLockDelayUnit; + } + + /** + * The time unit of the acquireLockDelay, default to TimeUnit.SECONDS. + */ + public void setAcquireLockDelayUnit(TimeUnit acquireLockDelayUnit) { + this.acquireLockDelayUnit = acquireLockDelayUnit; + } + + public long getAcquireLockInterval() { + return acquireLockInterval; + } + + /** + * The time to wait between attempts to try to acquire lock, default 10. + */ + public void setAcquireLockInterval(long acquireLockInterval) { + this.acquireLockInterval = acquireLockInterval; + } + + public void setAcquireLockInterval(long pollInterval, TimeUnit pollIntervalUnit) { + setAcquireLockInterval(pollInterval); + setAcquireLockIntervalUnit(pollIntervalUnit); + } + + public TimeUnit getAcquireLockIntervalUnit() { + return acquireLockIntervalUnit; + } + + /** + * The time unit of the acquireLockInterval, default to TimeUnit.SECONDS. + */ + public void setAcquireLockIntervalUnit(TimeUnit acquireLockIntervalUnit) { + this.acquireLockIntervalUnit = acquireLockIntervalUnit; + } + + public long getHealthInterval() { + return healthInterval; + } + + /** + * The time between current timestamp and leader's last visit, should be greater then acquireLockDelay+acquireLockInterval, default 60. + */ + public void setHealthInterval(long healthInterval) { + this.healthInterval = healthInterval; + } + + public TimeUnit getHealthIntervalUnit() { + return healthIntervalUnit; + } + + /** + * The time unit of the healthInterval, default to TimeUnit.SECONDS. + */ + public void setHealthIntervalUnit(TimeUnit healthIntervalUnit) { + this.healthIntervalUnit = healthIntervalUnit; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/HazelcastValueLockClusterView.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/HazelcastValueLockClusterView.java new file mode 100644 index 00000000..8447433d --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/HazelcastValueLockClusterView.java @@ -0,0 +1,271 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cluster; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import org.apache.camel.CamelContext; +import org.apache.camel.cluster.CamelClusterMember; +import org.apache.camel.support.cluster.AbstractCamelClusterView; +import org.apache.camel.util.ObjectHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.hazelcast.core.HazelcastInstance; +import com.hazelcast.core.IMap; + +@Deprecated(since = "1.10") +public class HazelcastValueLockClusterView extends AbstractCamelClusterView { + + private static final transient Logger LOG = LoggerFactory.getLogger(HazelcastValueLockClusterView.class); + + private static final String LOCK_VALUE_DELIMITER = "_"; + + private HazelcastInstance hazelcastInstance; + private IMap cache; + private long healthInterval; + private TimeUnit healthIntervalUnit; + private String lockName; + + private final ClusterMember localMember; + private ScheduledExecutorService executor; + private ScheduledFuture task; + + private long currentId; + private volatile boolean leader; + + protected HazelcastValueLockClusterView(HazelcastLockClusterService cluster, String namespace) { + super(cluster, namespace); + + this.hazelcastInstance = cluster.getHazelcastInstance(); + this.cache = cluster.getCache(); + this.healthInterval = cluster.getHealthInterval(); + this.healthIntervalUnit = cluster.getHealthIntervalUnit(); + + this.currentId = hazelcastInstance.getAtomicLong(cluster.getCacheName()).getAndIncrement(); + + this.localMember = new ClusterMember(); + this.lockName = namespace; + } + + @Override + public Optional getLeader() { + return this.localMember.isLeader() ? Optional.of(this.localMember) : Optional.empty(); + } + + @Override + public CamelClusterMember getLocalMember() { + return this.localMember; + } + + @Override + public List getMembers() { + return new ArrayList() {{ add(localMember); }}; + } + + @Override + protected void doStart() throws Exception { + HazelcastLockClusterService service = getClusterService().unwrap(HazelcastLockClusterService.class); + executor = getExecutor(); + + task = executor.scheduleAtFixedRate(this::tryLock, + TimeUnit.MILLISECONDS.convert(service.getAcquireLockDelay(), service.getAcquireLockDelayUnit()), + TimeUnit.MILLISECONDS.convert(service.getAcquireLockInterval(), service.getAcquireLockIntervalUnit()), + TimeUnit.MILLISECONDS); + } + + protected ScheduledExecutorService getExecutor() { + if (executor == null) { + HazelcastLockClusterService service = getClusterService().unwrap(HazelcastLockClusterService.class); + // Camel context should be set at this stage. + final CamelContext context = ObjectHelper.notNull(getCamelContext(), "CamelContext"); + + executor = context.getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "HazelcastLockClusterService-" + service.getId()); + } + + return executor; + } + + protected void tryLock() { + if (isStarting() || isStarted()) { + if (localMember.isLeader()) { + leaderHealth(); + } else if (!isLeaderHealthy()) { + tryLockProc(); + } else { + LOG.trace("The leader is healthy, but the jackals are on alert! Key {}", lockName); + } + } + } + + protected void leaderHealthWrite() { + cache.put(lockName, getLockValueNext()); + LOG.trace("Leader health refresh on lock {}", lockName); + } + + protected void leaderHealth() { + if (getLockOwnerId() == currentId) { + leaderHealthWrite(); + LOG.trace("Holding the lock on key {}", lockName); + } else { + LOG.error("Inconsistent lock on key {}. Leadership is reset!", lockName); + leader = false; + fireLeadershipChangedEvent(Optional.empty()); + } + } + + protected boolean isLeaderHealthy() { + boolean health = false; + if (cache.containsKey(lockName)) { + long leaderHealthCheck = getLockMilliseconds(); + long difference = healthIntervalUnit.convert(System.currentTimeMillis() - leaderHealthCheck, TimeUnit.MILLISECONDS); + health = difference < healthInterval; + } else { + LOG.warn("Empty leader's health key {}", lockName); + } + return health; + } + + protected void tryLockProc() { + LOG.debug("Try to acquire a lock on key {}", lockName); + + if (cache.tryLock(lockName)) { + leaderHealthWrite(); + if (getLockOwnerId() == currentId) { + leader = true; + fireLeadershipChangedEvent(Optional.ofNullable(localMember)); + LOG.info("Lock on key {} acquired", lockName); + } + cache.unlock(lockName); + } + + if (!localMember.isLeader()) { + LOG.debug("Lock on key {} NOT acquired", lockName); + leader = false; + fireLeadershipChangedEvent(Optional.empty()); + } + } + + protected String getLockValueNext() { + return String.valueOf(currentId) + LOCK_VALUE_DELIMITER + System.currentTimeMillis(); + } + + protected long getLockOwnerId() { + return getLockPart(cache.get(lockName), 0); + } + + protected long getLockMilliseconds() { + return getLockPart(cache.get(lockName), 1); + } + + protected long getLockPart(Object lockValue, int i) { + if (lockValue != null && lockValue instanceof String) { + String[] values = ((String)lockValue).split(LOCK_VALUE_DELIMITER); + if (values.length == 2) { + return Long.parseLong(values[i]); + } else { + throw new IllegalArgumentException("Lock value = " + lockValue + " in unknown format"); + } + } + return 0L; + } + + @Override + protected void doStop() throws Exception { + leader = false; + fireLeadershipChangedEvent(Optional.empty()); + closeInternal(); + shutdownExecutors(); + } + + protected void closeInternal() { + if (task != null) { + task.cancel(true); + } + tryUnlock(); + } + + protected void shutdownExecutors() { + CamelContext context = getCamelContext(); + if (executor != null) { + if (context != null) { + context.getExecutorServiceManager().shutdown(executor); + } else { + executor.shutdown(); + } + executor = null; + } + } + + protected void tryUnlock() { + LOG.debug("Unlock key {}", lockName); + try { + if (getLockOwnerId() == currentId && cache.tryLock(lockName)) { + try { + cache.delete(lockName); + LOG.trace("Leader lock {} is cleared", lockName); + } finally { + cache.unlock(lockName); + } + LOG.info("Unlocked key {}", lockName); + } else { + LOG.debug("Current thread is not owner of lock {}", lockName); + } + } catch (IllegalMonitorStateException e) { + LOG.trace("Unlock error", e); + } + } + + public boolean isLeader() { + return leader; + } + + public void setLeader(boolean leader) { + this.leader = leader; + } + + private final class ClusterMember implements CamelClusterMember { + @Override + public boolean isLeader() { + return leader; + } + + @Override + public boolean isLocal() { + return true; + } + + @Override + public String getId() { + return getClusterService().getId(); + } + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/JGroupsLockClusterService.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/JGroupsLockClusterService.java new file mode 100644 index 00000000..fad07757 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/JGroupsLockClusterService.java @@ -0,0 +1,84 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cluster; + +import java.util.concurrent.TimeUnit; + +import org.apache.camel.support.cluster.AbstractCamelClusterService; +import org.jgroups.blocks.locking.LockService; + +import ru.entaxy.platform.core.support.runtime.service.ServiceHolder; + +public class JGroupsLockClusterService extends AbstractCamelClusterService { + + private LockService lockService; + private long acquireLockDelay = 1; + private TimeUnit acquireLockDelayUnit = TimeUnit.SECONDS; + + public JGroupsLockClusterService(ServiceHolder lockService) throws Exception { + this.lockService = lockService.getService(); + } + + @Override + protected JGroupsLockClusterView createView(String namespace) throws Exception { + return new JGroupsLockClusterView(this, namespace); + } + + public LockService getLockService() throws Exception { + return lockService; + } + + public void setLockService(LockService lockService) { + this.lockService = lockService; + } + + public long getAcquireLockDelay() { + return acquireLockDelay; + } + + /** + * The time to wait before starting to try to acquire lock, default 1. + */ + public void setAcquireLockDelay(long acquireLockDelay) { + this.acquireLockDelay = acquireLockDelay; + } + + public void setAcquireLockDelay(long pollDelay, TimeUnit pollDelayUnit) { + setAcquireLockDelay(pollDelay); + setAcquireLockDelayUnit(pollDelayUnit); + } + + public TimeUnit getAcquireLockDelayUnit() { + return acquireLockDelayUnit; + } + + /** + * The time unit of the acquireLockDelay, default to TimeUnit.SECONDS. + */ + public void setAcquireLockDelayUnit(TimeUnit acquireLockDelayUnit) { + this.acquireLockDelayUnit = acquireLockDelayUnit; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/JGroupsLockClusterView.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/JGroupsLockClusterView.java new file mode 100644 index 00000000..97ebeb3b --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cluster/JGroupsLockClusterView.java @@ -0,0 +1,159 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cluster; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.locks.Lock; + +import org.apache.camel.CamelContext; +import org.apache.camel.cluster.CamelClusterMember; +import org.apache.camel.cluster.CamelClusterService; +import org.apache.camel.support.cluster.AbstractCamelClusterView; +import org.apache.camel.util.ObjectHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class JGroupsLockClusterView extends AbstractCamelClusterView { + + private static final transient Logger LOG = LoggerFactory.getLogger(JGroupsLockClusterView.class); + private final CamelClusterMember localMember = new JGroupsLocalMember(); + private String lockName; + + private Lock lock; + private ScheduledExecutorService executor; + private volatile boolean isMaster; + + protected JGroupsLockClusterView(CamelClusterService cluster, String namespace) { + super(cluster, namespace); + lockName = namespace; + } + + @Override + public Optional getLeader() { + if (isMaster) { + return Optional.of(localMember); + } else { + return Optional.empty(); + } + } + + @Override + public CamelClusterMember getLocalMember() { + return localMember; + } + + @Override + public List getMembers() { + return new ArrayList() {{ add(localMember); }}; + } + + @Override + protected void doStart() throws Exception { + if (lock != null) { + lock.unlock(); + lock = null; + } + JGroupsLockClusterService service = getClusterService().unwrap(JGroupsLockClusterService.class); + lock = service.getLockService().getLock(lockName); + + // Camel context should be set at this stage. + final CamelContext context = ObjectHelper.notNull(getCamelContext(), "CamelContext"); + executor = context.getExecutorServiceManager().newSingleThreadScheduledExecutor(this, "JGroupsLockClusterView-" + getClusterService().getId() + "-" + lockName); + executor.schedule(new Runnable() { + @Override + public void run() { + LOG.info("Attempting to become master acquiring the lock for group: " + lockName + " in JGroups cluster"); + lock.lock(); + isMaster = true; + fireLeadershipChangedEvent(Optional.ofNullable(localMember)); + LOG.info("Became master by acquiring the lock for group: " + lockName + " in JGroups cluster"); + } + }, + service.getAcquireLockDelay(), + service.getAcquireLockDelayUnit()); + } + + @Override + protected void doStop() throws Exception { + LOG.trace("doStop: " + lockName); + stopProcess(); + } + + @Override + protected void doShutdown() throws Exception { + LOG.trace("doShutdown: " + lockName); + stopProcess(); + } + + protected void stopProcess() throws Exception { + shutdownExecutor(); + fireLeadershipChangedEvent(Optional.empty()); + clearLock(); + isMaster = false; + } + + private void clearLock() throws Exception { + if (lock != null && isMaster) { + LOG.trace("tryUnlock: " + lockName); + JGroupsLockClusterService service = getClusterService().unwrap(JGroupsLockClusterService.class); + service.getLockService().unlockForce(lockName); + LOG.debug("unlocked: " + lockName); + lock = null; + } + } + + private void shutdownExecutor() { + CamelContext context = getCamelContext(); + if (executor != null) { + if (context != null) { + context.getExecutorServiceManager().shutdown(executor); + } else { + executor.shutdown(); + } + executor = null; + } + } + + private final class JGroupsLocalMember implements CamelClusterMember { + @Override + public boolean isLeader() { + return isMaster; + } + + @Override + public boolean isLocal() { + return true; + } + + @Override + public String getId() { + return getClusterService().getId(); + } + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/BasicAuthenticationInterceptor.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/BasicAuthenticationInterceptor.java new file mode 100644 index 00000000..0843fc81 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/BasicAuthenticationInterceptor.java @@ -0,0 +1,73 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cxf; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.common.util.Base64Utility; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.transport.http.Headers; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class BasicAuthenticationInterceptor extends AbstractPhaseInterceptor { + private static final Log LOG = LogFactory.getLog(BasicAuthenticationInterceptor.class); + + private String login; + + private String password; + + private static final String BASIC = "Basic "; + private static final String AUTHORIZATION = "Authorization"; + + + public BasicAuthenticationInterceptor() { + super(Phase.SETUP); + } + + @Override + public void handleMessage(Message message) throws Fault { + String authorization = login + ":" + password; + String encodeAuthorization = Base64Utility.encode(authorization.getBytes()); + Map> headers = Headers.getSetProtocolHeaders(message); + List auth = new ArrayList<>(); + auth.add(BASIC + encodeAuthorization); + headers.put(AUTHORIZATION, auth); + } + + public void setLogin(String login) { + this.login = login; + } + + public void setPassword(String password) { + this.password = password; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/ExtJwtTokenSecurityContext.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/ExtJwtTokenSecurityContext.java new file mode 100644 index 00000000..1af41483 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/ExtJwtTokenSecurityContext.java @@ -0,0 +1,110 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cxf; + +import org.apache.cxf.common.security.SimpleGroup; +import org.apache.cxf.common.security.SimplePrincipal; +import org.apache.cxf.helpers.CastUtils; +import org.apache.cxf.rs.security.jose.jwt.JwtToken; +import org.apache.cxf.rt.security.claims.Claim; +import org.apache.cxf.rt.security.claims.ClaimCollection; +import org.apache.cxf.rt.security.claims.ClaimsSecurityContext; + +import javax.security.auth.Subject; +import java.security.Principal; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +public class ExtJwtTokenSecurityContext implements ClaimsSecurityContext { + private final JwtToken token; + private final Principal principal; + private final Set roles; + private final ClaimCollection claims = new ClaimCollection(); + + public ExtJwtTokenSecurityContext(JwtToken jwt, String roleClaim, String regexp) { + principal = new SimplePrincipal(jwt.getClaims().getSubject()); + this.token = jwt; + if (roleClaim != null && jwt.getClaims().containsProperty(roleClaim)) { + roles = new HashSet<>(); + String role = jwt.getClaims().getStringProperty(roleClaim).trim(); + //TODO Think to remove regexp cz it is heavy operation + for (String r : role.split(regexp)) { + roles.add(new SimpleGroup(r)); + } + } else { + roles = Collections.emptySet(); + } + + // Parse JwtToken into ClaimCollection + jwt.getClaims().asMap().forEach((String name, Object values) -> { + Claim claim = new Claim(); + claim.setClaimType(name); + if (values instanceof List) { + claim.setValues(CastUtils.cast((List)values)); + } else { + claim.setValues(Collections.singletonList(values)); + } + claims.add(claim); + }); + } + + public JwtToken getToken() { + return token; + } + + @Override + public Subject getSubject() { + return null; + } + + @Override + public Set getUserRoles() { + return Collections.unmodifiableSet(roles); + } + + @Override + public Principal getUserPrincipal() { + return principal; + } + + @Override + public boolean isUserInRole(String role) { + for (Principal principalRole : roles) { + if (principalRole != principal && principalRole.getName().equals(role)) { + return true; + } + } + return false; + } + + @Override + public ClaimCollection getClaims() { + return claims; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/jose/ExtJwtAuthenticationFilter.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/jose/ExtJwtAuthenticationFilter.java new file mode 100644 index 00000000..c8b83271 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/jose/ExtJwtAuthenticationFilter.java @@ -0,0 +1,109 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cxf.jose; + +import org.apache.cxf.jaxrs.utils.JAXRSUtils; +import org.apache.cxf.message.Message; +import org.apache.cxf.message.MessageUtils; +import org.apache.cxf.rs.security.jose.common.JoseConstants; +import org.apache.cxf.rs.security.jose.common.JoseException; +import org.apache.cxf.rs.security.jose.jaxrs.JwtAuthenticationFilter; +import org.apache.cxf.rs.security.jose.jwa.SignatureAlgorithm; +import org.apache.cxf.rs.security.jose.jwt.JwtToken; +import org.apache.cxf.security.SecurityContext; +import ru.entaxy.platform.core.support.runtime.cxf.ExtJwtTokenSecurityContext; +import ru.entaxy.platform.core.support.runtime.cxf.security.AnonymousSecurityContext; + +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.core.HttpHeaders; +import java.io.IOException; +import java.util.List; + +public class ExtJwtAuthenticationFilter extends JwtAuthenticationFilter { + private static final String DEFAULT_AUTH_SCHEME = "JWT"; + private String expectedAuthScheme = DEFAULT_AUTH_SCHEME; + public static final String HEADER_IS_DISPLAY_SERVICE_SERVICE = "NTX_IsDisplayServiceSchema"; + private String regexp; + + protected String getEncodedJwtToken(ContainerRequestContext requestContext) { + String auth = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); + String[] parts = auth == null ? null : auth.split(" "); + if (parts == null || !expectedAuthScheme.equals(parts[0]) || parts.length != 2) { + throw new JoseException(expectedAuthScheme + " scheme is expected"); + } + return parts[1]; + } + + public void filter(ContainerRequestContext requestContext) throws IOException { + if (!(requestContext.getSecurityContext() instanceof AnonymousSecurityContext) && !getHeaderDisplayServiceSchema(requestContext)) { + String encodedJwtToken = this.getEncodedJwtToken(requestContext); + JwtToken token = super.getJwtToken(encodedJwtToken); + SecurityContext securityContext = this.configureSecurityContext(token); + if (securityContext != null) { + JAXRSUtils.getCurrentMessage().put(SecurityContext.class, securityContext); + } + } + } + + private boolean getHeaderDisplayServiceSchema(ContainerRequestContext context) { + List ntxIsDisplayServiceSchema = context.getHeaders().get(AnonymousSecurityContext.HEADER_IS_DISPLAY_SERVICE_SERVICE); + if (ntxIsDisplayServiceSchema != null && !ntxIsDisplayServiceSchema.isEmpty()) + return Boolean.parseBoolean(ntxIsDisplayServiceSchema.get(0)); + return false; + } + + public void setExpectedAuthScheme(String expectedAuthScheme) { + this.expectedAuthScheme = expectedAuthScheme; + } + + protected SecurityContext configureSecurityContext(JwtToken jwt) { + Message m = JAXRSUtils.getCurrentMessage(); + boolean enableUnsignedJwt = + MessageUtils.getContextualBoolean(m, JoseConstants.ENABLE_UNSIGNED_JWT_PRINCIPAL, false); + + // The token must be signed/verified with a public key to set up the security context, + // unless we directly configure otherwise + if (jwt.getClaims().getSubject() != null + && (isVerifiedWithAPublicKey(jwt) || enableUnsignedJwt)) { + return new ExtJwtTokenSecurityContext(jwt, getRoleClaim(), regexp); + } + return null; + } + + private boolean isVerifiedWithAPublicKey(JwtToken jwt) { + if (isJwsRequired()) { + String alg = (String)jwt.getJwsHeader(JoseConstants.HEADER_ALGORITHM); + SignatureAlgorithm sigAlg = SignatureAlgorithm.getAlgorithm(alg); + return SignatureAlgorithm.isPublicKeyAlgorithm(sigAlg); + } + + return false; + } + + public void setRegexp(String regexp) { + this.regexp = regexp; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/security/AnonymousSecurityContext.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/security/AnonymousSecurityContext.java new file mode 100644 index 00000000..2772c606 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/security/AnonymousSecurityContext.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cxf.security; + +import org.apache.cxf.security.SecurityContext; +import org.apache.karaf.jaas.boot.principal.UserPrincipal; + +import java.security.Principal; + +public class AnonymousSecurityContext implements SecurityContext { + + public static final String HEADER_IS_DISPLAY_SERVICE_SERVICE = "NTX_IsDisplayServiceSchema"; + + public static final String ANONYMOUS_USER_NAME = "anonymous"; + + protected static Principal ANONYMOUS_USER = new UserPrincipal(ANONYMOUS_USER_NAME); + + @Override + public Principal getUserPrincipal() { + return ANONYMOUS_USER; + } + + @Override + public boolean isUserInRole(String role) { + return false; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/security/oauth2/filters/DisplaySchemaOAuthRequestFilter.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/security/oauth2/filters/DisplaySchemaOAuthRequestFilter.java new file mode 100644 index 00000000..ba19bdcc --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/cxf/security/oauth2/filters/DisplaySchemaOAuthRequestFilter.java @@ -0,0 +1,60 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.cxf.security.oauth2.filters; + +import org.apache.cxf.jaxrs.utils.JAXRSUtils; +import org.apache.cxf.rs.security.oauth2.filters.OAuthRequestFilter; +import ru.entaxy.platform.core.support.runtime.cxf.security.AnonymousSecurityContext; + +import javax.annotation.Priority; +import javax.ws.rs.Priorities; +import javax.ws.rs.container.ContainerRequestContext; +import javax.ws.rs.container.PreMatching; +import javax.ws.rs.ext.Provider; +import java.util.List; + +@Provider +@PreMatching +// Priorities.AUTHORIZATION also works +@Priority(Priorities.AUTHENTICATION) +public class DisplaySchemaOAuthRequestFilter extends OAuthRequestFilter { + + @Override + public void filter(ContainerRequestContext context) { + if (!(context.getSecurityContext() instanceof AnonymousSecurityContext) + && !getHeaderDisplayServiceSchema(context)) { + validateRequest(JAXRSUtils.getCurrentMessage()); + } + } + + private boolean getHeaderDisplayServiceSchema(ContainerRequestContext context) { + List ntxIsDisplayServiceSchema = context.getHeaders().get(AnonymousSecurityContext.HEADER_IS_DISPLAY_SERVICE_SERVICE); + if (ntxIsDisplayServiceSchema != null && !ntxIsDisplayServiceSchema.isEmpty()) + return Boolean.parseBoolean(ntxIsDisplayServiceSchema.get(0)); + return false; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/ignite/IgniteInstanceIgniter.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/ignite/IgniteInstanceIgniter.java new file mode 100644 index 00000000..55c8bfe9 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/ignite/IgniteInstanceIgniter.java @@ -0,0 +1,194 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.ignite; + +import static org.apache.ignite.IgniteSystemProperties.IGNITE_QUIET; + +import java.io.File; + +import org.apache.camel.util.ObjectHelper; +import org.apache.ignite.Ignite; +import org.apache.ignite.IgniteCache; +import org.apache.ignite.Ignition; +import org.apache.ignite.cache.CacheAtomicityMode; +import org.apache.ignite.cache.CacheMode; +import org.apache.ignite.cache.CacheRebalanceMode; +import org.apache.ignite.configuration.CacheConfiguration; +import org.apache.ignite.configuration.DataStorageConfiguration; +import org.apache.ignite.configuration.IgniteConfiguration; +import org.apache.ignite.configuration.TransactionConfiguration; +import org.apache.ignite.logger.jcl.JclLogger; +import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; +import org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder; +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class IgniteInstanceIgniter { + + private static final Logger LOG = LoggerFactory.getLogger(IgniteInstanceIgniter.class); + + private BundleContext bundleContext; + private String workDirectory; + private String cacheName; + private String rebalanceMode; + private String cacheMode; + private String atomicityMode; + private int backups; + + private Ignite ignite; + + private IgniteCache systemCache; + CacheConfiguration cacheCfg; + + public IgniteInstanceIgniter() {} + + public void start() throws Exception { + ObjectHelper.notNull(bundleContext, "bundleContext"); + ObjectHelper.notNull(workDirectory, "workDirectory"); + + IgniteConfiguration cfg = createConfig(); + LOG.info("IgniteConfiguration created for workDirectory {}", workDirectory); + + cacheCfg = createCacheConfig(cacheName); + cfg.setCacheConfiguration(cacheCfg); + LOG.info("Common CacheConfiguration inited for cacheName {}", cacheName); + + System.setProperty(IGNITE_QUIET, "false"); + + ignite = Ignition.getOrStart(cfg); + ignite.cluster().active(true); + + systemCache = ignite.getOrCreateCache(cacheCfg); + + ignite.cluster().baselineAutoAdjustEnabled(true); + //default timeout 300s +// ignite.cluster().baselineAutoAdjustTimeout(30000); + LOG.info("Ignite instance initialized"); + + bundleContext.registerService(Ignite.class, ignite, null); + LOG.info("Ignite service published"); + } + + public void stop() throws Exception { + if (ignite != null) { + ignite.close(); + } + } + + protected CacheConfiguration createCacheConfig(String cacheName) { + CacheConfiguration cacheCfg = new CacheConfiguration<>(); + cacheCfg.setName(cacheName); + cacheCfg.setRebalanceMode(CacheRebalanceMode.valueOf(rebalanceMode)); + cacheCfg.setCacheMode(CacheMode.valueOf(cacheMode)); + cacheCfg.setAtomicityMode(CacheAtomicityMode.valueOf(atomicityMode)); + cacheCfg.setBackups(backups); + return cacheCfg; + } + + protected IgniteConfiguration createConfig() { + IgniteConfiguration cfg = new IgniteConfiguration(); +// cfg.setConsistentId(); + + TcpDiscoverySpi spi = new TcpDiscoverySpi(); +// spi.setIpFinder(new TcpDiscoverySharedFsIpFinder() {{setPath(workDirectory + "/addresses");}}); + spi.setIpFinder(new TcpDiscoveryMulticastIpFinder()); + cfg.setDiscoverySpi(spi); + + cfg.setGridLogger(new JclLogger()); + cfg.setTransactionConfiguration(new TransactionConfiguration()); + + //Persistence + DataStorageConfiguration storageCfg = new DataStorageConfiguration(); + storageCfg.getDefaultDataRegionConfiguration().setPersistenceEnabled(true); + cfg.setWorkDirectory(workDirectory); + cfg.setIgniteHome(workDirectory); + cfg.setDataStorageConfiguration(storageCfg); + + return cfg; + } + + public BundleContext getBundleContext() { + return bundleContext; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + public String getWorkDirectory() { + return workDirectory; + } + + public void setWorkDirectory(String workDirectory) { + if (workDirectory != null && + !workDirectory.startsWith(File.separator) && !workDirectory.contains(":")) { + workDirectory = System.getProperty("karaf.home", "/opt/karaf") + File.separator + workDirectory; + } + this.workDirectory = workDirectory; + } + + public String getCacheName() { + return cacheName; + } + + public void setCacheName(String cacheName) { + this.cacheName = cacheName; + } + + public String getRebalanceMode() { + return rebalanceMode; + } + + public void setRebalanceMode(String rebalanceMode) { + this.rebalanceMode = rebalanceMode; + } + + public String getCacheMode() { + return cacheMode; + } + + public void setCacheMode(String cacheMode) { + this.cacheMode = cacheMode; + } + + public String getAtomicityMode() { + return atomicityMode; + } + + public void setAtomicityMode(String atomicityMode) { + this.atomicityMode = atomicityMode; + } + + public int getBackups() { + return backups; + } + + public void setBackups(int backups) { + this.backups = backups; + } + +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jackson/EntaxyObjectMapper.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jackson/EntaxyObjectMapper.java new file mode 100644 index 00000000..8930e6a4 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jackson/EntaxyObjectMapper.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.jackson; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext; +import com.fasterxml.jackson.databind.ser.DefaultSerializerProvider; +import com.fasterxml.jackson.datatype.joda.JodaModule; + +public class EntaxyObjectMapper extends ObjectMapper { + + public EntaxyObjectMapper() { + super(); + this.registerModule(new JodaModule()); + } + + public EntaxyObjectMapper(JsonFactory jf) { + super(jf); + this.registerModule(new JodaModule()); + } + + public EntaxyObjectMapper(ObjectMapper src) { + super(src); + this.registerModule(new JodaModule()); + } + + public EntaxyObjectMapper(JsonFactory jf, DefaultSerializerProvider sp, DefaultDeserializationContext dc) { + super(jf, sp, dc); + this.registerModule(new JodaModule()); + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jackson/JacksonJsonProviderFactory.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jackson/JacksonJsonProviderFactory.java new file mode 100644 index 00000000..5a648a70 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jackson/JacksonJsonProviderFactory.java @@ -0,0 +1,71 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.jackson; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.joda.JodaModule; +import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; + +import javax.ws.rs.core.MediaType; + +public class JacksonJsonProviderFactory { + + private boolean acceptSingleValueAsArray; + + private boolean failOnUnknownProperties; + + private boolean addJodaModule; + + public JacksonJsonProvider create() { + JacksonJsonProvider provider = new JacksonJsonProvider(); + + if (acceptSingleValueAsArray) + provider.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY); + + if (!failOnUnknownProperties) + provider.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + + if (addJodaModule) { + ObjectMapper mapper = provider.locateMapper(ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE); + mapper.registerModule(new JodaModule()); + } + + return provider; + } + + public void setAcceptSingleValueAsArray(boolean acceptSingleValueAsArray) { + this.acceptSingleValueAsArray = acceptSingleValueAsArray; + } + + public void setFailOnUnknownProperties(boolean failOnUnknownProperties) { + this.failOnUnknownProperties = failOnUnknownProperties; + } + + public void setAddJodaModule(boolean addJodaModule) { + this.addJodaModule = addJodaModule; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jgroups/JGroupsLockServiceIgniter.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jgroups/JGroupsLockServiceIgniter.java new file mode 100644 index 00000000..e5b7516e --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/jgroups/JGroupsLockServiceIgniter.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.jgroups; + +import org.apache.camel.util.ObjectHelper; +import org.jgroups.JChannel; +import org.jgroups.blocks.locking.LockService; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.support.runtime.service.ServiceHolderHelper; + +@Component(service = JGroupsLockServiceIgniter.class, immediate = true) +public class JGroupsLockServiceIgniter extends ServiceHolderHelper { + private static final Logger LOG = LoggerFactory.getLogger(JGroupsLockServiceIgniter.class); + + private static final String DEFAULT_JGROUPS_CONFIG = "etc/jgroups.locking.xml"; + private static final String DEFAULT_JGROUPS_CLUSTERNAME = "jgroups-master"; + + private String jgroupsConfig; + private String jgroupsClusterName; + + private JChannel channel; + private LockService lockService; + + private BundleContext bundleContext; + + @Activate + public JGroupsLockServiceIgniter(BundleContext bundleContext) { + this(DEFAULT_JGROUPS_CONFIG, DEFAULT_JGROUPS_CLUSTERNAME, bundleContext); + } + + public JGroupsLockServiceIgniter(String jgroupsConfig, String jgroupsClusterName, BundleContext bundleContext) { + this.jgroupsConfig = jgroupsConfig; + this.jgroupsClusterName = jgroupsClusterName; + this.bundleContext = bundleContext; + } + + @Activate + public void start() throws Exception { + ObjectHelper.notNull(jgroupsConfig, "jgroupsConfig"); + ObjectHelper.notNull(jgroupsClusterName, "jgroupsClusterName"); + ObjectHelper.notNull(bundleContext, "bundleContext"); + init(); + publish(); + LOG.info("JGroups ServiceHolder published"); + } + + protected void init() throws Exception { + channel = new JChannel(jgroupsConfig); + lockService = new LockService(channel); + channel.connect(jgroupsClusterName); + LOG.info("JGroups LockService instance initialized"); + } + + public void stop() throws Exception { + if (channel != null) { + channel.disconnect(); + channel.close(); + channel = null; + } + } + + @Override + public LockService getService() throws Exception { + return lockService; + } + + @Override + protected Class getGenericType() { + return LockService.class; + } + + @Override + public BundleContext getBundleContext() { + return bundleContext; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/service/ServiceHolder.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/service/ServiceHolder.java new file mode 100644 index 00000000..5f0deb7d --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/service/ServiceHolder.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.service; + +public interface ServiceHolder { + + public static final String PROP_INTERNAL_TYPE = "internalType"; + + T getService() throws Exception; + +} diff --git a/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/service/ServiceHolderHelper.java b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/service/ServiceHolderHelper.java new file mode 100644 index 00000000..c86d6a02 --- /dev/null +++ b/platform/runtime/core/core-support/core-support-runtime/src/main/java/ru/entaxy/platform/core/support/runtime/service/ServiceHolderHelper.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * core-support-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.support.runtime.service; + +import java.util.Dictionary; +import java.util.Hashtable; + +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class ServiceHolderHelper implements ServiceHolder { + + private static final Logger LOG = LoggerFactory.getLogger(ServiceHolderHelper.class); + + public abstract BundleContext getBundleContext(); + protected abstract Class getGenericType(); + + protected void publish() { + Dictionary props = new Hashtable<>(); + props.put(PROP_INTERNAL_TYPE, getGenericType().getName()); + getBundleContext().registerService(ServiceHolder.class, this, props); + LOG.debug("ServiceHolder published: " + getGenericType().getName()); + } + +} diff --git a/platform/runtime/core/core-support/src/main/cfg/generated/fragments.xml b/platform/runtime/core/core-support/src/main/cfg/generated/fragments.xml new file mode 100644 index 00000000..b990ed1a --- /dev/null +++ b/platform/runtime/core/core-support/src/main/cfg/generated/fragments.xml @@ -0,0 +1,30 @@ + + + + mvn:ru.entaxy.esb.platform.runtime.core/core-support/1.11.0-SNAPSHOT/cfg/ignite + + diff --git a/platform/runtime/core/error-handling/LICENSE.txt b/platform/runtime/core/error-handling/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/error-handling/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/error-handling/error-handler/LICENSE.txt b/platform/runtime/core/error-handling/error-handler/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/error-handling/error-handler/README.md b/platform/runtime/core/error-handling/error-handler/README.md new file mode 100644 index 00000000..392da85c --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/README.md @@ -0,0 +1,116 @@ +# SYSTEM :: ENTAXY :: CORE :: COMMON ERROR HANDLER + +Централизованный обработчик ошибок для формирования кодов ошибок, их синхронного возврата клиенту и для асинхронного дублирования более подробного описания ошибки (для клиента и для Центральной Базы Интеграции). + +## Установка и настройка +Установка модуля происходит через фичу: +``` +feature:install error-handler +``` +Фича включена в общий установочный скрипт и будет устанавливаться вместе с остальными модулями. +Во время установки фичи в караф копируются файлы конфигурации: +``` +ru.entaxy.esb.error.cfg (основная конфигурация) +ru.entaxy.esb.error.code.cfg (справочник исключений с маппингом на коды ошибок) +ru.entaxy.esb.error.text.cfg (справочник кодов ошибок с маппингом на текстовые сообщения) +``` +Есть возможность настройки маппинга уровней журналирования через файл конфигурации `ru.entaxy.esb.error.severity.cfg`. +### ru.entaxy.esb.error.cfg (основная конфигурация) +``` +# асинхронный пакет с ошибкой отправляется от имени: +# false - системы, вызвавшей ошибку в шине +# true - шины (система с идентификатором "-1") +error.bus.always_at_source=false + +# асинхронный пакет с ошибкой в поле description содержит: +# false - сообщение из маппинга в файле ru.entaxy.esb.error.text.cfg +# true - содержит сообщение, сохранённое в исключении +error.description.exception_message=true + +# имя очереди для отправки пакета с ошибкой при недоступности системы, указанной в свойстве error.system.name +error.queue.name=error + +# имя системы для отправки пакета с ошибкой, подразумевается система ЦБИ +error.system.name=error + +# true - включает в пакет с ошибкой весь stacktrace исключения +error.stacktrace.show=true + +# свойство автоматического запуска тестового маршрута, который при старте модуля бросает исключение java.lang.IllegalArgumentException: Test exception thrown +error.test-route.startup=false +``` +### ru.entaxy.esb.error.code.cfg (справочник исключений с маппингом на коды ошибок) +Справочник содержит соответствие имён классов исключений и http кодов ошибок. И будет наполняться по мере использования шины в разных ситуациях. Для исключения, имя которого ещё не указано в этом файле, будет возвращаться http код `520` (Unknown Error). +``` +DefaultException=520 +com.ctc.wstx.exc.WstxParsingException=400 +java.security.AccessControlException=403 +javax.ws.rs.ForbiddenException=403 +ConnectorNotFound=424 +ru.entaxy.esb.system.common.exception.DefaultException=520 +ProfileNotFound=424 +# и т.д. +``` +### ru.entaxy.esb.error.text.cfg (справочник кодов ошибок с маппингом на текстовые сообщения) +Если в основной конфигурации свойство `error.description.exception_message` установлено в `false`, то описание ошибки отправляется из этого файла в соответствие с кодом http ошибки. +``` +# 1xx: Informational +# 2xx: Success +200=OK + +# 3xx: Redirection +# 4xx: Client Error +400=Bad Request +403=Forbidden +424=Failed Dependency + +# 5xx: Server Error +520=Unknown Error +# и т.д. +``` +## Подключение обработчика ошибок +Для подключения обработчика ошибок к маршрутам какого-либо модуля необходимо выполнить следующие шаги: +1. Добавить в модуль обработки ошибок в директорию `src/main/resources/xslt/operation` новый xslt для формирования ответа с ошибкой. Файл должен называться по имени операции, для которой будет формироваться ответ. Например `sendToJMS.xsl`. +1. Добавить в `camelContext` аттрибут `errorHandlerRef="commonErrorHandler"` и внутри зарегистрировать обработчик и политику повторной доставки: +```xml + + + + + + +``` +Для контекстов, содержащих конечные точки cxf, необходимо: +- через `pom.xml` импортировать интерцептор для перехвата ошибок (SoapFault) +```xml + + ru.entaxy.esb.system.core.common.error.handler.interceptor, + ... + +``` +- добавить интерцептор в `cxfEndpoint` и bean с указанием в первом аргументе идентификатора `camelContext` +```xml + + + + + + + + + + + +``` +- в `camelContext` добавить маршрут +```xml + + + + + + +``` diff --git a/platform/runtime/core/error-handling/error-handler/pom.xml b/platform/runtime/core/error-handling/error-handler/pom.xml new file mode 100644 index 00000000..ff6e9391 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/pom.xml @@ -0,0 +1,48 @@ + + + + 4.0.0 + + + ru.entaxy.platform.core + error-handling + 1.10.0 + + + ru.entaxy.platform.core.error-handling + error-handler + bundle + + ENTAXY :: PLATFORM :: CORE :: ERROR HANDLER + ENTAXY :: PLATFORM :: CORE :: ERROR HANDLER + + + + ru.entaxy.esb.system.core.common.error.handler.interceptor + + + org.apache.commons.lang3.exception, + * + + + + + + + + + ru.entaxy.esb.platform.runtime.core + core-support-runtime-legacy + ${project.version} + + + org.apache.camel + camel-core + + + org.apache.camel + camel-cxf + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/cfg/generated/fragments.xml b/platform/runtime/core/error-handling/error-handler/src/main/cfg/generated/fragments.xml new file mode 100644 index 00000000..61598776 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/cfg/generated/fragments.xml @@ -0,0 +1,13 @@ + + + mvn:ru.entaxy.platform.core.error-handling/error-handler/1.10.0/cfg/ru.entaxy.esb.error + + + + mvn:ru.entaxy.platform.core.error-handling/error-handler/1.10.0/cfg/ru.entaxy.esb.error.code + + + + mvn:ru.entaxy.platform.core.error-handling/error-handler/1.10.0/cfg/ru.entaxy.esb.error.text + + \ No newline at end of file diff --git a/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.cfg b/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.cfg new file mode 100644 index 00000000..439bc4c7 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.cfg @@ -0,0 +1,49 @@ +### +# ~~~~~~licensing~~~~~~ +# karaf-features +# ========== +# 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~~~~~~ +### +# асинхронный пакет с ошибкой отправляется от имени: +# false - системы, вызвавшей ошибку в шине +# true - шины (система с идентификатором "-1") +error.bus.always_at_source=false + +# асинхронный пакет с ошибкой в поле description содержит: +# false - сообщение из маппинга в файле ru.entaxy.esb.error.text.cfg +# true - содержит сообщение, сохранённое в исключении +error.description.exception_message=true + +# имя очереди для отправки пакета с ошибкой при недоступности системы, указанной в свойстве error.system.name +error.queue.name=error + +# имя системы для отправки пакета с ошибкой +error.system.name=error + +# true - включает в асинхронный пакет с ошибкой весь stacktrace исключения +error.asynch.stacktrace.show=true + +# false - включает в синхронный ответ с ошибкой весь stacktrace исключения +error.synch.stacktrace.show=false + +# свойство автоматического запуска тестового маршрута, который при старте модуля бросает исключение java.lang.IllegalArgumentException: Test exception thrown +error.test-route.startup=false diff --git a/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.code.cfg b/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.code.cfg new file mode 100644 index 00000000..881bcb97 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.code.cfg @@ -0,0 +1,48 @@ +### +# ~~~~~~licensing~~~~~~ +# karaf-features +# ========== +# 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~~~~~~ +### +# Справочник содержит соответствие имён классов исключений и http кодов ошибок. +# И будет наполняться по мере использования шины в разных ситуациях. +# Для исключения, имя которого ещё не указано в этом файле, +# будет возвращаться http код 520 (Unknown Error). +# согласование кодов ошибок происходит в https://docs.google.com/spreadsheets/d/1rvRyiSN-khuuRSJenwP5g7Q-ilbctOGCFgDfdM-abEk/edit#gid=1202937725 +DefaultException=520 + +com.ctc.wstx.exc.WstxParsingException=400 + +java.lang.NullPointerException=418 +java.security.AccessControlException=403 + +org.apache.cxf.interceptor.security.AuthenticationException=401 +javax.ws.rs.ForbiddenException=403 +org.apache.cxf.interceptor.security.AccessDeniedException=403 + +org.apache.camel.language.bean.RuntimeBeanExpressionException=500 + +ConnectorNotFound=424 +ru.entaxy.esb.system.common.exception.DefaultException=520 +ProfileNotFound=424 + +java.io.FileNotFoundException=404 diff --git a/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.text.cfg b/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.text.cfg new file mode 100644 index 00000000..87ab4bf4 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/cfg/ru.entaxy.esb.error.text.cfg @@ -0,0 +1,39 @@ +### +# ~~~~~~licensing~~~~~~ +# karaf-features +# ========== +# 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~~~~~~ +### +# 1xx: Informational +# 2xx: Success +200=OK + +# 3xx: Redirection +# 4xx: Client Error +400=Bad Request +401=Unauthorized +403=Forbidden +418=I’m a teapot +424=Failed Dependency + +# 5xx: Server Error +520=Unknown Error diff --git a/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/interceptor/EntaxyCxfFaultInterceptor.java b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/interceptor/EntaxyCxfFaultInterceptor.java new file mode 100644 index 00000000..d03f4aa9 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/interceptor/EntaxyCxfFaultInterceptor.java @@ -0,0 +1,214 @@ +/*- + * ~~~~~~licensing~~~~~~ + * error-handler + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.core.common.error.handler.interceptor; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.endpoint.Endpoint; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Exchange; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.transport.Conduit; +import org.apache.cxf.transport.http.Headers; + +/** + * + * Prepare soap response and send back to calling system. + * Body can be simple string. + * + * Example: + * + * + * + * + * + * + * + * + * append bean to cxf service description + * + * + * + * + * + */ +public class EntaxyCxfFaultInterceptor extends AbstractSoapInterceptor { + + private static final Log LOG = LogFactory.getLog(EntaxyCxfFaultInterceptor.class); + + private final ProducerTemplate template; + /** + * endpoint to custom error handler route for + * preparing soap response + */ + private final String endpointUri; + /** + * wrap with soap envelope + */ + private boolean wrap = false; + /** + * wrapper endpoint, can be custom + */ + private String wrapEndpoint = "direct-vm:soap-wrap"; + /** + * 1 line logging: + * + */ + private boolean log = false; + /** + * use service logging key + */ + private boolean loggingKeyUse = false; + /** + * default header with logging key + */ + private String loggingKeyHeader = "NTX_loggingKey"; + + public EntaxyCxfFaultInterceptor(CamelContext camelContext, String endpointUri) { + super(Phase.POST_PROTOCOL); + this.template = camelContext.createProducerTemplate(); + this.endpointUri = endpointUri; + } + + public void handleMessage(SoapMessage message) { + LOG.debug("EntaxyCxfFaultInterceptor.handleMessage invocation"); + Map headers = prepareHeaders(message); + logging(headers); + String response = template.requestBodyAndHeaders(this.endpointUri, "", headers, String.class); + if (wrap) { + response = template.requestBodyAndHeaders(this.wrapEndpoint, response, headers, String.class); + } + LOG.debug("EntaxyCxfFaultInterceptor.handleMessage result from camel: \n" + response); + sendErrorResponse(message, 200, response, headers); + } + + protected void logging(Map headers) { + if (log) { + Fault fault = (Fault) headers.get("NTX_ERROR_HANDLER_SoapFault"); + StringBuilder errorMessage = new StringBuilder(); + if (loggingKeyUse && headers.get(loggingKeyHeader) != null) { + errorMessage.append(headers.get(loggingKeyHeader)); + errorMessage.append(" "); + } + errorMessage.append(fault.getCause().getMessage()); + LOG.error(errorMessage); + } + } + + protected Map prepareHeaders(SoapMessage message) { + Map> inHeaders = Headers.getSetProtocolHeaders(message); + + Map headers = new HashMap<>(); + Object value; + for (Map.Entry> e : inHeaders.entrySet()) { + if (e.getValue() != null && e.getValue().size() == 1 && e.getValue().get(0) instanceof String) { + value = e.getValue().get(0); + } else { + value = e.getValue(); + } + headers.put(e.getKey(), value); + } + + Fault fault = (Fault) message.getContent(Exception.class); + headers.put("NTX_ERROR_HANDLER_SoapFault", fault); + return headers; + } + + + protected void sendErrorResponse(Message message, int responseCode, String ret, Map headers) { + Message outMessage = getOutMessage(message); + outMessage.put(Message.ENCODING, StandardCharsets.UTF_8.name()); + outMessage.put(Message.RESPONSE_CODE, responseCode); + // Clear the response headers + @SuppressWarnings("rawtypes") + Map responseHeaders = (Map) outMessage.get(Message.PROTOCOL_HEADERS); + if (responseHeaders != null) { + responseHeaders.clear(); + } + message.getInterceptorChain().abort(); + try { + getConduit(message).prepare(outMessage); + write(outMessage, ret); + } catch (IOException e) { + LOG.warn(e.getMessage(), e); + } + } + + protected Message getOutMessage(Message inMessage) { + Exchange exchange = inMessage.getExchange(); + Message outMessage = exchange.getOutMessage(); + if (outMessage == null) { + Endpoint endpoint = exchange.get(Endpoint.class); + outMessage = endpoint.getBinding().createMessage(); + exchange.setOutMessage(outMessage); + } + outMessage.putAll(inMessage); + return outMessage; + } + + protected Conduit getConduit(Message inMessage) throws IOException { + Exchange exchange = inMessage.getExchange(); + Conduit conduit = exchange.getDestination().getBackChannel(inMessage); + exchange.setConduit(conduit); + return conduit; + } + + protected void write(Message outMessage, String ret) throws IOException { + try (OutputStream os = outMessage.getContent(OutputStream.class);) { + os.write(ret.getBytes(StandardCharsets.UTF_8)); + os.flush(); + } + } + + public void setWrap(boolean wrap) { + this.wrap = wrap; + } + public void setWrapEndpoint(String wrapEndpoint) { + this.wrapEndpoint = wrapEndpoint; + } + public void setLog(boolean log) { + this.log = log; + } + public void setLoggingKeyUse(boolean loggingKeyUse) { + this.loggingKeyUse = loggingKeyUse; + } + public void setLoggingKeyHeader(String loggingKeyHeader) { + this.loggingKeyHeader = loggingKeyHeader; + } + +} diff --git a/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/interceptor/HandleOutFaultInterceptor.java b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/interceptor/HandleOutFaultInterceptor.java new file mode 100644 index 00000000..9e467f21 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/interceptor/HandleOutFaultInterceptor.java @@ -0,0 +1,155 @@ +/*- + * ~~~~~~licensing~~~~~~ + * error-handler + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.core.common.error.handler.interceptor; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.cxf.common.message.CxfConstants; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.interceptor.AbstractSoapInterceptor; +import org.apache.cxf.endpoint.Endpoint; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Exchange; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.transport.Conduit; +import org.apache.cxf.transport.http.Headers; + +import ru.entaxy.esb.system.common.util.SystemHeadersConstants; + +public class HandleOutFaultInterceptor extends AbstractSoapInterceptor { + private static final Log LOG = LogFactory.getLog(HandleOutFaultInterceptor.class); + + private final ProducerTemplate template; + private final String endpointUri; + + public HandleOutFaultInterceptor(CamelContext camelContext, String endpointUri) { + super(Phase.POST_PROTOCOL); + this.template = camelContext.createProducerTemplate(); + this.endpointUri = endpointUri; + } + + + public void handleMessage(SoapMessage message) { + LOG.debug("HandleOutFaultInterceptor.handleMessage invocation"); + // String inMessage = message.getExchange().getInMessage().getContent(String.class); + // Fault fault = (Fault) message.getContent(Exception.class); + Map headers = prepareHeaders(message); + String response = template.requestBodyAndHeaders(this.endpointUri, "", headers, String.class); + LOG.debug("HandleOutFaultInterceptor.handleMessage result from camel: \n" + response); + sendErrorResponse(message, 200, response); + } + + private Map prepareHeaders(SoapMessage message) { + Fault fault = (Fault) message.getContent(Exception.class); + Map headers = new HashMap(); + headers.put("NTX_ERROR_HANDLER_SoapFault", fault); + // headers.put("ERROR_HANDLER_EXCEPTION", fault.getCause()); + // headers.put("NTX_ERROR_HANDLER_ExceptionClass", fault.getCause().getClass().getName()); + // headers.put("NTX_ERROR_HANDLER_ExceptionMessage", fault.getCause().getMessage()); + headers.put(CxfConstants.OPERATION_NAME, getOperationName(message)); + try { + addSystemHeaders(message, headers); + } catch (Exception e) { + LOG.info("Unable to add source system information to headers in HandleOutFaultInterceptor"); + } + return headers; + } + + private void addSystemHeaders(SoapMessage message, Map headers) { + Message inMessage = message.getExchange().getInMessage(); + Map> inHeaders = Headers.getSetProtocolHeaders(inMessage); + headers.put(SystemHeadersConstants.HEADER_SYSTEM_NAME, + inHeaders.get(SystemHeadersConstants.HEADER_SYSTEM_NAME).get(0)); + headers.put(SystemHeadersConstants.HEADER_SYSTEM_ID, + inHeaders.get(SystemHeadersConstants.HEADER_SYSTEM_ID).get(0)); + } + + private String getOperationName(SoapMessage message) { + String operation = ""; + try { + operation = message.getExchange().getBindingOperationInfo().getOperationInfo().getName().getLocalPart(); + } catch (Exception e) { + LOG.error(e); + } + LOG.debug("operation name: " + operation); + return operation; + } + + private void sendErrorResponse(Message message, int responseCode, String ret) { + Message outMessage = getOutMessage(message); + outMessage.put(Message.RESPONSE_CODE, responseCode); + // Set the response headers + Map responseHeaders = (Map) outMessage.get(Message.PROTOCOL_HEADERS); + if (responseHeaders != null) { + responseHeaders.clear(); + responseHeaders.put("CAMEL_ERROR", Arrays.asList(ret)); + } + message.getInterceptorChain().abort(); + try { + getConduit(message).prepare(outMessage); + write(outMessage, ret); + } catch (IOException e) { + LOG.warn(e.getMessage(), e); + } + } + + private Message getOutMessage(Message inMessage) { + Exchange exchange = inMessage.getExchange(); + Message outMessage = exchange.getOutMessage(); + if (outMessage == null) { + Endpoint endpoint = exchange.get(Endpoint.class); + outMessage = endpoint.getBinding().createMessage(); + exchange.setOutMessage(outMessage); + } + outMessage.putAll(inMessage); + return outMessage; + } + + private Conduit getConduit(Message inMessage) throws IOException { + Exchange exchange = inMessage.getExchange(); + Conduit conduit = exchange.getDestination().getBackChannel(inMessage); + exchange.setConduit(conduit); + return conduit; + } + + private void write(Message outMessage, String ret) throws IOException { + OutputStream os = outMessage.getContent(OutputStream.class); + os.write(ret.getBytes(StandardCharsets.UTF_8)); + os.flush(); + os.close(); + } +} diff --git a/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/processor/ErrorProcessor.java b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/processor/ErrorProcessor.java new file mode 100644 index 00000000..439f9446 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/processor/ErrorProcessor.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * error-handler + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.core.common.error.handler.processor; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.ProducerTemplate; + +public class ErrorProcessor implements Processor { + + @Override + public void process(Exchange exchange) throws Exception { + + String body = exchange.getIn().getBody(String.class); + Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class); + exchange.getIn().setBody("ErrorProcessor: \n" + cause.getMessage()); + + ProducerTemplate template = exchange.getContext().createProducerTemplate(); +// template.send("xslt:xslt/CreateUniversalErrorPacket.xsl", exchange); + template.send("direct-vm:commonErrorEndpoint", exchange); + } +} diff --git a/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/util/Timestamp.java b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/util/Timestamp.java new file mode 100644 index 00000000..32ecfbad --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/java/ru/entaxy/esb/system/core/common/error/handler/util/Timestamp.java @@ -0,0 +1,36 @@ +/*- + * ~~~~~~licensing~~~~~~ + * error-handler + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.core.common.error.handler.util; + +public class Timestamp { + public String currentTimeMillis(String body) { + return String.valueOf(System.currentTimeMillis()); + } + + public String unixTime(String body) { + return String.valueOf(System.currentTimeMillis() / 1000L); + } +} diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/OSGI-INF/blueprint/common-error-handler-context.xml b/platform/runtime/core/error-handling/error-handler/src/main/resources/OSGI-INF/blueprint/common-error-handler-context.xml new file mode 100644 index 00000000..9a565af9 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/OSGI-INF/blueprint/common-error-handler-context.xml @@ -0,0 +1,482 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Oops... some test error occurred]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ]]> + + + + + + + + ${headers.NTX_ERROR_HANDLER_GenerateResponseEndpoint} != null + + + + ${headers.NTX_ERROR_HANDLER_SYNC_TYPE} == "application/json" + + + + + + + + + + + + + + + + ${properties:error.asynch.stacktrace.show} + + + ${properties:error.synch.stacktrace.show} + + + + ${exception} != null + + ${exception.class.name} + + + ${exception.message} + + + + ${header.NTX_ERROR_HANDLER_asynch_Stacktrace} == "true" || ${header.NTX_ERROR_HANDLER_synch_Stacktrace} == "true" + + + ${exception.stacktrace} + + + + + ${header.NTX_ERROR_HANDLER_SoapFault} != null + + ${header.NTX_ERROR_HANDLER_SoapFault.cause.class.name} + + + ${header.NTX_ERROR_HANDLER_SoapFault.cause.message} + + + + ${header.NTX_ERROR_HANDLER_asynch_Stacktrace} == "true" || ${header.NTX_ERROR_HANDLER_synch_Stacktrace} == "true" + + + ${body} + + + + ${body} + + + ${exchangeProperty.bodyHolder} + + + + + + ru.entaxy.esb.system.common.exception.DefaultException + + + Something wrong + + + + + + ${header.NTX_ERROR_HANDLER_ExceptionClass} + + + ${properties:${header.NTX_ERROR_HANDLER_ExceptionClass}} + + + java.lang.Exception + + + ${properties:ru.entaxy.esb.system.common.exception.DefaultException} + + + + + + + + ${properties:error.description.exception_message} == "true" + + ${header.NTX_ERROR_HANDLER_ExceptionMessage} + + + + + ${properties:${header.NTX_ERROR_HANDLER_ResponseCode}} + + + + + + + + + + + + + + + + + + + + java.lang.Exception + + + + + + + + + + ${headers.X-SystemName} != "esb" + + + + java.lang.Exception + + + + + + + + + + + + + + + + esb + + + + + + + + ${bean:uuidGenerator.toString} + + + ВыгрузкаДанныхКаноническийФормат + + + application/xml + + + String + + + xs:string + + + + + + + + ${properties:error.system.name} + + + + + ${headers.ENTAXY_Source} != null && ${headers.ENTAXY_Source} != "" + + + ${headers.ENTAXY_Source} + + + ${headers.ENTAXY_Source} + + + + ${headers.NTX_SystemId} != null && ${headers.NTX_SystemId} != "" + + ${headers.NTX_SystemId} + + + ${headers.NTX_SystemId} + + + + ${headers.X-SystemName} != null && ${headers.X-SystemName} != "" + + ${headers.X-SystemName} + + + ${headers.X-SystemName} + + + + + esb + + + esb + + + + + + ${headers.X-SystemName} == null || ${headers.X-SystemName} == "" + + esb + + + + + + ${headers.X-SystemId} == null || ${headers.X-SystemId} == "" + + -1 + + + + + + ${properties:error.bus.always_at_source} == "true" + + esb + + + esb + + + -1 + + + + + + ${bean:uuidGenerator.toString} + + + + ${bean:timestamp?method=currentTimeMillis} + + + ${headers.NTX_ERROR_HANDLER_SeverityLevel} == null + + ERROR + + + + + + + + ]]> + + + + + ${headers.operationName} + + + + java.lang.Exception + + + + + + + + + + + + + + + + ${headers.operationName} + + + + + java.lang.Exception + + + + + + + + + + + + + + + + + + java.lang.Exception + + + + + ${body} + + + ${null} + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/ftl/DefaultResponse.ftl b/platform/runtime/core/error-handling/error-handler/src/main/resources/ftl/DefaultResponse.ftl new file mode 100644 index 00000000..244321ed --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/ftl/DefaultResponse.ftl @@ -0,0 +1,48 @@ +[#-- + + ~~~~~~licensing~~~~~~ + error-handler + ========== + 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~~~~~~ + +--] +{ + "status" : "[=headers.NTX_ERROR_HANDLER_ResponseCode]" +[#if headers.NTX_ERROR_HANDLER_ResponseText?has_content] + , "description" : "[=headers.NTX_ERROR_HANDLER_ResponseText]" +[/#if] +[#if headers.NTX_ERROR_HANDLER_synch_Stacktrace == "true" && headers.NTX_ERROR_HANDLER_Stacktrace?has_content] + , "stacktrace" : "[=headers.NTX_ERROR_HANDLER_Stacktrace]" +[/#if] +} \ No newline at end of file diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/DefaultResponse.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/DefaultResponse.xsl new file mode 100644 index 00000000..01f35b40 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/DefaultResponse.xsl @@ -0,0 +1,54 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/UniversalErrorPacket.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/UniversalErrorPacket.xsl new file mode 100644 index 00000000..371339f7 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/UniversalErrorPacket.xsl @@ -0,0 +1,110 @@ + + + + + + + + + + + + + + + + + + + + + + + +
+ http://www.entaxy.ru/ServiceInterface/1.0 + 2020-05-20T07:19:59 + 1 +
+ + <Справочник.События> + <КлючевыеСвойства> + <Ссылка> + + + + + + + + + + + + + + + + + + + + Packet.Validation + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/WrapSoapEnvelope.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/WrapSoapEnvelope.xsl new file mode 100644 index 00000000..0468b6a8 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/WrapSoapEnvelope.xsl @@ -0,0 +1,37 @@ + + + + + + + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/ConfirmGettingPackets.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/ConfirmGettingPackets.xsl new file mode 100644 index 00000000..71cb020c --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/ConfirmGettingPackets.xsl @@ -0,0 +1,36 @@ + + + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/GetPackets.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/GetPackets.xsl new file mode 100644 index 00000000..71cb020c --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/GetPackets.xsl @@ -0,0 +1,36 @@ + + + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/PutPackets.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/PutPackets.xsl new file mode 100644 index 00000000..71cb020c --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/PutPackets.xsl @@ -0,0 +1,36 @@ + + + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/sendAcknowledge.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/sendAcknowledge.xsl new file mode 100644 index 00000000..96dc365d --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/sendAcknowledge.xsl @@ -0,0 +1,30 @@ + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/sendToJMS.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/sendToJMS.xsl new file mode 100644 index 00000000..96dc365d --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/sendToJMS.xsl @@ -0,0 +1,30 @@ + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/type/response.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/type/response.xsl new file mode 100644 index 00000000..a83c97aa --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/operation/type/response.xsl @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + diff --git a/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/soapWrap.xsl b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/soapWrap.xsl new file mode 100644 index 00000000..65a1e209 --- /dev/null +++ b/platform/runtime/core/error-handling/error-handler/src/main/resources/xslt/soapWrap.xsl @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/error-handling/pom.xml b/platform/runtime/core/error-handling/pom.xml new file mode 100644 index 00000000..aa415994 --- /dev/null +++ b/platform/runtime/core/error-handling/pom.xml @@ -0,0 +1,18 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime + core + 1.10.0 + + ru.entaxy.platform.core + error-handling + pom + ENTAXY :: PLATFORM :: CORE :: ERROR HANDLING + ENTAXY :: PLATFORM :: CORE :: ERROR HANDLING + + + error-handler + + + diff --git a/platform/runtime/core/infrastructure/file-upload/LICENSE.txt b/platform/runtime/core/infrastructure/file-upload/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/infrastructure/file-upload/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/infrastructure/file-upload/pom.xml b/platform/runtime/core/infrastructure/file-upload/pom.xml new file mode 100644 index 00000000..a6547f23 --- /dev/null +++ b/platform/runtime/core/infrastructure/file-upload/pom.xml @@ -0,0 +1,50 @@ + + + 4.0.0 + + + ru.entaxy.esb.platform.runtime.core + infrastructure + 1.10.0 + + + ru.entaxy.platform.core.infrastructure + file-upload + bundle + + ENTAXY :: CORE :: INFRASTRUCTURE :: FILE UPLOAD + ENTAXY :: CORE :: INFRASTRUCTURE :: FILE UPLOAD + + + + org.apache.cxf.jaxrs.impl, + org.apache.camel.component.cxf.jaxrs.blueprint, + org.apache.camel.component.cxf.blueprint, + * + + + + + + + org.apache.camel + camel-cxf + + + + org.osgi + org.osgi.service.component.annotations + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + ru.entaxy.esb.platform.runtime.base.resources + resources-api + ${project.version} + + + + diff --git a/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadProcessor.java b/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadProcessor.java new file mode 100644 index 00000000..baebe637 --- /dev/null +++ b/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadProcessor.java @@ -0,0 +1,79 @@ +/*- + * ~~~~~~licensing~~~~~~ + * file-upload + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.management.file.upload; +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceService; + +import javax.activation.DataHandler; +import javax.ws.rs.core.MultivaluedMap; +import java.io.InputStream; + +public class FileUploadProcessor implements Processor { + + private static final Logger log = LoggerFactory.getLogger(FileUploadProcessor.class); + + private EntaxyResourceService entaxyResourceService; + + public void setEntaxyResourceService(EntaxyResourceService entaxyResourceService) { + this.entaxyResourceService = entaxyResourceService; + } + + @Override + public void process(Exchange exchange) throws Exception { + Attachment attachment = exchange.getIn().getBody(Attachment.class); + DataHandler dataHandler = attachment.getDataHandler(); + + InputStream inputStream = null; + EntaxyResource entaxyResource = null; + + try { + MultivaluedMap map = attachment.getHeaders(); + + inputStream = dataHandler.getInputStream(); + + String protocol = (String) exchange.getIn().getHeader("protocol"); + String path = (String) exchange.getIn().getHeader("path"); + String location = protocol + ":" + path; + + entaxyResource = entaxyResourceService.getResource(location); + + /* For now we allow resource reloading */ + // if (!entaxyResource.exists()) { + entaxyResource.save(inputStream); + // } + } catch (Exception e) { + log.error("Error while uploading file: " + e.getMessage()); + } finally { + inputStream.close(); + } + exchange.getMessage().setBody(entaxyResource.getName()); + } +} diff --git a/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadService.java b/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadService.java new file mode 100644 index 00000000..8f0fbce1 --- /dev/null +++ b/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadService.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * file-upload + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.management.file.upload; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +@Path("/") +public interface FileUploadService { + + @POST + @Path("/upload/file") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.TEXT_PLAIN) + public String uploadFile(Attachment attachment); + + @POST + @Path("/upload/resource") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.TEXT_PLAIN) + public String uploadResource( + @Multipart(value = "protocol") String protocol, + @Multipart(value = "path") String path, + @Multipart(value = "file") Attachment attachment + ); +} diff --git a/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadServiceImpl.java b/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadServiceImpl.java new file mode 100644 index 00000000..614ee863 --- /dev/null +++ b/platform/runtime/core/infrastructure/file-upload/src/main/java/ru/entaxy/esb/system/management/file/upload/FileUploadServiceImpl.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * file-upload + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.management.file.upload; + +import org.apache.cxf.jaxrs.ext.multipart.Attachment; +import org.apache.cxf.jaxrs.ext.multipart.Multipart; + +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; + +@Path("/") +public class FileUploadServiceImpl { + + @POST + @Path("/post") + @Consumes(MediaType.MULTIPART_FORM_DATA) + @Produces(MediaType.TEXT_PLAIN) + public String uploadFile(@Multipart(value = "file") Attachment attachment) { + return "I got it"; + }; +} diff --git a/platform/runtime/core/infrastructure/file-upload/src/main/resources/OSGI-INF/blueprint/camel-context.xml b/platform/runtime/core/infrastructure/file-upload/src/main/resources/OSGI-INF/blueprint/camel-context.xml new file mode 100644 index 00000000..2f0b5401 --- /dev/null +++ b/platform/runtime/core/infrastructure/file-upload/src/main/resources/OSGI-INF/blueprint/camel-context.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/initializer/artifact-loader/LICENSE.txt b/platform/runtime/core/initializer/artifact-loader/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/initializer/artifact-loader/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/initializer/artifact-loader/pom.xml b/platform/runtime/core/initializer/artifact-loader/pom.xml new file mode 100644 index 00000000..ae471848 --- /dev/null +++ b/platform/runtime/core/initializer/artifact-loader/pom.xml @@ -0,0 +1,35 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + initializer + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.initializer + artifact-loader + bundle + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: INITIALIZER :: artifact loader + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: INITIALIZER :: artifact loader + + + + ru.entaxy.platform.initializer.artifactloader + + + + + + ru.entaxy.esb.platform.runtime.core.initializer + init-manager + ${project.version} + compile + + + ru.entaxy.esb.platform.runtime.core + artifact-management + ${project.version} + + + + + diff --git a/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactDeployer.java b/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactDeployer.java new file mode 100644 index 00000000..fb99c2be --- /dev/null +++ b/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactDeployer.java @@ -0,0 +1,255 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-loader + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.initializer.artifactloader; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.WatchEvent; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.runtime.core.initializer.api.Initialized; +import ru.entaxy.platform.base.support.SimpleFileWatcher; +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.Artifacts; +import ru.entaxy.platform.core.artifact.DeployedArtifact; +import ru.entaxy.platform.core.artifact.service.ArtifactService; + +@Component(service = ArtifactDeployer.class, immediate = true) +public class ArtifactDeployer implements SimpleFileWatcher.WatcherCallback { + + public static final Logger log = LoggerFactory.getLogger(ArtifactDeployer.class); + + public static final String ROOT_PATH = "init/artifacts"; + + public static final String LOCAL_PATH = "local"; + + public static final String SHARED_PATH = "shared"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY, target = "(id=repositories)") + volatile Initialized repositoriesInitializedMarker; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ArtifactService artifactService; + + protected ExecutorService executor = Executors.newSingleThreadExecutor(); + + protected SimpleFileWatcher artifactWatcher = null; + + protected Path rootPath; + + protected static Map sources = new HashMap<>(); + + protected static Map pathPrefixes = new HashMap<>(); + + @Activate + public void activate() { + + sources.put(LOCAL_PATH, false); + sources.put(SHARED_PATH, true); + + } + + public void start() { + + Path watchPath = Paths.get(System.getProperty("karaf.etc"), ROOT_PATH); + try { + artifactWatcher = new SimpleFileWatcher(watchPath); + artifactWatcher.setWatcherCallback(this); + executor.submit(artifactWatcher); + } catch (IOException e) { + log.error("FAILED creating file watcher for ArtifactDeployer", e); + } + + // do the initial job + + File rootFolder = new File(System.getProperty("karaf.etc")); + if (rootFolder.exists()) { + rootPath = Paths.get(rootFolder.getAbsolutePath(), ROOT_PATH); + log.debug("\n\t-->> Root path: [{}]", rootPath.toString()); + + for (Entry entry : sources.entrySet()) { + Path currentPath = Paths.get(rootPath.toString(), entry.getKey()); + pathPrefixes.put(currentPath.toAbsolutePath().toString(), entry.getValue()); + } + + scan(rootPath); + + } + + } + + protected static String getPrefix(File f) { + String filePath = f.getAbsolutePath(); + for (String prefix : pathPrefixes.keySet()) + if (filePath.startsWith(prefix)) + return prefix; + return null; + } + + protected static class FileData { + + public File file; + public String prefix; + public boolean isShared; + + public Artifact artifact; + + public DeployedArtifact deployedArtifact; + + public FileData(File f) { + file = f; + prefix = getPrefix(f); + isShared = pathPrefixes.getOrDefault(prefix, false); + } + + public FileData setArtifact(Artifact artifact) { + this.artifact = artifact; + return this; + } + + public FileData setDeployedArtifact(DeployedArtifact deployedArtifact) { + this.deployedArtifact = deployedArtifact; + return this; + } + + + + } + + protected void scan(Path pathToScan) { + + if (!pathToScan.toFile().exists() || !pathToScan.toFile().isDirectory()) + return; + + log.info("SCANNING: [{}]", pathToScan); + + try (Stream pathStream = Files.walk(pathToScan)) { + List fileDataList = pathStream + .map(p -> p.toFile()) + .filter(f -> f.exists()) + .filter(f -> !f.isDirectory()) + .map(f -> new FileData(f)) + .filter(fd -> fd.prefix != null) + .map(fd -> fd.setArtifact(Artifacts.fromFile(fd.file, fd.prefix))) + .filter(fd -> fd.artifact != null) + .collect(Collectors.toList()); + List deployed = fileDataList.stream() + .map(fd -> fd.setDeployedArtifact(fd.isShared ? artifactService.deployShared(fd.artifact) + : artifactService.deployLocal(fd.artifact))) + .filter(fd -> (fd.deployedArtifact != null)) + .collect(Collectors.toList()); + for (FileData fd : deployed) + log.info("Deployed [initial] {} artifact: [{}]", fd.isShared ? "shared" : "local", + fd.deployedArtifact.getLocation()); + } catch (IOException e) { + log.error("Error processing files", e); + } + + } + + @Deactivate + public void deactivate() { + executor.shutdown(); + if (artifactWatcher != null) { + artifactWatcher.close(); + } + } + + /* -- WatcherCallback implementation */ + + @SuppressWarnings("unchecked") + @Override + public void fileCreated(WatchEvent event, Path directory) { + Path name = ((WatchEvent) event).context(); + Path fileFullPath = directory.resolve(name); + + Path fileRelPath = rootPath.relativize(fileFullPath); + Path fileRelTargetPath = null; + Path fileRootPath = null; + + boolean deployShared = true; + + // check if it's shared artifact + if (fileRelPath != null && fileRelPath.toString().startsWith(SHARED_PATH)) { + fileRootPath = Paths.get(rootPath.toString(), SHARED_PATH); + try { + fileRelPath = fileRootPath.relativize(fileFullPath); + log.debug("NEW SHARED FILE: [{}] -> [{}]", fileFullPath, fileRelPath); + } catch (IllegalArgumentException ignore) { + // not shared artifact + } + } else if (fileRelPath != null && fileRelPath.toString().startsWith(LOCAL_PATH)) { + fileRootPath = Paths.get(rootPath.toString(), LOCAL_PATH); + try { + fileRelPath = fileRootPath.relativize(fileFullPath); + log.debug("NEW SHARED FILE: [{}] -> [{}]", fileFullPath, fileRelPath); + deployShared = false; + } catch (IllegalArgumentException ignore) { + // not shared artifact + } + } else { + log.warn("File NOT LOCAL or SHARED -> ingoring: [{}]", fileFullPath); + return; + } + + Artifact artifact = Artifacts.fromFile(fileFullPath.toFile(), fileRootPath.toString()); + DeployedArtifact deployedArtifact = + deployShared ? artifactService.deployShared(artifact) : artifactService.deployLocal(artifact); + log.info("Deployed {} artifact: [{}]", deployShared ? "shared" : "local", deployedArtifact.getLocation()); + } + + @Override + public void directoryCreated(WatchEvent event, Path directory) { + + Path name = ((WatchEvent) event).context(); + Path dirFullPath = directory.resolve(name); + + log.info("DIRECTORY CREATED: [{}]", dirFullPath.toAbsolutePath().toString()); + + scan(dirFullPath); + } +} diff --git a/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactInstaller.java b/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactInstaller.java new file mode 100644 index 00000000..7fcf6d7e --- /dev/null +++ b/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactInstaller.java @@ -0,0 +1,369 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-loader + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.initializer.artifactloader; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.WatchEvent; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.apache.camel.tooling.model.Strings; +import org.apache.felix.utils.properties.Properties; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.SimpleFileWatcher; +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.ArtifactCoordinates; +import ru.entaxy.platform.core.artifact.Artifacts; +import ru.entaxy.platform.core.artifact.DeployedArtifact; +import ru.entaxy.platform.core.artifact.installer.builder.InstallationResult; +import ru.entaxy.platform.core.artifact.installer.builder.Installer; +import ru.entaxy.platform.core.artifact.installer.builder.typed.CommonBundleInstaller; +import ru.entaxy.platform.core.artifact.repository.impl.DeployedArtifactImpl; +import ru.entaxy.platform.core.artifact.service.ArtifactService; + +@Component(service = ArtifactInstaller.class, immediate = true) +public class ArtifactInstaller implements SimpleFileWatcher.WatcherCallback { + + public static final Logger log = LoggerFactory.getLogger(ArtifactInstaller.class); + + public static final String ROOT_PATH = "init/install"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + protected ArtifactService artifactService; + + protected ExecutorService watchExecutor = Executors.newSingleThreadExecutor(); + + protected ExecutorService installExecutor = Executors.newCachedThreadPool(); + + protected boolean installThreadIsRunning = false; + + protected Object installThreadLock = new Object(); + + // protected List currentTasks = Collections.synchronizedList(new + // ArrayList<>()); + + protected final Map currentTasks = new HashMap<>(); + + protected final Object currentTasksLock = new Object(); + + protected SimpleFileWatcher installPropertiesWatcher = null; + + protected Path rootPath; + + + @Activate + public void activate() { + watchExecutor = Executors.newSingleThreadExecutor(); + installExecutor = Executors.newCachedThreadPool(); + } + + @Deactivate + public void deactivate() { + watchExecutor.shutdown(); + installExecutor.shutdown(); + } + + public void start() { + + rootPath = Paths.get(System.getProperty("karaf.etc"), ROOT_PATH); + + try { + installPropertiesWatcher = new SimpleFileWatcher(rootPath); + installPropertiesWatcher.setWatcherCallback(this); + watchExecutor.submit(installPropertiesWatcher); + } catch (IOException e) { + log.error("FAILED creating file watcher for ArtifactDeployer", e); + } + + // do the initial job + + try (Stream pathStream = Files.walk(rootPath)) { + List fileList = pathStream + .map(p -> p.toFile()) + .filter(f -> f.exists()) + .filter(f -> !f.isDirectory()) + .collect(Collectors.toList()); + for (File f : fileList) { + log.debug("INITIAL processing file: " + f.getAbsolutePath()); + List tasks = parseProperties(f.getAbsoluteFile().toPath()); + if (tasks != null && !tasks.isEmpty()) + submitTasks(tasks); + } + + } catch (Exception e) { + log.error("Error processing files", e); + } + + + } + + protected List parseProperties(Path propertiesFile) { + + List result = new ArrayList<>(); + + Properties properties; + try { + + List lines = Files.readAllLines(propertiesFile); + + for (String line : lines) { + if (Strings.isNullOrEmpty(line)) + continue; + if (line.startsWith("#")) + continue; + String[] parsed = line.split("="); + if (parsed.length < 2) { + log.warn("incorrect line [{}] in file [{}]", line, propertiesFile); + continue; + } + String url = parsed[0].trim(); + String paramsData = parsed[1].trim(); + InstallationTask task = InstallationTask.parseParams(paramsData); + task.artifactUrl = url; + task.createArtifacts(); + result.add(task); + } + + /* + properties = new Properties(propertiesFile.toFile()); + + for (Entry entry : properties.entrySet()) { + String url = entry.getKey(); + String paramsData = entry.getValue(); + InstallationTask task = InstallationTask.parseParams(paramsData); + task.artifactUrl = url; + task.createArtifacts(); + result.add(task); + } + */ + } catch (IOException e) { + log.error("Failed reading file [" + propertiesFile.toString() + "]", e); + } + + return result; + + } + + protected void submitTasks(List tasks) { + log.debug("SUBMITTING TASKS: " + tasks.size()); + int newTasks = 0; + synchronized (currentTasksLock) { + for (InstallationTask task : tasks) + if (!this.currentTasks.containsKey(task.artifactUrl)) { + this.currentTasks.putIfAbsent(task.artifactUrl, task); + newTasks++; + } + } + log.debug("TOTAL TASKS: " + this.currentTasks.size() + "; NEW TASKS: " + newTasks); + if (newTasks == 0) + return; + synchronized (installThreadLock) { + if (!installThreadIsRunning) { + log.debug("STARTING INSTALLER"); + startInstaller(); + } else { + log.debug("INSTALLER ALREADY STARTED"); + } + } + } + + protected void startInstaller() { + if (installExecutor.isTerminated() || installExecutor.isShutdown()) { + log.debug("INSTALLER IS TERMINATED -> RECREATING"); + installExecutor = Executors.newCachedThreadPool(); + } + + installExecutor.submit(new InstallerWorker()); + } + + /* -- WatcherCallback implementation */ + + @Override + public void fileCreated(WatchEvent event, Path directory) { + Path name = ((WatchEvent) event).context(); + Path fileFullPath = directory.resolve(name); + List tasks = parseProperties(fileFullPath); + if (tasks != null && !tasks.isEmpty()) + submitTasks(tasks); + } + + protected class InstallerWorker implements Runnable { + + @Override + public void run() { + + synchronized (installThreadLock) { + if (installThreadIsRunning) { + log.debug(" >> ANOTHER THREAD IS ALREADY RUNNING"); + return; + } + installThreadIsRunning = true; + } + + List completed = new ArrayList<>(); + + List expired = new ArrayList<>(); + + log.debug(" >> TOTAL TASKS: " + currentTasks.size()); + + Map localMap = new HashMap<>(); + + synchronized (currentTasksLock) { + localMap.putAll(currentTasks); + } + + while (!localMap.isEmpty()) { + + for (InstallationTask task : localMap.values()) { + + log.debug(" >> EXECUTING task for [{}]", task.artifactUrl); + + Installer installer = task.installShared ? artifactService.installers().cluster() + : artifactService.installers().local(); + + installer.artifact(task.deployedArtifact); + + CommonBundleInstaller bundleInstaller = installer.typed(CommonBundleInstaller.class); + InstallationResult result = + bundleInstaller.installOnlyIfMissing() + .forceInstall() + .start().startLevel(task.startLevel).install(); + + if (result != null && result.isSuccessful()) { + completed.add(task); + log.info("Successfully installed: [{}]", task.artifactUrl); + } else { + task.retriesCount--; + if (task.retriesCount <= 0) { + expired.add(task); + log.warn("Installation failed: expired: [{}]", task.artifactUrl); + if (!result.isSuccessful() && CommonUtils.isValid(result.getMessage())) + log.error("Installation error for [{}]: {}", task.artifactUrl, result.getMessage()); + + } + } + + } + + synchronized (currentTasksLock) { + for (InstallationTask task : completed) + currentTasks.remove(task.artifactUrl); + for (InstallationTask task : expired) + currentTasks.remove(task.artifactUrl); + log.debug(" >> TOTAL TASKS LEFT: " + currentTasks.size()); + localMap.clear(); + localMap.putAll(currentTasks); + } + + if (localMap.isEmpty()) { + log.debug(" >> EXITING"); + break; + } else { + log.debug(" >> CONTINUE"); + } + + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + log.debug("Interrupted"); + } + } + synchronized (installThreadLock) { + installThreadIsRunning = false; + } + + } + + } + + protected static class InstallationTask { + + protected static final String SHARED_TARGET = "shared"; + + public static InstallationTask parseParams(String data) { + InstallationTask result = new InstallationTask(); + + String[] values = data.split(";"); + result.installShared = values[0].equals(SHARED_TARGET); + + if (values.length > 1) + result.artifactCategory = values[1].trim(); + + if (values.length > 2) + try { + result.startLevel = Integer.parseInt(values[2].trim()); + } catch (Exception ignore) { + + } + + return result; + } + + String artifactUrl = ""; + + boolean installShared = true; + + String artifactCategory = "jar"; + + int startLevel = 100; + + Artifact artifact; + + DeployedArtifact deployedArtifact; + + int retriesCount = 100; + + public void createArtifacts() { + + Artifact artifact = Artifacts.create(artifactCategory); + + artifact.getCoordinates().set(ArtifactCoordinates.fromUrl(artifactUrl)); + + deployedArtifact = new DeployedArtifactImpl(artifact, "mvn:" + artifactUrl); + + } + + } + +} diff --git a/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactLoader.java b/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactLoader.java new file mode 100644 index 00000000..64a19618 --- /dev/null +++ b/platform/runtime/core/initializer/artifact-loader/src/main/java/ru/entaxy/platform/initializer/artifactloader/ArtifactLoader.java @@ -0,0 +1,58 @@ +/*- + * ~~~~~~licensing~~~~~~ + * artifact-loader + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.initializer.artifactloader; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; + +import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer; +import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer; + +@Component(service = ArtifactLoader.class, immediate = true) +@StandaloneInitializer(id = "artifacts") +public class ArtifactLoader extends AbstractStandaloneInitializer { + + @Reference + ArtifactDeployer artifactDeployer; + + @Reference + ArtifactInstaller artifactInstaller; + + @Activate + public void activate() { + artifactDeployer.start(); + artifactInstaller.start(); + register(); + } + + @Deactivate + public void deactivate() { + + } + +} diff --git a/platform/runtime/core/initializer/connection-initializer/src/main/non-packaged-resources/etc/init/broker-connections.json b/platform/runtime/core/initializer/connection-initializer/src/main/non-packaged-resources/etc/init/broker-connections.json new file mode 100644 index 00000000..cac2229a --- /dev/null +++ b/platform/runtime/core/initializer/connection-initializer/src/main/non-packaged-resources/etc/init/broker-connections.json @@ -0,0 +1,14 @@ +{ + "connections": [ + { + "factoryId": "artemis-connection", + "objectId": "entaxy-broker", + "properties": { + "connectionString": "(tcp://localhost:61616)", + "camel_username": "entaxy", + "camel_password": "entaxy", + "isPlatform": true + } + } + ] +} \ No newline at end of file diff --git a/platform/runtime/core/initializer/connection-initializer/src/main/non-packaged-resources/etc/init/db-connections.json b/platform/runtime/core/initializer/connection-initializer/src/main/non-packaged-resources/etc/init/db-connections.json new file mode 100644 index 00000000..b2d7d736 --- /dev/null +++ b/platform/runtime/core/initializer/connection-initializer/src/main/non-packaged-resources/etc/init/db-connections.json @@ -0,0 +1,20 @@ +{ + "connections": [ + { + "factoryId": "jdbc-connection", + "objectId": "entaxy-db-storage", + "properties": { + "dataSourceName": "entaxy.esb.storage", + "isPlatform": true + } + }, + { + "factoryId": "jdbc-connection", + "objectId": "entaxy-db-cache", + "properties": { + "dataSourceName": "entaxy.esb.cache", + "isPlatform": true + } + } + ] +} diff --git a/platform/runtime/core/initializer/datasources-initializer/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/datasources/DataSourcesStandaloneInitializer.java b/platform/runtime/core/initializer/datasources-initializer/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/datasources/DataSourcesStandaloneInitializer.java new file mode 100644 index 00000000..ff63fe97 --- /dev/null +++ b/platform/runtime/core/initializer/datasources-initializer/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/datasources/DataSourcesStandaloneInitializer.java @@ -0,0 +1,59 @@ +/*- + * ~~~~~~licensing~~~~~~ + * datasources-initializer + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.core.initializer.datasources; + +import javax.sql.DataSource; + +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.esb.platform.runtime.core.initializer.api.AbstractStandaloneInitializer; +import ru.entaxy.esb.platform.runtime.core.initializer.api.StandaloneInitializer; + +@Component(service = DataSourcesStandaloneInitializer.class, immediate = true) +@StandaloneInitializer(id = "datasources") +public class DataSourcesStandaloneInitializer extends AbstractStandaloneInitializer { + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY, target = "(osgi.jndi.service.name=entaxy.esb.storage)") + volatile DataSource storage; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY, target = "(osgi.jndi.service.name=entaxy.esb.cache)") + volatile DataSource cache; + + @Activate + public void activate(ComponentContext componentContext) { + setBundleContext(componentContext.getBundleContext()); + register(); + } + +} diff --git a/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/AbstractStandaloneInitializer.java b/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/AbstractStandaloneInitializer.java new file mode 100644 index 00000000..534a0142 --- /dev/null +++ b/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/AbstractStandaloneInitializer.java @@ -0,0 +1,85 @@ +/*- + * ~~~~~~licensing~~~~~~ + * init-manager + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.core.initializer.api; + +import java.util.Dictionary; +import java.util.Hashtable; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public abstract class AbstractStandaloneInitializer implements Initialized { + + private static final Logger log = LoggerFactory.getLogger(AbstractStandaloneInitializer.class); + + protected String initializerId; + protected BundleContext bundleContext; + protected ServiceRegistration serviceRegistration; + + protected AbstractStandaloneInitializer() { + super(); + if (getClass().isAnnotationPresent(StandaloneInitializer.class)) { + StandaloneInitializer anno = getClass().getAnnotation(StandaloneInitializer.class); + this.initializerId = anno.id(); + } + } + + public String getInitializerId() { + return initializerId; + } + + public void setInitializerId(String initializerId) { + this.initializerId = initializerId; + } + + public BundleContext getBundleContext() { + return bundleContext; + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + protected BundleContext getCurrentBundleContext() { + if (this.bundleContext != null) + return bundleContext; + return FrameworkUtil.getBundle(Initialized.class).getBundleContext(); + } + + protected void register() { + try { + Dictionary props = new Hashtable<>(); + props.put(PROP_INITIALIZER_ID, initializerId); + serviceRegistration = getCurrentBundleContext().registerService(Initialized.class, this, props); + } catch (Exception e) { + log.error("Error registering service for initializer[" + initializerId + "]", e); + } + } + +} diff --git a/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/Initialized.java b/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/Initialized.java new file mode 100644 index 00000000..f9273a9d --- /dev/null +++ b/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/Initialized.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * init-manager + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.core.initializer.api; + +/** + * Marker interface to provide information of successful initialization. Service with the interface + * is exposed to be used as a dependency in other components. + * + * Initializer ID get be retrieved via service property 'id' + */ +public interface Initialized { + + String PROP_INITIALIZER_ID = "id"; + +} diff --git a/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/StandaloneInitializer.java b/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/StandaloneInitializer.java new file mode 100644 index 00000000..dd213203 --- /dev/null +++ b/platform/runtime/core/initializer/init-manager/src/main/java/ru/entaxy/esb/platform/runtime/core/initializer/api/StandaloneInitializer.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * init-manager + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.runtime.core.initializer.api; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface StandaloneInitializer { + + String id(); + +} diff --git a/platform/runtime/core/management/config-management/LICENSE.txt b/platform/runtime/core/management/config-management/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/management/config-management/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/management/config-management/pom.xml b/platform/runtime/core/management/config-management/pom.xml new file mode 100644 index 00000000..fdade5ab --- /dev/null +++ b/platform/runtime/core/management/config-management/pom.xml @@ -0,0 +1,38 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + management + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.management + config-management + bundle + + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: MANAGEMENT :: CONFIG MANAGEMENT + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: MANAGEMENT :: CONFIG MANAGEMENT + + + ru.entaxy.platform.config.management + ru.entaxy.platform.config.management.impl + + + + + ru.entaxy.esb.platform.runtime.base + management-core + ${project.version} + + + ru.entaxy.esb.platform.runtime.core.management + object-management + ${project.version} + + + ru.entaxy.esb.platform.runtime.core.objects-implementations.config-implementation + config-runtime + ${project.version} + + + + diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ConfigMBean.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ConfigMBean.java new file mode 100644 index 00000000..3810c05b --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ConfigMBean.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ConfigMBean extends EntaxyRuntimeObjectMBean { + + String SUBQUALIFIER_KEY = "config"; + + @Attribute(desc = "Configuration PID") + default String getPid() { + return getObjectId(); + } + +} diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ConfigsMBean.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ConfigsMBean.java new file mode 100644 index 00000000..ddcfe05d --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ConfigsMBean.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.config.runtime.ObjectConfig; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ConfigsMBean extends EntaxyRuntimeObjectContainerMBean { + + String CONFIG_RUNTIME_TYPE = ObjectConfig.CONFIG_OBJECT_TYPE; + + Qualifier QUALIFIER = ManagementCore.Q_RUNTIME.qualifier("category", "configs"); + + String SUBQUALIFIER = QUALIFIER.getValue().substring(ManagementCore.Q_RUNTIME.getValue().length() + 1); + +} diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ObjectConfigMBean.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ObjectConfigMBean.java new file mode 100644 index 00000000..c019e491 --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/ObjectConfigMBean.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ObjectConfigMBean extends ConfigMBean { + + @Attribute(desc = "Target object being configured by this config") + default String getTarget() { + return getRuntimeObject().getAttributeOrDefault("target", "").toString(); + } + +} diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigMBeanFactory.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigMBeanFactory.java new file mode 100644 index 00000000..55a0cbc9 --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigMBeanFactory.java @@ -0,0 +1,72 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management.impl; + +import java.util.Collections; +import java.util.List; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.config.management.ConfigsMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@MBeanFactory(id = "vaults-factory", supportedTypes = {ConfigsMBean.CONFIG_RUNTIME_TYPE}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class ConfigMBeanFactory extends AbstractMBeanFactory { + + private static final Logger LOG = LoggerFactory.getLogger(ConfigMBeanFactory.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ConfigsMBeanImpl configsMBean; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + try { + if (entaxyRuntimeObject.getIncomiingSubordRelations().isEmpty()) + return (T) new ConfigMBeanImpl(entaxyRuntimeObject); + else + return (T) new ObjectConfigMBeanImpl(entaxyRuntimeObject); + } catch (Exception e) { + LOG.error("Error creating MBean for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + } + return null; + } + + @Override + public List createMBeans() { + return Collections.singletonList(configsMBean); + } + +} diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigMBeanImpl.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigMBeanImpl.java new file mode 100644 index 00000000..adfec9a4 --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigMBeanImpl.java @@ -0,0 +1,63 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.config.management.ConfigMBean; +import ru.entaxy.platform.config.management.ConfigsMBean; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@EntaxyRuntimeTyped(name = ConfigsMBean.CONFIG_RUNTIME_TYPE) +@ObjectMBean(subQualifierName = ConfigMBean.SUBQUALIFIER_KEY) +public class ConfigMBeanImpl extends AbstractObjectMBean + implements ConfigMBean { + + public ConfigMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super((Class) ConfigMBean.class, entaxyRuntimeObject); + } + + protected ConfigMBeanImpl(Class mbeanInterface, EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(mbeanInterface, entaxyRuntimeObject); + } + + @Override + public Qualifier getJMXQualifier() { + return ConfigsMBean.QUALIFIER.qualifier(ConfigMBean.SUBQUALIFIER_KEY, getObjectId()); + } + + @Override + public String getJMXSubQualifier() { + return ConfigMBean.SUBQUALIFIER_KEY.concat("=") + .concat(getObjectId()); + } +} diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigsMBeanImpl.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigsMBeanImpl.java new file mode 100644 index 00000000..77df7619 --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ConfigsMBeanImpl.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management.impl; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.platform.config.management.ConfigsMBean; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; + +@Component(service = ConfigsMBeanImpl.class, immediate = true) +@ContainerMBean(id = "configs", subQualifierValue = "configs") +public class ConfigsMBeanImpl extends AbstractObjectContainerMBean + implements ConfigsMBean { + + public ConfigsMBeanImpl() throws NotCompliantMBeanException { + super(ConfigsMBean.class); + } + + @Override + public Qualifier getJMXQualifier() { + return ConfigsMBean.QUALIFIER; + } + + @Override + public String getJMXSubQualifier() { + return ConfigsMBean.SUBQUALIFIER; + } + +} diff --git a/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ObjectConfigMBeanImpl.java b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ObjectConfigMBeanImpl.java new file mode 100644 index 00000000..d5218c29 --- /dev/null +++ b/platform/runtime/core/management/config-management/src/main/java/ru/entaxy/platform/config/management/impl/ObjectConfigMBeanImpl.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.management.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.platform.config.management.ObjectConfigMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +public class ObjectConfigMBeanImpl extends ConfigMBeanImpl implements ObjectConfigMBean { + + public ObjectConfigMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) throws NotCompliantMBeanException { + super(ObjectConfigMBean.class, entaxyRuntimeObject); + } + + @Override + public String getParentSubPath() { + return ""; + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/ConnectionMBean.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/ConnectionMBean.java new file mode 100644 index 00000000..aeb42279 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/ConnectionMBean.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove; + +import ru.entaxy.esb.platform.base.management.core.api.RuntimeTypedMBean; + +public interface ConnectionMBean extends RuntimeTypedMBean { + + public static final String CONNECTION_KEY = "connection"; + + /* + * connection name + */ + public String getName(); + + /* + * if connection is platform one or user defined + */ + public boolean isPlatform(); + + /* + * status of the bundle if connection is deplyed + */ + public String getStatus(); + + /* + * if the connection local or shared (cluster) + */ + public boolean isLocal(); + + /* + * if the connection is shared (single malt) + * or prototype-like (blended) + */ + public boolean isShared(); + + /* + * if the connection is deployed or only defined + */ + public boolean isDeployed(); + + /* + * bundle id for single malt connection + * null for blended + */ + public String getBundleId(); + + /* + * connection label + */ + public String getLabel(); + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/ConnectionsMBean.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/ConnectionsMBean.java new file mode 100644 index 00000000..62bbfdbd --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/ConnectionsMBean.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove; + +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATION_ENRICH) +public interface ConnectionsMBean { + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.connection"; + + public static final String CONNECTIONS_KEY = "category"; + + public static final String CONNECTIONS_KEY_VALUE = "connections"; + + @Operation(desc = "Gets connection's configuration") + public String getConnectionConfig( + @Parameter(name = "connectionName", desc = "Connection name") String connectionName) throws Exception; + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ConnectionMBeanImpl.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ConnectionMBeanImpl.java new file mode 100644 index 00000000..b04a1ff9 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ConnectionMBeanImpl.java @@ -0,0 +1,105 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.impl; + +import javax.management.NotCompliantMBeanException; +import javax.management.StandardMBean; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.esb.platform.core.management.connection.to_remove.ConnectionMBean; + +//@TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.connection") +public class ConnectionMBeanImpl extends StandardMBean implements ConnectionMBean { + + protected ManagedConnection connection; + + protected BundleContext bundleContext; + + public ConnectionMBeanImpl(BundleContext bundleContext, ManagedConnection connection) throws NotCompliantMBeanException { + super(ConnectionMBean.class); + this.bundleContext = bundleContext; + this.connection = connection; + } + + @Override + public String getName() { + return connection.getName(); + } + + @Override + public boolean isPlatform() { + return connection.isPlatform(); + } + + @Override + public String getStatus() { + int state = this.bundleContext.getBundle(connection.getBundleId()).getState(); + switch (state) { + case Bundle.ACTIVE: + return "Active"; + case Bundle.INSTALLED: + return "Installed"; + case Bundle.RESOLVED: + return "Resolved"; + case Bundle.STARTING: + return "Starting"; + case Bundle.STOPPING: + return "Stopping"; + default: + return "Unknown"; + } + } + + @Override + public boolean isLocal() { + return connection.isLocal; + } + + @Override + public boolean isShared() { + return connection.isShared(); + } + + @Override + public boolean isDeployed() { + return connection.isDeployed; + } + + @Override + public String getBundleId() { + return connection.getBundleId() + ""; + } + + @Override + public String getLabel() { + return connection.getLabel(); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ConnectionsMBeanImpl.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ConnectionsMBeanImpl.java new file mode 100644 index 00000000..e3d56072 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ConnectionsMBeanImpl.java @@ -0,0 +1,145 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.impl; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean; +import ru.entaxy.esb.platform.core.management.connection.to_remove.ConnectionMBean; +import ru.entaxy.esb.platform.core.management.connection.to_remove.ConnectionsMBean; +import ru.entaxy.esb.platform.core.management.connection.to_remove.tracker.DeployedConnectionTracker; +import ru.entaxy.platform.base.objects.EntaxyObjectService; + +/* + +@Component( + service = {ConnectionsMBean.class, DynamicMBean.class, MBeanRegistration.class}, + property = {ManagementCore.JMX_OBJECTNAME + + "=" + ManagementCore.Q_RUNTIME_S + + "," + ConnectionsMBean.CONNECTIONS_KEY + + "=" + ConnectionsMBean.CONNECTIONS_KEY_VALUE}, + scope = ServiceScope.SINGLETON, + immediate = true + ) +*/ + + +public class ConnectionsMBeanImpl extends AnnotatedMBean + implements ConnectionsMBean, ManagedConnectionsListener { + + private static final Logger log = LoggerFactory.getLogger(ConnectionsMBeanImpl.class); + + public static final Qualifier Q_CONNECTIONS = ManagementCore.Q_RUNTIME + .qualifier(ConnectionsMBean.CONNECTIONS_KEY, ConnectionsMBean.CONNECTIONS_KEY_VALUE); + + protected BundleContext bundleContext; + + protected DeployedConnectionTracker tracker; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyObjectService entaxyObjectService; + + protected static class ManagedConnectionDescriptor { + + ManagedConnection connection; + ServiceRegistration registration; + + } + + protected Map managed = new HashMap<>(); + + public ConnectionsMBeanImpl() throws NotCompliantMBeanException { + super(ConnectionsMBean.class); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + tracker = new DeployedConnectionTracker(bundleContext, this); + tracker.open(); + } + + @Deactivate + public void deactivate() { + tracker.close(); + } + + @Override + public void added(ManagedConnections connections) { + Hashtable props = new Hashtable<>(); + // String jmxObjectName = "jmx.objectname"; + // String objectName = "ru.entaxy.esb:group=platform,category=connections,connection="; + for (ManagedConnection connection: connections.managedConnections) { + if (managed.containsKey(connection.getName())) + this.managed.get(connection.getName()).registration.unregister(); + try { + ConnectionMBeanImpl service = new ConnectionMBeanImpl(bundleContext, connection); + ManagedConnectionDescriptor descriptor = new ManagedConnectionDescriptor(); + descriptor.connection = connection; + props.put(ManagementCore.JMX_OBJECTNAME + , Q_CONNECTIONS.qualifier(ConnectionMBean.CONNECTION_KEY + , connection.getName()).getValue()); + descriptor.registration = bundleContext.registerService(ConnectionMBean.class + , service + , props); + managed.put(connection.getName(), descriptor); + } catch (Exception e) { + log.error("Error adding connection [" + connection.getName() + "]", e); + } + } + } + + @Override + public void removed(ManagedConnections connections) { + for (ManagedConnection connection: connections.managedConnections) { + if (managed.containsKey(connection.getName())) { + this.managed.get(connection.getName()).registration.unregister(); + this.managed.remove(connection.getName()); + } + } + } + + @Override + public String getConnectionConfig(String connectionName) throws Exception { + return entaxyObjectService.findObject(connectionName, "entaxy.runtime.connection").getConfiguration(); + } +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnection.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnection.java new file mode 100644 index 00000000..c7b6dce3 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnection.java @@ -0,0 +1,116 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.impl; + +public class ManagedConnection { + + protected String name; + protected boolean isPlatform; + protected boolean isLocal; + protected boolean isShared; + protected long bundleId; + protected boolean isDeployed; + protected String label; + + public String getName() { + return name; + } + public boolean isPlatform() { + return isPlatform; + } + public boolean isLocal() { + return isLocal; + } + public boolean isShared() { + return isShared; + } + public long getBundleId() { + return bundleId; + } + public boolean isDeployed() { + return isDeployed; + } + public String getLabel() { + return label; + } + + public void setName(String name) { + this.name = name; + } + public void setPlatform(boolean isPlatform) { + this.isPlatform = isPlatform; + } + public void setLocal(boolean isLocal) { + this.isLocal = isLocal; + } + public void setShared(boolean isShared) { + this.isShared = isShared; + } + public void setBundleId(long bundleId) { + this.bundleId = bundleId; + } + public void setDeployed(boolean isDeployed) { + this.isDeployed = isDeployed; + } + public void setLabel(String label) { + this.label = label; + } + + public ManagedConnection name(String name) { + setName(name); + return this; + } + + public ManagedConnection platform(boolean isPlatform) { + setPlatform(isPlatform); + return this; + } + + public ManagedConnection local(boolean isLocal) { + setLocal(isLocal); + return this; + } + + public ManagedConnection shared(boolean isShared) { + setShared(isShared); + return this; + } + + public ManagedConnection bundleId(long bundleId) { + setBundleId(bundleId); + return this; + } + + public ManagedConnection deployed(boolean deployed) { + setDeployed(deployed); + return this; + } + + public ManagedConnection label(String label) { + setLabel(label); + return this; + } +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnections.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnections.java new file mode 100644 index 00000000..b8ae379f --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnections.java @@ -0,0 +1,35 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.impl; + +import java.util.ArrayList; +import java.util.List; + +public class ManagedConnections { + + public List managedConnections = new ArrayList<>(); + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnectionsListener.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnectionsListener.java new file mode 100644 index 00000000..080b868e --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/impl/ManagedConnectionsListener.java @@ -0,0 +1,33 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.impl; + +public interface ManagedConnectionsListener { + + public void added(ManagedConnections connections); + public void removed(ManagedConnections connections); + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/tracker/DeployedConnectionCustomizer.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/tracker/DeployedConnectionCustomizer.java new file mode 100644 index 00000000..87d386f2 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/tracker/DeployedConnectionCustomizer.java @@ -0,0 +1,102 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.tracker; + +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.wiring.BundleCapability; +import org.osgi.framework.wiring.BundleRevision; +import org.osgi.util.tracker.BundleTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.management.connection.to_remove.ConnectionsMBean; +import ru.entaxy.esb.platform.core.management.connection.to_remove.impl.ManagedConnection; +import ru.entaxy.esb.platform.core.management.connection.to_remove.impl.ManagedConnections; +import ru.entaxy.esb.platform.core.management.connection.to_remove.impl.ManagedConnectionsListener; +import ru.entaxy.platform.base.support.CommonUtils; + +public class DeployedConnectionCustomizer implements BundleTrackerCustomizer { + + private static final Logger log = LoggerFactory.getLogger(DeployedConnectionCustomizer.class); + + protected ManagedConnectionsListener listener; + + public DeployedConnectionCustomizer(ManagedConnectionsListener listener) { + this.listener = listener; + } + + @Override + public ManagedConnections addingBundle(Bundle bundle, BundleEvent event) { + log.debug("INSPECTING: " + bundle.getBundleId()); + BundleRevision revision = bundle.adapt(BundleRevision.class); + if (revision == null) + return null; + log.debug("REVISION FOUND: " + bundle.getBundleId()); + List capabilities = revision.getDeclaredCapabilities(ConnectionsMBean.CAPABILITY_NAMESPACE); + if ((capabilities==null) || (capabilities.size()==0)) + return null; + log.debug("CAPABILITIES FOUND: " + bundle.getBundleId()); + ManagedConnections result = new ManagedConnections(); + for (BundleCapability capability: capabilities) { + Object val = capability.getAttributes().get("name"); + String name = val==null?"":val.toString(); + log.debug("CAPABILITIES/NAME [" + name + "] : " + bundle.getBundleId()); + if (!CommonUtils.isValid(name)) + continue; + val = capability.getAttributes().get("platform"); + boolean isPlatform = val==null?false:"true".equals(val.toString()); + val = capability.getAttributes().get("label"); + String label = val == null ? "" : val.toString(); + ManagedConnection mc = (new ManagedConnection()) + .name(name) + .platform(isPlatform) + .deployed(true) + .local(isPlatform) + .shared(true) + .bundleId(bundle.getBundleId()) + .label(label); + result.managedConnections.add(mc); + } + listener.added(result); + return result; + } + + @Override + public void modifiedBundle(Bundle bundle, BundleEvent event, ManagedConnections object) { + // TODO Auto-generated method stub + + } + + @Override + public void removedBundle(Bundle bundle, BundleEvent event, ManagedConnections object) { + log.debug("BUNDLE [{}] REMOVING", bundle.getBundleId()); + listener.removed(object); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/tracker/DeployedConnectionTracker.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/tracker/DeployedConnectionTracker.java new file mode 100644 index 00000000..c80761c1 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/esb/platform/core/management/connection/to_remove/tracker/DeployedConnectionTracker.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.connection.to_remove.tracker; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.BundleTracker; + +import ru.entaxy.esb.platform.core.management.connection.to_remove.impl.ManagedConnections; +import ru.entaxy.esb.platform.core.management.connection.to_remove.impl.ManagedConnectionsListener; + +public class DeployedConnectionTracker extends BundleTracker { + + public DeployedConnectionTracker(BundleContext bundleContext, ManagedConnectionsListener listener) { + super(bundleContext + , Bundle.ACTIVE | Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING + , new DeployedConnectionCustomizer(listener)); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/ConnectionMBean.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/ConnectionMBean.java new file mode 100644 index 00000000..9a92f3d6 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/ConnectionMBean.java @@ -0,0 +1,85 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ConnectionMBean extends EntaxyRuntimeObjectMBean { + + public static final String CONNECTION_KEY = "connection"; + + /* + * connection name + */ + @Attribute + default String getName() { + return getObjectId(); + }; + + /* + * if connection is platform one or user defined + */ + @Attribute + public boolean isPlatform(); + + /* + * status of the bundle if connection is deplyed + */ + @Attribute + public String getStatus(); + + /* + * if the connection local or shared (cluster) + */ + @Attribute + public boolean isLocal(); + + /* + * if the connection is shared (single malt) or prototype-like (blended) + */ + @Attribute + public boolean isShared(); + + /* + * if the connection is deployed or only defined + */ + @Attribute + public boolean isDeployed(); + + /* + * connection label + */ + @Deprecated(since = "1.10", forRemoval = true) + @Attribute + default String getLabel() { + return getObjectLabel(); + }; + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/ConnectionsMBean.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/ConnectionsMBean.java new file mode 100644 index 00000000..f63f7d84 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/ConnectionsMBean.java @@ -0,0 +1,59 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection; + +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ConnectionsMBean extends EntaxyRuntimeObjectContainerMBean { + + public static final String CONNECTION_TYPE = "entaxy.runtime.connection"; + + public static final String CONNECTIONS_KEY = "category"; + + public static final String CONNECTIONS_KEY_VALUE = "connections"; + + @Operation(desc = "Gets connection's configuration") + public String getConnectionConfig( + @Parameter(name = "connectionName", desc = "Connection name") String connectionName) throws Exception; + + @Operation(desc = "Start connection") + void startConnection( + @Parameter(name = "idOrName", desc = "Id or name of the connection") String idOrName) throws Exception; + + @Operation(desc = "Stop connection") + void stopConnection( + @Parameter(name = "idOrName", desc = "Id or name of the connection") String idOrName) throws Exception; + + @Operation(desc = "Uninstall connection") + void uninstallConnection( + @Parameter(name = "idOrName", desc = "Id or name of the connection") String idOrName) throws Exception; + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionMBeanFactory.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionMBeanFactory.java new file mode 100644 index 00000000..45e5af38 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionMBeanFactory.java @@ -0,0 +1,75 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.impl; + +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + + +@MBeanFactory(id = "connection-factory", supportedTypes = {"entaxy.runtime.connection", "entaxy.runtime.connection.*"}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class ConnectionMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(ConnectionMBeanFactory.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policyOption = ReferencePolicyOption.GREEDY) + ConnectionsMBeanImpl connectionsMBean; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + ConnectionMBeanImpl beanImpl; + try { + beanImpl = new ConnectionMBeanImpl(entaxyRuntimeObject); + beanImpl.setParentMBean(connectionsMBean); + } catch (NotCompliantMBeanException e) { + log.error("Error creating ProfileMBeanImpl for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + return (T) beanImpl; + } + + @Override + public List createMBeans() { + return Collections.singletonList(connectionsMBean); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionMBeanImpl.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionMBeanImpl.java new file mode 100644 index 00000000..6eed6c32 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionMBeanImpl.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.core.management.connection.ConnectionMBean; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +// @TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.connection") +@ObjectMBean(subQualifierName = "connection") +public class ConnectionMBeanImpl extends AbstractObjectMBean implements ConnectionMBean { + + public ConnectionMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(ConnectionMBean.class, entaxyRuntimeObject); + } + + @Override + public String getJMXSubQualifierValue() { + return getObjectId(); + } + + @Override + public boolean isPlatform() { + return entaxyRuntimeObject.getAttributeOrDefault("platform", "false").toString().equals("true"); + } + + @Override + public String getStatus() { + return getBundleState(); + } + + @Override + public boolean isLocal() { + return isPlatform(); + } + + @Override + public boolean isShared() { + return true; + } + + @Override + public boolean isDeployed() { + return true; + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionsMBeanImpl.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionsMBeanImpl.java new file mode 100644 index 00000000..e7569b84 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/impl/ConnectionsMBeanImpl.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.impl; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ServiceScope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.platform.base.objects.EntaxyObjectService; +import ru.entaxy.platform.core.management.connection.ConnectionsMBean; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager; + +@Component( + service = {ConnectionsMBeanImpl.class}, + scope = ServiceScope.SINGLETON, + immediate = true) +@ContainerMBean(id = "connections", subQualifierName = "category", subQualifierValue = "connections") +public class ConnectionsMBeanImpl extends AbstractObjectContainerMBean + implements ConnectionsMBean { + + private static final Logger log = LoggerFactory.getLogger(ConnectionsMBeanImpl.class); + + public static final Qualifier Q_CONNECTIONS = ManagementCore.Q_RUNTIME + .qualifier(ConnectionsMBean.CONNECTIONS_KEY, ConnectionsMBean.CONNECTIONS_KEY_VALUE); + + protected BundleContext bundleContext; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyObjectService entaxyObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyRuntimeObjectManager entaxyRuntimeObjectManager; + + + public ConnectionsMBeanImpl() throws NotCompliantMBeanException { + super(ConnectionsMBean.class); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + } + + @Deactivate + public void deactivate() {} + + + @Override + public String getConnectionConfig(String connectionName) throws Exception { + return entaxyObjectService.findObject(connectionName, ConnectionsMBean.CONNECTION_TYPE).getConfiguration(); + } + + @Override + public void startConnection(String idOrName) throws Exception { + entaxyRuntimeObjectManager + .start(entaxyObjectService.findObject(idOrName, ConnectionsMBean.CONNECTION_TYPE).getObjectFullId()); + } + + @Override + public void stopConnection(String idOrName) throws Exception { + entaxyRuntimeObjectManager + .stopForced(entaxyObjectService.findObject(idOrName, ConnectionsMBean.CONNECTION_TYPE) + .getObjectFullId()); + } + + @Override + public void uninstallConnection(String idOrName) throws Exception { + entaxyRuntimeObjectManager + .uninstallForced(entaxyObjectService.findObject(idOrName, ConnectionsMBean.CONNECTION_TYPE) + .getObjectFullId()); + } +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/DeployedLegacyConnectionCustomizer.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/DeployedLegacyConnectionCustomizer.java new file mode 100644 index 00000000..1cadbc3f --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/DeployedLegacyConnectionCustomizer.java @@ -0,0 +1,105 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.wiring.BundleCapability; +import org.osgi.framework.wiring.BundleRevision; +import org.osgi.util.tracker.BundleTrackerCustomizer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; + +public class DeployedLegacyConnectionCustomizer implements BundleTrackerCustomizer { + + private static final Logger log = LoggerFactory.getLogger(DeployedLegacyConnectionCustomizer.class); + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.connection"; + + protected ManagedLegacyConnectionsListener listener; + + public DeployedLegacyConnectionCustomizer(ManagedLegacyConnectionsListener listener) { + this.listener = listener; + } + + @Override + public ManagedLegacyConnections addingBundle(Bundle bundle, BundleEvent event) { + log.debug("INSPECTING: " + bundle.getBundleId()); + BundleRevision revision = bundle.adapt(BundleRevision.class); + if (revision == null) + return null; + log.debug("REVISION FOUND: " + bundle.getBundleId()); + List capabilities = revision.getDeclaredCapabilities(CAPABILITY_NAMESPACE); + if ((capabilities == null) || (capabilities.size() == 0)) + return null; + log.debug("CAPABILITIES FOUND: " + bundle.getBundleId()); + ManagedLegacyConnections result = new ManagedLegacyConnections(); + for (BundleCapability capability : capabilities) { + + // process only legacy connections + if (capability.getAttributes().containsKey("objectId") && capability.getAttributes().containsKey("factory")) + continue; + + Object val = capability.getAttributes().get("name"); + String name = val == null ? "" : val.toString(); + log.debug("CAPABILITIES/NAME [" + name + "] : " + bundle.getBundleId()); + if (!CommonUtils.isValid(name)) + continue; + val = capability.getAttributes().get("platform"); + boolean isPlatform = val == null ? false : "true".equals(val.toString()); + val = capability.getAttributes().get("label"); + String label = val == null ? "" : val.toString(); + ManagedLegacyConnection mc = (new ManagedLegacyConnection()) + .name(name) + .platform(isPlatform) + .deployed(true) + .local(isPlatform) + .shared(true) + .bundleId(bundle.getBundleId()) + .label(label); + result.managedConnections.add(mc); + } + listener.added(result); + return result; + } + + @Override + public void modifiedBundle(Bundle bundle, BundleEvent event, ManagedLegacyConnections object) { + // TODO Auto-generated method stub + + } + + @Override + public void removedBundle(Bundle bundle, BundleEvent event, ManagedLegacyConnections object) { + log.debug("BUNDLE [{}] REMOVING", bundle.getBundleId()); + listener.removed(object); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/DeployedLegacyConnectionTracker.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/DeployedLegacyConnectionTracker.java new file mode 100644 index 00000000..21c587c0 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/DeployedLegacyConnectionTracker.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.util.tracker.BundleTracker; + +public class DeployedLegacyConnectionTracker extends BundleTracker { + + public DeployedLegacyConnectionTracker(BundleContext bundleContext, ManagedLegacyConnectionsListener listener) { + super(bundleContext, Bundle.ACTIVE | Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING, + new DeployedLegacyConnectionCustomizer(listener)); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionMBean.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionMBean.java new file mode 100644 index 00000000..27ac2fec --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionMBean.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +import ru.entaxy.esb.platform.base.management.core.api.RuntimeTypedMBean; + +public interface LegacyConnectionMBean extends RuntimeTypedMBean { + + public static final String CONNECTION_KEY = "connection"; + + /* + * connection name + */ + public String getName(); + + /* + * if connection is platform one or user defined + */ + public boolean isPlatform(); + + /* + * status of the bundle if connection is deplyed + */ + public String getStatus(); + + /* + * if the connection local or shared (cluster) + */ + public boolean isLocal(); + + /* + * if the connection is shared (single malt) + * or prototype-like (blended) + */ + public boolean isShared(); + + /* + * if the connection is deployed or only defined + */ + public boolean isDeployed(); + + /* + * bundle id for single malt connection + * null for blended + */ + public String getBundleId(); + + /* + * connection label + */ + public String getLabel(); + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionMBeanImpl.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionMBeanImpl.java new file mode 100644 index 00000000..122758a7 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionMBeanImpl.java @@ -0,0 +1,106 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +import javax.management.NotCompliantMBeanException; +import javax.management.StandardMBean; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; + + +// @TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.connection") +public class LegacyConnectionMBeanImpl extends StandardMBean implements LegacyConnectionMBean { + + protected ManagedLegacyConnection connection; + + protected BundleContext bundleContext; + + public LegacyConnectionMBeanImpl(BundleContext bundleContext, ManagedLegacyConnection connection) + throws NotCompliantMBeanException { + super(LegacyConnectionMBean.class); + this.bundleContext = bundleContext; + this.connection = connection; + } + + @Override + public String getName() { + return connection.getName(); + } + + @Override + public boolean isPlatform() { + return connection.isPlatform(); + } + + @Override + public String getStatus() { + int state = this.bundleContext.getBundle(connection.getBundleId()).getState(); + switch (state) { + case Bundle.ACTIVE: + return "Active"; + case Bundle.INSTALLED: + return "Installed"; + case Bundle.RESOLVED: + return "Resolved"; + case Bundle.STARTING: + return "Starting"; + case Bundle.STOPPING: + return "Stopping"; + default: + return "Unknown"; + } + } + + @Override + public boolean isLocal() { + return connection.isLocal; + } + + @Override + public boolean isShared() { + return connection.isShared(); + } + + @Override + public boolean isDeployed() { + return connection.isDeployed; + } + + @Override + public String getBundleId() { + return connection.getBundleId() + ""; + } + + @Override + public String getLabel() { + return connection.getLabel(); + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionsManager.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionsManager.java new file mode 100644 index 00000000..244f2291 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/LegacyConnectionsManager.java @@ -0,0 +1,125 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +import java.util.HashMap; +import java.util.Hashtable; +import java.util.Map; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ServiceScope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.core.management.connection.to_remove.ConnectionMBean; +import ru.entaxy.esb.platform.core.management.connection.to_remove.ConnectionsMBean; +import ru.entaxy.platform.base.objects.EntaxyObjectService; + +@Component( + service = {LegacyConnectionsManager.class}, + scope = ServiceScope.SINGLETON, + immediate = true) +public class LegacyConnectionsManager implements ManagedLegacyConnectionsListener { + + private static final Logger log = LoggerFactory.getLogger(LegacyConnectionsManager.class); + + public static final Qualifier Q_CONNECTIONS = ManagementCore.Q_RUNTIME + .qualifier(ConnectionsMBean.CONNECTIONS_KEY, ConnectionsMBean.CONNECTIONS_KEY_VALUE); + + protected BundleContext bundleContext; + + protected DeployedLegacyConnectionTracker tracker; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyObjectService entaxyObjectService; + + protected static class ManagedConnectionDescriptor { + + ManagedLegacyConnection connection; + ServiceRegistration registration; + + } + + protected Map managed = new HashMap<>(); + + public LegacyConnectionsManager() { + super(); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + tracker = new DeployedLegacyConnectionTracker(bundleContext, this); + tracker.open(); + } + + @Deactivate + public void deactivate() { + tracker.close(); + } + + @Override + public void added(ManagedLegacyConnections connections) { + Hashtable props = new Hashtable<>(); + // String jmxObjectName = "jmx.objectname"; + // String objectName = "ru.entaxy.esb:group=platform,category=connections,connection="; + for (ManagedLegacyConnection connection : connections.managedConnections) { + if (managed.containsKey(connection.getName())) + this.managed.get(connection.getName()).registration.unregister(); + try { + LegacyConnectionMBeanImpl service = new LegacyConnectionMBeanImpl(bundleContext, connection); + ManagedConnectionDescriptor descriptor = new ManagedConnectionDescriptor(); + descriptor.connection = connection; + props.put(ManagementCore.JMX_OBJECTNAME, + Q_CONNECTIONS.qualifier(ConnectionMBean.CONNECTION_KEY, connection.getName()).getValue()); + descriptor.registration = bundleContext.registerService(LegacyConnectionMBean.class, service, props); + managed.put(connection.getName(), descriptor); + } catch (Exception e) { + log.error("Error adding connection [" + connection.getName() + "]", e); + } + } + } + + @Override + public void removed(ManagedLegacyConnections connections) { + for (ManagedLegacyConnection connection : connections.managedConnections) { + if (managed.containsKey(connection.getName())) { + this.managed.get(connection.getName()).registration.unregister(); + this.managed.remove(connection.getName()); + } + } + } + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnection.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnection.java new file mode 100644 index 00000000..8b548da6 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnection.java @@ -0,0 +1,116 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +public class ManagedLegacyConnection { + + protected String name; + protected boolean isPlatform; + protected boolean isLocal; + protected boolean isShared; + protected long bundleId; + protected boolean isDeployed; + protected String label; + + public String getName() { + return name; + } + public boolean isPlatform() { + return isPlatform; + } + public boolean isLocal() { + return isLocal; + } + public boolean isShared() { + return isShared; + } + public long getBundleId() { + return bundleId; + } + public boolean isDeployed() { + return isDeployed; + } + public String getLabel() { + return label; + } + + public void setName(String name) { + this.name = name; + } + public void setPlatform(boolean isPlatform) { + this.isPlatform = isPlatform; + } + public void setLocal(boolean isLocal) { + this.isLocal = isLocal; + } + public void setShared(boolean isShared) { + this.isShared = isShared; + } + public void setBundleId(long bundleId) { + this.bundleId = bundleId; + } + public void setDeployed(boolean isDeployed) { + this.isDeployed = isDeployed; + } + public void setLabel(String label) { + this.label = label; + } + + public ManagedLegacyConnection name(String name) { + setName(name); + return this; + } + + public ManagedLegacyConnection platform(boolean isPlatform) { + setPlatform(isPlatform); + return this; + } + + public ManagedLegacyConnection local(boolean isLocal) { + setLocal(isLocal); + return this; + } + + public ManagedLegacyConnection shared(boolean isShared) { + setShared(isShared); + return this; + } + + public ManagedLegacyConnection bundleId(long bundleId) { + setBundleId(bundleId); + return this; + } + + public ManagedLegacyConnection deployed(boolean deployed) { + setDeployed(deployed); + return this; + } + + public ManagedLegacyConnection label(String label) { + setLabel(label); + return this; + } +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnections.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnections.java new file mode 100644 index 00000000..cb852dc1 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnections.java @@ -0,0 +1,35 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +import java.util.ArrayList; +import java.util.List; + +public class ManagedLegacyConnections { + + public List managedConnections = new ArrayList<>(); + +} diff --git a/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnectionsListener.java b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnectionsListener.java new file mode 100644 index 00000000..837386f0 --- /dev/null +++ b/platform/runtime/core/management/connection-management/src/main/java/ru/entaxy/platform/core/management/connection/support/legacy/ManagedLegacyConnectionsListener.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * connection-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.connection.support.legacy; + +public interface ManagedLegacyConnectionsListener { + + public void added(ManagedLegacyConnections connections); + + public void removed(ManagedLegacyConnections connections); + +} diff --git a/platform/runtime/core/management/object-management/LICENSE.txt b/platform/runtime/core/management/object-management/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/management/object-management/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/management/object-management/pom.xml b/platform/runtime/core/management/object-management/pom.xml new file mode 100644 index 00000000..795a0f9e --- /dev/null +++ b/platform/runtime/core/management/object-management/pom.xml @@ -0,0 +1,39 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + management + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.management + object-management + bundle + ENTAXY :: CORE :: MANAGEMENT :: OBJECT + ENTAXY :: CORE :: MANAGEMENT :: OBJECT + + + + ru.entaxy.platform.core.management.object, + ru.entaxy.platform.core.management.object.factory + + + ru.entaxy.platform.core.management.object.impl, + ru.entaxy.platform.core.management.object.factory.impl, + ru.entaxy.platform.core.management.object.shell + + none + + + + + ru.entaxy.esb.platform.runtime.core + object-runtime-core + ${project.version} + + + org.apache.karaf.bundle + org.apache.karaf.bundle.core + ${karaf.version} + + + diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/ContainerMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/ContainerMBean.java new file mode 100644 index 00000000..85b059f7 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/ContainerMBean.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Inherited +@Retention(RUNTIME) +@Target(TYPE) +public @interface ContainerMBean { + + String id() default ""; + + String subQualifierName() default EntaxyRuntimeObjectContainerMBean.JMX_QUALIFIER_NAME; + + String subQualifierValue(); + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeItemMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeItemMBean.java new file mode 100644 index 00000000..5766c30a --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeItemMBean.java @@ -0,0 +1,162 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import java.util.Map; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface EntaxyRuntimeItemMBean { + + String JMX_SUBPATH_QUALIFIER = "subgroup"; + + String JMX_SUBQUALIFIER_AUTO = "@AUTO@"; + + EntaxyRuntimeItemMBean DEFAULT_PARENT_MBEAN = new EntaxyRuntimeItemMBean() { + + @Override + public Class getMBeanClass() { + // TODO Auto-generated method stub + return null; + } + + public String getJMXSubQualifier() { + return ManagementCore.Q_RUNTIME_S; + }; + + @Override + public String getJMXSubQualifierValue() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getJMXSubQualifierName() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Qualifier getJMXQualifier() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getId() { + // TODO Auto-generated method stub + return null; + } + + public EntaxyRuntimeItemMBean getParentMBean() { + return null; + } + + @Override + public void setParentMBean(EntaxyRuntimeItemMBean mBean) { + // TODO Auto-generated method stub + + } + + @Override + public void setParentSubPath(String subPath) { + // TODO Auto-generated method stub + + } + + @Override + public void setJMXSubQualifierName(String name) { + // TODO Auto-generated method stub + + } + + @Override + public void setJMXSubQualifierValue(String value) { + // TODO Auto-generated method stub + + } + + @Override + public Map getChildMBeans() { + // TODO Auto-generated method stub + return null; + } + + @Override + public void addChildMBean(EntaxyRuntimeItemMBean mBean) { + // TODO Auto-generated method stub + + } + + @Override + public void removeChildMBean(EntaxyRuntimeItemMBean mBean) { + // TODO Auto-generated method stub + + } + + }; + + + Qualifier getJMXQualifier(); + + default String getJMXSubQualifier() { + return getJMXSubQualifierName().concat("=").concat(getJMXSubQualifierValue()); + }; + + default EntaxyRuntimeItemMBean getParentMBean() { + return DEFAULT_PARENT_MBEAN; + }; + + void setParentMBean(EntaxyRuntimeItemMBean mBean); + + default String getParentSubPath() { + return ""; + }; + + void setParentSubPath(String subPath); + + Map getChildMBeans(); + + void addChildMBean(EntaxyRuntimeItemMBean mBean); + + void removeChildMBean(EntaxyRuntimeItemMBean mBean); + + String getJMXSubQualifierName(); + + void setJMXSubQualifierName(String name); + + String getJMXSubQualifierValue(); + + void setJMXSubQualifierValue(String value); + + String getId(); + + Class getMBeanClass(); +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectContainerMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectContainerMBean.java new file mode 100644 index 00000000..0bc72e7a --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectContainerMBean.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface EntaxyRuntimeObjectContainerMBean extends EntaxyRuntimeItemMBean { + + String JMX_QUALIFIER_NAME = "category"; + + String JMX_DEFAULT_CATEGORY = "objects"; + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBean.java new file mode 100644 index 00000000..8cbb62d7 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBean.java @@ -0,0 +1,99 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import java.util.Map; + +import javax.management.MBeanOperationInfo; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.RuntimeTypedMBean; +import ru.entaxy.esb.platform.base.management.core.utils.BundleAwareMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface EntaxyRuntimeObjectMBean extends EntaxyRuntimeItemMBean, BundleAwareMBean, RuntimeTypedMBean { + + public static final String DEFAULT_OBJECT_SUBQUALIFIER = "object"; + + EntaxyRuntimeObject getRuntimeObject(); + + @Override + default String getJMXSubQualifierName() { + if (this.getClass().isAnnotationPresent(ObjectMBean.class)) + return this.getClass().getAnnotation(ObjectMBean.class).subQualifierName(); + return DEFAULT_OBJECT_SUBQUALIFIER; + } + + @Attribute(desc = "Managed bean Id") + String getId(); + + @Deprecated(since = "1.10.0", forRemoval = true) + @Attribute(desc = "Object Name") + String getName(); + + @Attribute(desc = "Object Id") + String getObjectId(); + + @Attribute(desc = "Object Type") + String getObjectType(); + + @Attribute(desc = "Object full Id") + String getObjectFullId(); + + @Attribute(desc = "Object label") + public String getObjectLabel(); + + @Attribute(desc = "Display name") + public String getDisplayName(); + + @Attribute(desc = "Object factory Id") + String getFactoryId(); + + @Attribute(desc = "Object scope") + String getScope(); + + @Attribute(desc = "Object owner for private objects") + String getOwner(); + + @Attribute(desc = "Object container Id") + String getContainerId(); + + @Attribute(desc = "Object is provided via capability descriptor") + boolean isProvided(); + + @Attribute(desc = "Object is ghost: assumed by relations but not present") + boolean isGhost(); + + @Operation(desc = "Gets JSON configuration of the object", impact = MBeanOperationInfo.INFO) + String readConfiguration(); + + @Operation(desc = "Reads extended data of the object", impact = MBeanOperationInfo.INFO) + Map> readExtendedData(); +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBeanCustomizer.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBeanCustomizer.java new file mode 100644 index 00000000..2624f3fd --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBeanCustomizer.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import java.util.List; + +public interface EntaxyRuntimeObjectMBeanCustomizer { + + public interface Customized { + + EntaxyRuntimeObjectMBean getCustomizedMBean(); + + List getAdditionalMBeans(); + } + + String getId(); + + boolean isAccepted(EntaxyRuntimeObjectMBean bean); + + Customized customize(EntaxyRuntimeObjectMBean bean); + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBeanFactory.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBeanFactory.java new file mode 100644 index 00000000..54a34942 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/EntaxyRuntimeObjectMBeanFactory.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import java.util.List; + +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +public interface EntaxyRuntimeObjectMBeanFactory { + + String JMX_QUALIFIER_NAME = "category"; + + String JMX_DEFAULT_CATEGORY = "objects"; + + String getId(); + + default String getCategory() { + return JMX_DEFAULT_CATEGORY; + }; + + default String getJMXSubQualifier() { + return JMX_QUALIFIER_NAME.concat("=").concat(getCategory()); + } + + List getSupportedTypes(); + + T createMBean(EntaxyRuntimeObject entaxyRuntimeObject); + + // T createMBeanContainerForType(String + // entaxyObjectType); + + List createMBeans(); +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/MBeanFactory.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/MBeanFactory.java new file mode 100644 index 00000000..b8d00508 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/MBeanFactory.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Inherited +@Retention(RUNTIME) +@Target(TYPE) +public @interface MBeanFactory { + + String[] supportedTypes(); + + String id(); +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/ObjectMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/ObjectMBean.java new file mode 100644 index 00000000..38f6c090 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/ObjectMBean.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object; + +import static java.lang.annotation.ElementType.TYPE; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + +import java.lang.annotation.Retention; +import java.lang.annotation.Target; + +@Retention(RUNTIME) +@Target(TYPE) +public @interface ObjectMBean { + + String subQualifierName(); + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractMBeanFactory.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractMBeanFactory.java new file mode 100644 index 00000000..a01f565e --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractMBeanFactory.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; + +public abstract class AbstractMBeanFactory implements EntaxyRuntimeObjectMBeanFactory { + + protected String id; + + protected List supportedTypes = new ArrayList<>(); + + protected AbstractMBeanFactory() { + super(); + this.id = this.getClass().getSimpleName(); + if (this.getClass().isAnnotationPresent(MBeanFactory.class)) { + MBeanFactory anno = this.getClass().getAnnotation(MBeanFactory.class); + this.id = anno.id(); + supportedTypes.addAll(Arrays.asList(anno.supportedTypes())); + } + + } + + @Override + public String getId() { + return this.id; + } + + @Override + public List getSupportedTypes() { + return this.supportedTypes; + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectContainerMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectContainerMBean.java new file mode 100644 index 00000000..8b078ee7 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectContainerMBean.java @@ -0,0 +1,54 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +public abstract class AbstractObjectContainerMBean + extends AbstractObjectItemMBean + implements EntaxyRuntimeObjectContainerMBean { + + protected AbstractObjectContainerMBean(Class mbeanInterface) throws NotCompliantMBeanException { + super(mbeanInterface); + if (this.getClass().isAnnotationPresent(ContainerMBean.class)) { + ContainerMBean anno = this.getClass().getAnnotation(ContainerMBean.class); + jmxSubQualifierName = anno.subQualifierName(); + jmxSubQualifierValue = anno.subQualifierValue(); + id = anno.id(); + } + } + + @Override + public Qualifier getJMXQualifier() { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectItemMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectItemMBean.java new file mode 100644 index 00000000..3a58ea48 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectItemMBean.java @@ -0,0 +1,134 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory; + +import java.util.HashMap; +import java.util.Map; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; + +public abstract class AbstractObjectItemMBean extends AnnotatedMBean + implements EntaxyRuntimeItemMBean { + + protected String jmxSubQualifierName; + protected String jmxSubQualifierValue; + + protected String id; + + protected EntaxyRuntimeItemMBean parentMBean; + protected String parentSubPath; + + protected Map children = new HashMap<>(); + + protected AbstractObjectItemMBean(Class mbeanInterface) throws NotCompliantMBeanException { + super(mbeanInterface); + } + + @Override + public Qualifier getJMXQualifier() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getJMXSubQualifierName() { + return jmxSubQualifierName; + } + + @Override + public void setJMXSubQualifierName(String name) { + jmxSubQualifierName = name; + } + + @Override + public String getJMXSubQualifierValue() { + return jmxSubQualifierValue; + } + + @Override + public void setJMXSubQualifierValue(String value) { + jmxSubQualifierValue = value; + } + + @Override + public String getId() { + return id; + } + + @Override + public Class getMBeanClass() { + return this.interfaceClass; + } + + @Override + public EntaxyRuntimeItemMBean getParentMBean() { + if (this.parentMBean != null) + return this.parentMBean; + return EntaxyRuntimeItemMBean.super.getParentMBean(); + } + + @Override + public void setParentMBean(EntaxyRuntimeItemMBean mBean) { + if (this.parentMBean != null) + this.parentMBean.removeChildMBean(this); + this.parentMBean = mBean; + if (parentMBean != null) + this.parentMBean.addChildMBean(this); + } + + @Override + public String getParentSubPath() { + if (CommonUtils.isValid(this.parentSubPath)) + return this.parentSubPath; + return EntaxyRuntimeItemMBean.super.getParentSubPath(); + } + + @Override + public void setParentSubPath(String parentSubPath) { + this.parentSubPath = parentSubPath; + } + + @Override + public Map getChildMBeans() { + return this.children; + } + + @Override + public void addChildMBean(EntaxyRuntimeItemMBean mBean) { + children.put(mBean.getId(), mBean); + } + + @Override + public void removeChildMBean(EntaxyRuntimeItemMBean mBean) { + children.remove(mBean.getId()); + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectMBean.java new file mode 100644 index 00000000..083818f9 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/AbstractObjectMBean.java @@ -0,0 +1,214 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory; + +import java.util.HashMap; +import java.util.Map; + +import javax.management.NotCompliantMBeanException; + +import org.apache.karaf.bundle.core.BundleInfo; +import org.apache.karaf.bundle.core.BundleState; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.factory.impl.ServiceHelper; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; + +public abstract class AbstractObjectMBean + extends AbstractObjectItemMBean + implements EntaxyRuntimeObjectMBean { + + private static final Logger LOG = LoggerFactory.getLogger(AbstractObjectMBean.class); + + protected EntaxyRuntimeObject entaxyRuntimeObject; + + protected AbstractObjectMBean(Class mbeanInterface, EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(mbeanInterface); + this.entaxyRuntimeObject = entaxyRuntimeObject; + } + + @Override + public String getJMXSubQualifierName() { + if (CommonUtils.isValid(this.jmxSubQualifierName)) + return this.jmxSubQualifierName; + return EntaxyRuntimeObjectMBean.super.getJMXSubQualifierName(); + } + + @Override + public String getJMXSubQualifierValue() { + return entaxyRuntimeObject.getObjectFullId().replace(':', '_'); + } + + @Override + public long getBundleId() { + if (entaxyRuntimeObject.getBundleInfo() != null) + return entaxyRuntimeObject.getBundleInfo().getBundleId(); + return -1; + } + + @Override + public String getBundleState() { + if (getBundleId() < 0) + return BundleState.Unknown.name(); + BundleInfo bi = ServiceHelper.getInstance().getBundleInfo(getBundleId()); + if (bi == null) + return BundleState.Unknown.name(); + return bi.getState().name(); + } + + @Override + public String getBundleSymbolicName() { + if (entaxyRuntimeObject.isGhost()) + return ""; + if (entaxyRuntimeObject.getContainer() == null) + return ""; + return entaxyRuntimeObject.getContainer().getName(); + } + + @Override + public String getId() { + if (entaxyRuntimeObject != null) + return entaxyRuntimeObject.getObjectFullId(); + return super.getId(); + } + + @Override + public void refreshBundleInfo() { + // TODO Auto-generated method stub + } + + @Override + public EntaxyRuntimeObject getRuntimeObject() { + return this.entaxyRuntimeObject; + } + + @Override + public String getName() { + return entaxyRuntimeObject.getAttributeOrDefault("name", getObjectId()).toString(); + }; + + @Override + public String getObjectId() { + return this.entaxyRuntimeObject.getId(); + } + + @Override + public String getObjectType() { + return this.entaxyRuntimeObject.getType(); + } + + @Override + public String getObjectFullId() { + return this.entaxyRuntimeObject.getObjectFullId(); + } + + @Override + public String getDisplayName() { + return this.entaxyRuntimeObject.getDisplayName(); + } + + @Override + public String getObjectLabel() { + return entaxyRuntimeObject.getAttributeOrDefault("label", "").toString(); + } + + @Override + public String getFactoryId() { + return this.entaxyRuntimeObject.getFactoryId(); + } + + @Override + public String getContainerId() { + return "" + getBundleId(); + } + + @Override + public String getScope() { + return this.entaxyRuntimeObject.getScope(); + } + + @Override + public String getOwner() { + return this.entaxyRuntimeObject.getOwner(); + } + + @Override + public String getRuntimeType() { + if (entaxyRuntimeObject != null) + return entaxyRuntimeObject.getType(); + return EntaxyRuntimeObjectMBean.super.getRuntimeType(); + } + + @Override + public boolean isProvided() { + if (entaxyRuntimeObject != null) + return entaxyRuntimeObject.isProvided(); + return false; + } + + @Override + public boolean isGhost() { + if (entaxyRuntimeObject != null) + return entaxyRuntimeObject.isGhost(); + return true; + } + + @Override + public String readConfiguration() { + if (entaxyRuntimeObject != null) + return entaxyRuntimeObject.getConfiguration(); + return ""; + } + + @Override + public Map> readExtendedData() { + try { + BundleContext bundleContext = FrameworkUtil.getBundle(EntaxyRuntimeObjectService.class).getBundleContext(); + ServiceReference ref = + bundleContext.getServiceReference(EntaxyRuntimeObjectService.class); + EntaxyRuntimeObjectService objectService = bundleContext.getService(ref); + + Map> result = objectService.getExtendedObjectInfo(entaxyRuntimeObject); + + bundleContext.ungetService(ref); + + if (result != null) + return result; + + } catch (Exception e) { + LOG.error(String.format("Error reading extended data for [%s]", entaxyRuntimeObject.getObjectFullId()), e); + } + return new HashMap<>(); + } +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/ObjectsContainerMBean.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/ObjectsContainerMBean.java new file mode 100644 index 00000000..a30c4503 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/ObjectsContainerMBean.java @@ -0,0 +1,65 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory; + +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ObjectsContainerMBean extends EntaxyRuntimeObjectContainerMBean { + + @Operation(desc = "Refreshes full object tree") + void refresh(); + + @Operation(desc = "Start bundle") + String startBundle( + @Parameter(name = "idOrName", desc = "Id or name of the object") String idOrName, + @Parameter(name = "runtimeType", desc = "Runtime type of the object") String runtimeType, + @Parameter(name = "forced", desc = "Operation flag for forced processing") boolean forced, + @Parameter(name = "soft", desc = "Operation flag for soft processing") boolean soft) throws Exception; + + @Operation(desc = "Stop bundle") + String stopBundle( + @Parameter(name = "idOrName", desc = "Id or name of the object") String idOrName, + @Parameter(name = "runtimeType", desc = "Runtime type of the object") String runtimeType, + @Parameter(name = "forced", desc = "Operation flag for forced processing") boolean forced, + @Parameter(name = "soft", desc = "Operation flag for soft processing") boolean soft) throws Exception; + + @Operation(desc = "Uninstall bundle") + String uninstallBundle( + @Parameter(name = "idOrName", desc = "Id or name of the object") String idOrName, + @Parameter(name = "runtimeType", desc = "Runtime type of the object") String runtimeType, + @Parameter(name = "forced", desc = "Operation flag for forced processing") boolean forced, + @Parameter(name = "soft", desc = "Operation flag for soft processing") boolean soft) throws Exception; + + @Operation(desc = "Find objects by osgi filter") + String findObjects( + @Parameter(name = "osgiFilter", desc = "OSGI filter") String osgiFilter) throws Exception; + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/EntaxyObjectMBeanFactory.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/EntaxyObjectMBeanFactory.java new file mode 100644 index 00000000..cb56daab --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/EntaxyObjectMBeanFactory.java @@ -0,0 +1,88 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory.impl; + +import java.util.ArrayList; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.core.management.object.impl.EntaxyRuntimeObjectMBeanManager; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@MBeanFactory(id = "root-object-factory", supportedTypes = {"*"}) +// @Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class EntaxyObjectMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(EntaxyObjectMBeanFactory.class); + + protected ObjectsContainerMBeanImpl objectsContainerMBeanImpl; + + protected EntaxyRuntimeObjectMBeanManager objectMBeanManager; + + public EntaxyObjectMBeanFactory(EntaxyRuntimeObjectMBeanManager objectMBeanManager) { + super(); + this.objectMBeanManager = objectMBeanManager; + try { + objectsContainerMBeanImpl = new ObjectsContainerMBeanImpl(); + } catch (NotCompliantMBeanException e) { + log.error("Error creating MBean for ObjectsContainerMBean", e); + } + } + + public void activate() {} + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + try { + EntaxyRuntimeObjectMBeanImpl result = new EntaxyRuntimeObjectMBeanImpl(entaxyRuntimeObject); + if (objectsContainerMBeanImpl != null) + result.setParentMBean(objectsContainerMBeanImpl); + return (T) result; + } catch (NotCompliantMBeanException e) { + log.error("Error creating MBean for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + } + + @Override + public List createMBeans() { + List result = new ArrayList<>(); + if (objectsContainerMBeanImpl != null) { + objectsContainerMBeanImpl.manager = objectMBeanManager; + result.add(objectsContainerMBeanImpl); + } + return result; + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/EntaxyRuntimeObjectMBeanImpl.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/EntaxyRuntimeObjectMBeanImpl.java new file mode 100644 index 00000000..eb06c67e --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/EntaxyRuntimeObjectMBeanImpl.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +public class EntaxyRuntimeObjectMBeanImpl extends AbstractObjectMBean + implements EntaxyRuntimeObjectMBean { + + public EntaxyRuntimeObjectMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) throws NotCompliantMBeanException { + super(EntaxyRuntimeObjectMBean.class, entaxyRuntimeObject); + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/ObjectsContainerMBeanImpl.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/ObjectsContainerMBeanImpl.java new file mode 100644 index 00000000..4f7cd5cd --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/ObjectsContainerMBeanImpl.java @@ -0,0 +1,150 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory.impl; + +import javax.management.NotCompliantMBeanException; + +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; +import ru.entaxy.platform.core.management.object.factory.ObjectsContainerMBean; +import ru.entaxy.platform.core.management.object.impl.EntaxyRuntimeObjectMBeanManager; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager.OperationResult; + +import java.util.stream.Collectors; + +@ContainerMBean(id = "objects", subQualifierValue = EntaxyRuntimeObjectMBeanFactory.JMX_DEFAULT_CATEGORY) +public class ObjectsContainerMBeanImpl extends AbstractObjectContainerMBean + implements ObjectsContainerMBean { + + protected EntaxyRuntimeObjectMBeanManager manager; + + protected ObjectsContainerMBeanImpl() throws NotCompliantMBeanException { + super(ObjectsContainerMBean.class); + } + + @Override + public void refresh() { + manager.refresh(); + } + + @Override + public String startBundle(String idOrName, String runtimeType, boolean forced, boolean soft) throws Exception { + if (ServiceHelper.getInstance() == null) { + throw new IllegalStateException("Service helper is not initialized"); + } + + String objectFullId = ServiceHelper.getInstance() + .entaxyObjectService.findObject(idOrName, runtimeType).getObjectFullId(); + + OperationResult result; + + if (forced) { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.startForced(objectFullId); + } else if (soft) { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.startSoft(objectFullId); + } else { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.start(objectFullId); + } + + return getOutput(result); + } + + @Override + public String stopBundle(String idOrName, String runtimeType, boolean forced, boolean soft) throws Exception { + if (ServiceHelper.getInstance() == null) { + throw new IllegalStateException("Service helper is not initialized"); + } + + String objectFullId = ServiceHelper.getInstance() + .entaxyObjectService.findObject(idOrName, runtimeType).getObjectFullId(); + + OperationResult result; + + if (forced) { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.stopForced(objectFullId); + } else if (soft) { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.stopSoft(objectFullId); + } else { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.stop(objectFullId); + } + + return getOutput(result); + } + + @Override + public String uninstallBundle(String idOrName, String runtimeType, boolean forced, boolean soft) throws Exception { + if (ServiceHelper.getInstance() == null) { + throw new IllegalStateException("Service helper is not initialized"); + } + + String objectFullId = ServiceHelper.getInstance() + .entaxyObjectService.findObject(idOrName, runtimeType).getObjectFullId(); + + OperationResult result; + + if (forced) { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.uninstallForced(objectFullId); + } else if (soft) { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.uninstallSoft(objectFullId); + } else { + result = ServiceHelper.getInstance().entaxyRuntimeObjectManager.uninstall(objectFullId); + } + + return getOutput(result); + } + + private String getOutput(OperationResult result) { + JsonObject jsonObject = new JsonObject(); + + jsonObject.addProperty("result", result.getResult().name()); + if (!result.getAffected().isEmpty()) { + JsonArray affectedArray = new JsonArray(); + for (String key : result.getAffected().keySet()) { + JsonObject affected = new JsonObject(); + affected.addProperty("objectId", key); + affected.addProperty("action", result.getAffected().get(key).name()); + affectedArray.add(affected); + } + jsonObject.addProperty("affected", affectedArray.toString()); + } + if (CommonUtils.isValid(result.getMessage())) { + jsonObject.addProperty("message", result.getMessage()); + } + + return jsonObject.toString(); + } + + public String findObjects(String osgiFilter) throws Exception { + return JSONUtils.GSON.toJson(manager.findObjects(osgiFilter).stream().map(object -> { + return object.getObjectFullId(); + }).collect(Collectors.toList())); + } +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/ServiceHelper.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/ServiceHelper.java new file mode 100644 index 00000000..2861f239 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/factory/impl/ServiceHelper.java @@ -0,0 +1,81 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.factory.impl; + +import org.apache.karaf.bundle.core.BundleInfo; +import org.apache.karaf.bundle.core.BundleService; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.*; +import ru.entaxy.platform.base.objects.EntaxyObjectService; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager; + +@Component(service = ServiceHelper.class, immediate = true) +public class ServiceHelper { + + private static ServiceHelper INSTANCE; + + public static ServiceHelper getInstance() { + return INSTANCE; + } + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public EntaxyObjectService entaxyObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public EntaxyRuntimeObjectManager entaxyRuntimeObjectManager; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + BundleService bundleService; + + BundleContext bundleContext; + + @Activate + public void activate(ComponentContext componentContext) { + INSTANCE = this; + this.bundleContext = componentContext.getBundleContext(); + } + + @Deactivate + public void deactivate() { + INSTANCE = null; + } + + public BundleService getBundleService() { + return bundleService; + } + + public BundleInfo getBundleInfo(long id) { + Bundle b = FrameworkUtil.getBundle(getClass()).getBundleContext().getBundle(id); + if (b == null) + return null; + return bundleService.getInfo(b); + } +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeItemMBeanInfo.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeItemMBeanInfo.java new file mode 100644 index 00000000..150d2b05 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeItemMBeanInfo.java @@ -0,0 +1,133 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.BundleContext; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; + +public class EntaxyRuntimeItemMBeanInfo { + + public enum ItemStatus { + NEW, + ACTIVE, + REREGISTER, + RECREATE, + REMOVE, + UNKNOWN + } + + public MBeanHolder mbeanHolder = null; + boolean isVirtual = false; + + protected BundleContext bundleContext; + + public ItemStatus itemStatus = ItemStatus.UNKNOWN; + + public ItemStatus status() { + return itemStatus; + } + + public ItemStatus status(ItemStatus newStatus) { + if (newStatus == null) + return status(ItemStatus.UNKNOWN); + this.itemStatus = newStatus; + return status(); + } + + public boolean isInStatus(ItemStatus checkStatus) { + return this.itemStatus.equals(checkStatus); + } + + EntaxyRuntimeItemMBeanInfo parentMBeanInfo; + + List> children = new ArrayList<>(); + + protected EntaxyRuntimeObjectMBeanFactory factory; + + public String getId() { + return mbeanHolder == null ? "" : mbeanHolder.mbean.getId(); + } + + public boolean createHolder(T mbean) { + mbeanHolder = MBeanHolder.create(mbean); + return isCreated(); + } + + public boolean isCreated() { + if (mbeanHolder == null) + return false; + return mbeanHolder.mbean != null; + } + + public boolean isRegistered() { + return isCreated() && (mbeanHolder.registration != null); + } + + public void setBundleContext(BundleContext bundleContext) { + this.bundleContext = bundleContext; + } + + public void register(BundleContext bundleContext) { + setBundleContext(bundleContext); + register(); + } + + public void register() { + try { + if (this.mbeanHolder.bundleContext == null) + this.mbeanHolder.bundleContext = this.bundleContext; + this.mbeanHolder.register(); + } catch (Exception ignore) { + // NOOP + } + } + + public void unregister() { + try { + this.mbeanHolder.unregister(); + } catch (Exception ignore) { + // NOOP + } + } + + public Map getAllChildMBeans() { + if (this.mbeanHolder != null) + return this.mbeanHolder.mbean.getChildMBeans(); + return Collections.emptyMap(); + }; + + public Map getPrimaryChildMBeans() { + return getAllChildMBeans(); + }; + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectContainerMBeanInfo.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectContainerMBeanInfo.java new file mode 100644 index 00000000..22a4ccc5 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectContainerMBeanInfo.java @@ -0,0 +1,33 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +public class EntaxyRuntimeObjectContainerMBeanInfo + extends EntaxyRuntimeItemMBeanInfo { + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanCustomizerHolder.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanCustomizerHolder.java new file mode 100644 index 00000000..4973c86d --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanCustomizerHolder.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import java.util.ArrayList; +import java.util.List; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanCustomizer; + +public class EntaxyRuntimeObjectMBeanCustomizerHolder { + + public EntaxyRuntimeObjectMBeanCustomizer customizer; + + public List> mbeanInfo = new ArrayList<>(); + + public EntaxyRuntimeObjectMBeanCustomizerHolder(EntaxyRuntimeObjectMBeanCustomizer customizer) { + this.customizer = customizer; + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanInfo.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanInfo.java new file mode 100644 index 00000000..333f557a --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanInfo.java @@ -0,0 +1,119 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeRelation; + +public class EntaxyRuntimeObjectMBeanInfo extends EntaxyRuntimeItemMBeanInfo { + + public enum LOAD_STATUS { + AUTO_LOADED, + LOADED, + NONE + } + + public EntaxyRuntimeObjectMBeanInfo(EntaxyRuntimeObject runtimeObject) { + this.runtimeObject = runtimeObject; + } + + String foundPattern; + + EntaxyRuntimeObject runtimeObject; + + EntaxyRuntimeObject parentObject; + + EntaxyRuntimeRelation relationFromParent; + + LOAD_STATUS loadStatus = LOAD_STATUS.NONE; + + Map> secondaryBeans = new HashMap<>(); + + public boolean isGhost() { + return this.runtimeObject.isGhost(); + } + + public void resetStatus() { + this.loadStatus = LOAD_STATUS.NONE; + } + + public void makeAutoLoaded() { + this.loadStatus = LOAD_STATUS.AUTO_LOADED; + } + + public boolean isAutoLoaded() { + return LOAD_STATUS.AUTO_LOADED.equals(this.loadStatus); + } + + public void makeLoaded() { + this.loadStatus = LOAD_STATUS.LOADED; + } + + public boolean isLoaded() { + return LOAD_STATUS.LOADED.equals(this.loadStatus); + } + + public boolean isUpdatedByLoad() { + return !LOAD_STATUS.NONE.equals(this.loadStatus); + } + + public void register() { + super.register(); + for (String key : secondaryBeans.keySet()) { + List list = secondaryBeans.get(key); + for (EntaxyRuntimeObjectMBeanInfo sMBean : list) + sMBean.register(this.bundleContext); + } + } + + public void unregister() { + for (String key : secondaryBeans.keySet()) { + List list = secondaryBeans.get(key); + for (EntaxyRuntimeObjectMBeanInfo sMBean : list) + sMBean.unregister(); + } + super.unregister(); + } + + @Override + public Map getPrimaryChildMBeans() { + final List secondariesIds = + secondaryBeans.values().stream().flatMap(list -> list.stream()) + .map(bi -> bi.mbeanHolder.mbean.getId()) + .collect(Collectors.toList()); + Map result = + getAllChildMBeans().entrySet().stream().filter(e -> !secondariesIds.contains(e.getValue().getId())) + .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); + return result; + } +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanManager.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanManager.java new file mode 100644 index 00000000..d4dc35b9 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/EntaxyRuntimeObjectMBeanManager.java @@ -0,0 +1,734 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.objects.EntaxyObject.OBJECT_RELATION; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanCustomizer; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanCustomizer.Customized; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.factory.impl.EntaxyObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.impl.EntaxyRuntimeItemMBeanInfo.ItemStatus; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeRelation; + +@Component(service = EntaxyRuntimeObjectMBeanManager.class, immediate = true) +public class EntaxyRuntimeObjectMBeanManager implements EntaxyRuntimeObjectService.Listener { + + private static final Logger log = LoggerFactory.getLogger(EntaxyRuntimeObjectMBeanManager.class); + + private static final String TYPE_WILDCARD = "*"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile EntaxyRuntimeObjectService entaxyRuntimeObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile EntaxyRuntimeObjectManager entaxyRuntimeObjectManager; + + protected static class FactorySearchResult { + + public static FactorySearchResult create(EntaxyRuntimeObjectMBeanFactory factory, String pattern) { + return new FactorySearchResult(factory, pattern); + } + + EntaxyRuntimeObjectMBeanFactory factory; + String pattern; + + protected FactorySearchResult(EntaxyRuntimeObjectMBeanFactory factory, String pattern) { + this.factory = factory; + this.pattern = pattern; + } + + } + + protected Map factoriesMap = new HashMap<>(); + + protected Map> infoById = new HashMap<>(); + + protected Map customizersMap = + new HashMap<>(); + + // protected Map> infoByJMXObjectName = new HashMap<>(); + + protected List toRemove = new ArrayList<>(); + + protected BundleContext bundleContext; + + protected boolean activated = false; + + protected Object lock = new Object(); + + @Activate + public EntaxyRuntimeObjectMBeanManager(BundleContext bundleContext) { + super(); + this.bundleContext = bundleContext; + + // add root factory + addFactory(new EntaxyObjectMBeanFactory(this)); + } + + + @Activate + public void activate(ComponentContext componentContext) { + // this.bundleContext = componentContext.getBundleContext(); + activated = true; + synchronized (lock) { + entaxyRuntimeObjectService.addListener(this); + loadCurrentObjects(); + } + + } + + + @Deactivate + public void deactivate() { + entaxyRuntimeObjectService.removeListener(this); + } + + @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY, + collectionType = CollectionType.SERVICE, unbind = "removeFactory") + public void addFactory(EntaxyRuntimeObjectMBeanFactory factory) { + synchronized (lock) { + for (String pattern : factory.getSupportedTypes()) { + factoriesMap.put(pattern, factory); + } + List mbeans = factory.createMBeans(); + if (mbeans != null) + for (EntaxyRuntimeItemMBean mbean : mbeans) { + EntaxyRuntimeItemMBeanInfo mbeanInfo = MBeanUtils.createMBeanInfo(mbean); + if (!mbeanInfo.isCreated()) { + log.error("Error creating MBeanInfo for mbean [{}]", mbean.getId()); + continue; + } + if (infoById.containsKey(mbeanInfo.getId())) { + try { + infoById.get(mbeanInfo.getId()).unregister(); + } catch (Exception ignore) { + // ignore + } + } + infoById.put(mbeanInfo.getId(), mbeanInfo); + mbeanInfo.register(bundleContext); + } + + + // review all created mbeans if they suit newly added factory + + List infoToRecreate = new ArrayList<>(); + List> infoToReregister = new ArrayList<>(); + + for (EntaxyRuntimeItemMBeanInfo itemInfo : infoById.values()) { + if (!(itemInfo instanceof EntaxyRuntimeObjectMBeanInfo)) + continue; + EntaxyRuntimeObjectMBeanInfo mBeanInfo = (EntaxyRuntimeObjectMBeanInfo) itemInfo; + FactorySearchResult result = findFactory(mBeanInfo.runtimeObject); + if (result.factory.getId().equals(factory.getId())) + if (!infoToRecreate.contains(mBeanInfo)) + infoToRecreate.add(mBeanInfo); + } + + List itemsToReregister = new ArrayList<>(); + + for (EntaxyRuntimeObjectMBeanInfo mBeanInfo : infoToRecreate) + collectCascadeChildren(itemsToReregister, mBeanInfo.mbeanHolder.mbean); + + infoToReregister.addAll(itemsToReregister.stream() + .map(item -> infoById.get(item.getId())) + .filter(item -> item != null) + .collect(Collectors.toList())); + infoToReregister.removeAll(infoToRecreate); + + List runtimeObjects = infoToRecreate.stream() + .map(inf -> inf.runtimeObject) + .collect(Collectors.toList()); + + ObjectHelper helper = new ObjectHelper(runtimeObjects); + + List recreatedInfos = helper.load(); + + List toRegister = new ArrayList<>(); + + for (EntaxyRuntimeObjectMBeanInfo newInfo : recreatedInfos) { + + EntaxyRuntimeObjectMBeanInfo oldInfo = (EntaxyRuntimeObjectMBeanInfo) infoById.get(newInfo.getId()); + + if (oldInfo == null) { + + // just add + + infoById.put(newInfo.getId(), newInfo); + newInfo.setBundleContext(bundleContext); + newInfo.status(ItemStatus.REREGISTER); + toRegister.add(newInfo); + } else { + + // mbean info already exists + + if (newInfo.isAutoLoaded()) { + + // object loaded only as someone's parent + // so we just switch the children links + switchChildren(newInfo.mbeanHolder.mbean, oldInfo.mbeanHolder.mbean); + + if (oldInfo.isInStatus(ItemStatus.REMOVE)) + oldInfo.status(ItemStatus.REREGISTER); + + } else if (newInfo.isLoaded()) { + + // unregister existing mbean + oldInfo.unregister(); + + updateObjectMBeanInfo(newInfo, oldInfo, toRegister); + + switchChildren(oldInfo.mbeanHolder.mbean, newInfo.mbeanHolder.mbean); + + // detach old secondaries from parent + for (String key : oldInfo.secondaryBeans.keySet()) { + List list = oldInfo.secondaryBeans.get(key); + for (EntaxyRuntimeObjectMBeanInfo bi : list) + bi.mbeanHolder.mbean.setParentMBean(null); + } + + // remove all secondaries + oldInfo.secondaryBeans.clear(); + + // add new secondaries + oldInfo.secondaryBeans.putAll(newInfo.secondaryBeans); + + // set new mbean + oldInfo.mbeanHolder.mbean = newInfo.mbeanHolder.mbean; + + oldInfo.status(ItemStatus.REREGISTER); + + // schedule existing to re-register + toRegister.add(oldInfo); + + } + + } + + } + + /* + * for (EntaxyRuntimeObjectMBeanInfo mBeanInfo : infoToRecreate) { FactorySearchResult + * searchResult = findFactory(mBeanInfo.runtimeObject); EntaxyRuntimeObjectMBean + * newMBean = searchResult.factory.createMBean(mBeanInfo.runtimeObject); + * EntaxyRuntimeObjectMBeanInfo newInfo = (EntaxyRuntimeObjectMBeanInfo) + * MBeanUtils.createMBeanInfo(newMBean); + * + * mBeanInfo.mbeanHolder.unregister(); + * + * if (newInfo.mbeanHolder.mbean.getParentMBean() == null) { + * newInfo.mbeanHolder.mbean.setParentMBean(mBeanInfo.mbeanHolder.mbean.getParentMBean() + * ); } + * + * // unlink from parent and switch children + * mBeanInfo.mbeanHolder.mbean.setParentMBean(null); + * switchChildren(mBeanInfo.mbeanHolder.mbean, newInfo.mbeanHolder.mbean); + * + * infoById.put(newInfo.getId(), newInfo); newInfo.mbeanHolder.bundleContext = + * bundleContext; newInfo.mbeanHolder.register(); } + */ + + for (EntaxyRuntimeItemMBeanInfo toReg : toRegister) { + toReg.unregister(); + toReg.register(); + } + + infoToReregister.removeAll(toRegister); + + for (EntaxyRuntimeItemMBeanInfo toReg : infoToReregister) { + toReg.unregister(); + toReg.register(); + } + } + + + } + + public void refresh() { + synchronized (lock) { + toRemove.addAll(infoById.values().stream() + .filter(v -> (v instanceof EntaxyRuntimeObjectMBeanInfo)) + .map(v -> EntaxyRuntimeObjectMBeanInfo.class.cast(v)) + .collect(Collectors.toList())); + tryToRemove(); + loadCurrentObjects(); + } + } + + public void removeFactory(EntaxyRuntimeObjectMBeanFactory factory) { + for (String pattern : factory.getSupportedTypes()) { + factoriesMap.remove(pattern); + } + } + + @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY, + collectionType = CollectionType.SERVICE, unbind = "removeCustomizer") + public void addCustomizer(EntaxyRuntimeObjectMBeanCustomizer customizer) { + + synchronized (lock) { + + EntaxyRuntimeObjectMBeanCustomizerHolder holder = customizersMap.get(customizer.getId()); + + if (holder != null) { + // just switch to new customizer + holder.customizer = customizer; + } else { + holder = new EntaxyRuntimeObjectMBeanCustomizerHolder(customizer); + + customizersMap.put(customizer.getId(), holder); + + for (EntaxyRuntimeItemMBeanInfo itemInfo : infoById.values()) { + + if ((itemInfo.mbeanHolder == null) + || !(itemInfo.mbeanHolder.mbean instanceof EntaxyRuntimeObjectMBean)) + continue; + + if (!customizer.isAccepted((EntaxyRuntimeObjectMBean) itemInfo.mbeanHolder.mbean)) + continue; + + EntaxyRuntimeObjectMBeanInfo objectInfo = (EntaxyRuntimeObjectMBeanInfo) itemInfo; + + Customized customized = customizer.customize(objectInfo.mbeanHolder.mbean); + + if (customized.getAdditionalMBeans() == null || customized.getAdditionalMBeans().isEmpty()) + continue; + + List secondaries = customized.getAdditionalMBeans().stream() + .map(b -> (EntaxyRuntimeObjectMBeanInfo) MBeanUtils.createMBeanInfo(b)).map(bi -> { + bi.status(ItemStatus.NEW); + bi.runtimeObject = objectInfo.runtimeObject; + return bi; + }).collect(Collectors.toList()); + + for (EntaxyRuntimeObjectMBeanInfo bi : secondaries) { + bi.register(bundleContext); + } + + objectInfo.secondaryBeans.put(customizer.getId(), secondaries); + + } + + } + + } + + } + + public void removeCustomizer(EntaxyRuntimeObjectMBeanCustomizer customizer) { + synchronized (lock) { + + for (EntaxyRuntimeItemMBeanInfo itemInfo : infoById.values()) { + + if ((itemInfo.mbeanHolder == null) + || !(itemInfo.mbeanHolder.mbean instanceof EntaxyRuntimeObjectMBean)) + continue; + + EntaxyRuntimeObjectMBeanInfo objectInfo = (EntaxyRuntimeObjectMBeanInfo) itemInfo; + + if (objectInfo.secondaryBeans.containsKey(customizer.getId())) { + for (EntaxyRuntimeObjectMBeanInfo sBean : objectInfo.secondaryBeans.get(customizer.getId())) + sBean.unregister(); + objectInfo.secondaryBeans.remove(customizer.getId()); + } + + } + + customizersMap.remove(customizer.getId()); + } + + } + + protected void loadCurrentObjects() { + + ObjectHelper helper = new ObjectHelper(entaxyRuntimeObjectService.getObjects()); + List mBeanInfoList = helper.load(); + + for (EntaxyRuntimeObjectMBeanInfo mBeanInfo : mBeanInfoList) { + infoById.put(mBeanInfo.getId(), mBeanInfo); + mBeanInfo.register(bundleContext); + mBeanInfo.resetStatus(); + } + + } + + protected FactorySearchResult findFactory(EntaxyRuntimeObject entaxyRuntimeObject) { + EntaxyRuntimeObjectMBeanFactory result = null; + String type = entaxyRuntimeObject.getType(); + while (CommonUtils.isValid(type)) { + result = factoriesMap.get(type); + if (result != null) + return FactorySearchResult.create(result, type); + int index = type.lastIndexOf('.'); + if (index < 0) { + if (type.equals(TYPE_WILDCARD)) + type = ""; + else + type = TYPE_WILDCARD; + } else { + if (type.endsWith(TYPE_WILDCARD)) + type = type.substring(0, index); + else { + type = type.substring(0, index).concat(".").concat(TYPE_WILDCARD); + } + } + } + + return FactorySearchResult.create(null, ""); + } + + protected void findFactory(EntaxyRuntimeObjectMBeanInfo mBeanInfo) { + FactorySearchResult searchResult = findFactory(mBeanInfo.runtimeObject); + if (searchResult != null) { + mBeanInfo.factory = searchResult.factory; + mBeanInfo.foundPattern = searchResult.pattern; + } + } + + + // EntaxyRuntimeObjectService.Listener + + @Override + public void objectAdded(EntaxyRuntimeObject object) { + if (object == null) + return; + synchronized (lock) { + ObjectHelper helper = new ObjectHelper(Collections.singletonList(object)); + List mBeanInfoList = helper.load(); + + List toRegister = new ArrayList<>(); + + for (EntaxyRuntimeObjectMBeanInfo mBeanInfo : mBeanInfoList) { + + if (!infoById.containsKey(mBeanInfo.getId())) { + + // just add + + infoById.put(mBeanInfo.getId(), mBeanInfo); + mBeanInfo.setBundleContext(bundleContext);; + mBeanInfo.status(ItemStatus.REREGISTER); + toRegister.add(mBeanInfo); + } else { + + // mbean info already exists + + EntaxyRuntimeObjectMBeanInfo existing = + (EntaxyRuntimeObjectMBeanInfo) infoById.get(mBeanInfo.getId()); + + if (mBeanInfo.isAutoLoaded()) { + + // object loaded only as someone's parent + // so we just switch the children links + // switchChildren(mBeanInfo.mbeanHolder.mbean, existing.mbeanHolder.mbean); + + switchChildren(mBeanInfo.mbeanHolder.mbean, existing.mbeanHolder.mbean, + existing.secondaryBeans.values().stream().flatMap(list -> list.stream()) + .map(bi -> bi.mbeanHolder.mbean).collect(Collectors.toList())); + + if (existing.isInStatus(ItemStatus.REMOVE)) + existing.status(ItemStatus.REREGISTER); + + } else if (mBeanInfo.isLoaded()) { + + // unregister existing mbean + existing.unregister(); + + updateObjectMBeanInfo(mBeanInfo, existing, toRegister); + + // switchChildren(existing.mbeanHolder.mbean, mBeanInfo.mbeanHolder.mbean); + + switchChildren(existing.mbeanHolder.mbean, mBeanInfo.mbeanHolder.mbean, + existing.secondaryBeans.values().stream().flatMap(list -> list.stream()) + .map(bi -> bi.mbeanHolder.mbean).collect(Collectors.toList())); + + // detach old secondaries from parent + for (String key : existing.secondaryBeans.keySet()) { + List list = existing.secondaryBeans.get(key); + for (EntaxyRuntimeObjectMBeanInfo bi : list) + bi.mbeanHolder.mbean.setParentMBean(null); + } + + // remove all secondaries + existing.secondaryBeans.clear(); + + // add new secondaries + existing.secondaryBeans.putAll(mBeanInfo.secondaryBeans); + + // set new mbean + existing.mbeanHolder.mbean = mBeanInfo.mbeanHolder.mbean; + + existing.status(ItemStatus.REREGISTER); + + // schedule existing to re-register + toRegister.add(existing); + + } + + } + + } + + for (EntaxyRuntimeObjectMBeanInfo mbean : toRegister) { + if (mbean.isRegistered()) + mbean.unregister(); + mbean.register(); + } + + } + + } + + protected void switchChildren(EntaxyRuntimeItemMBean fromMBean, EntaxyRuntimeItemMBean toMBean, + List ignore) { + + // avoid cuncurrent modifications + List children = new ArrayList<>(fromMBean.getChildMBeans().values()); + + for (EntaxyRuntimeItemMBean child : children) + if (!ignore.contains(child)) + child.setParentMBean(toMBean); + + } + + protected void switchChildren(EntaxyRuntimeItemMBean fromMBean, EntaxyRuntimeItemMBean toMBean) { + + // avoid cuncurrent modifications + List children = new ArrayList<>(fromMBean.getChildMBeans().values()); + + for (EntaxyRuntimeItemMBean child : children) + child.setParentMBean(toMBean); + } + + protected void updateObjectMBeanInfo(EntaxyRuntimeObjectMBeanInfo fromMBeanInfo, + EntaxyRuntimeObjectMBeanInfo toMBeanInfo, List affectedItems) { + + // switch existing children to new mbean + // and schedule them to re-register + /* + * List children = new + * ArrayList<>(fromMBeanInfo.mbeanHolder.mbean.getChildMBeans().values()); for + * (EntaxyRuntimeItemMBean child : children) { + * child.setParentMBean(toMBeanInfo.mbeanHolder.mbean); if + * (!affectedItems.contains(infoById.get(child.getId()))) + * affectedItems.add((EntaxyRuntimeObjectMBeanInfo) infoById.get(child.getId())); + * + * List cascadeChildren = new ArrayList<>(); + * collectCascadeChildren(cascadeChildren, child); affectedItems.addAll( + * cascadeChildren.stream() .map(c -> (EntaxyRuntimeObjectMBeanInfo) + * infoById.get(c.getId())) .collect(Collectors.toList())); } + */ + // set parent to new mbean + // existing.mbeanHolder.mbean.setParentMBean(mBeanInfo.mbeanHolder.mbean.getParentMBean()); + // toMBeanInfo.mbeanHolder.mbean.setParentMBean(null); + + // update existing + toMBeanInfo.factory = fromMBeanInfo.factory; + toMBeanInfo.foundPattern = fromMBeanInfo.foundPattern; + toMBeanInfo.relationFromParent = fromMBeanInfo.relationFromParent; + toMBeanInfo.runtimeObject = fromMBeanInfo.runtimeObject; + + } + + protected void collectCascadeChildren(List result, EntaxyRuntimeItemMBean startMBean) { + for (EntaxyRuntimeItemMBean child : startMBean.getChildMBeans().values()) { + result.add(child); + collectCascadeChildren(result, child); + } + } + + @Override + public void objectModified(EntaxyRuntimeObject object) { + // we'll do the same as when an object is added + objectAdded(object); + } + + @Override + public void objectRemoved(EntaxyRuntimeObject object) { + synchronized (lock) { + if (!infoById.containsKey(object.getObjectFullId())) + return; + toRemove.add((EntaxyRuntimeObjectMBeanInfo) infoById.get(object.getObjectFullId())); + tryToRemove(); + } + } + + protected void tryToRemove() { + int currentSize = -1; + while (currentSize != toRemove.size()) { + currentSize = toRemove.size(); + List removed = new ArrayList<>(); + for (EntaxyRuntimeObjectMBeanInfo item : toRemove) { + if (item.isRegistered()) + item.unregister(); + // if (item.mbeanHolder.mbean.getChildMBeans().isEmpty()) { + if (item.getPrimaryChildMBeans().isEmpty()) { + // remove from parent + item.mbeanHolder.mbean.setParentMBean(null); + // remove + infoById.remove(item.getId()); + + removed.add(item); + } + } + toRemove.removeAll(removed); + } + } + + // Util classes + + protected class ObjectHelper { + + List objects; + + Map createdInfo = new HashMap<>(); + + public ObjectHelper(List objects) { + this.objects = objects; + } + + public List load() { + + // create Mbean info objects + for (EntaxyRuntimeObject object : this.objects) { + String objectId = object.getObjectFullId(); + + EntaxyRuntimeObjectMBeanInfo mBeanInfo = getOrCreateMBeanInfo(object); + if (mBeanInfo == null) + continue; + + mBeanInfo.makeLoaded(); + + EntaxyRuntimeObjectMBean mBean = mBeanInfo.mbeanHolder.mbean; + + List relations = object.getIncomiingRelations(OBJECT_RELATION.COMPOSITION); + if (relations.isEmpty()) + relations = object.getIncomiingRelations(OBJECT_RELATION.AGGREGATION); + if (relations.isEmpty()) + continue; + + EntaxyRuntimeRelation parentLink = relations.get(0); + EntaxyRuntimeObject parentObject = parentLink.getMain(); + String parentObjectId = parentObject.getObjectFullId(); + EntaxyRuntimeObjectMBeanInfo mBeanInfoParent = getOrCreateMBeanInfo(parentObject); + + if (!mBeanInfoParent.isLoaded()) + mBeanInfoParent.makeAutoLoaded(); + + mBean.setParentMBean(mBeanInfoParent.mbeanHolder.mbean); + if (CommonUtils.isValid(parentLink.getName())) + mBean.setJMXSubQualifierName(parentLink.getName()); + mBean.setParentSubPath(parentLink.getGroup()); + } + + return new ArrayList<>(createdInfo.values()); + + } + + protected EntaxyRuntimeObjectMBeanInfo getOrCreateMBeanInfo(EntaxyRuntimeObject object) { + String objectId = object.getObjectFullId(); + if (!createdInfo.containsKey(objectId)) { + FactorySearchResult searchResult = findFactory(object); + if (searchResult.factory == null) { + log.warn("No MBean factory found for object [{}]", objectId); + return null; + } + EntaxyRuntimeObjectMBean mBean = searchResult.factory.createMBean(object); + EntaxyRuntimeObjectMBeanInfo mBeanInfo = + (EntaxyRuntimeObjectMBeanInfo) MBeanUtils.createMBeanInfo(mBean); + + for (EntaxyRuntimeObjectMBeanCustomizerHolder holder : customizersMap.values()) { + EntaxyRuntimeObjectMBeanCustomizer customizer = holder.customizer; + if (customizer.isAccepted(mBean)) { + Customized customized = customizer.customize(mBean); + if (customized.getAdditionalMBeans() != null && !customized.getAdditionalMBeans().isEmpty()) + mBeanInfo.secondaryBeans.put(customizer.getId(), + customized.getAdditionalMBeans().stream() + .map(b -> (EntaxyRuntimeObjectMBeanInfo) MBeanUtils.createMBeanInfo(b)) + .map(bi -> { + bi.status(ItemStatus.NEW); + bi.runtimeObject = object; + return bi; + }) + .collect(Collectors.toList())); + } + + } + + mBeanInfo.status(ItemStatus.NEW); + mBeanInfo.runtimeObject = object; + createdInfo.put(objectId, mBeanInfo); + return mBeanInfo; + } else { + return createdInfo.get(objectId); + } + + } + } + + public Map getFactoriesMap() { + return Collections.unmodifiableMap(factoriesMap); + } + + + public Map> getInfoById() { + return Collections.unmodifiableMap(infoById); + } + + public List findObjects(String osgiFilter) throws InvalidSyntaxException { + return entaxyRuntimeObjectService.findObjects(osgiFilter); + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/MBeanHolder.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/MBeanHolder.java new file mode 100644 index 00000000..3a43088c --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/MBeanHolder.java @@ -0,0 +1,150 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Hashtable; +import java.util.Iterator; + +import javax.management.DynamicMBean; +import javax.management.MBeanRegistration; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceRegistration; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; + +public class MBeanHolder { + + private static final Logger log = LoggerFactory.getLogger(MBeanHolder.class); + + public static MBeanHolder create(S mbean) { + MBeanHolder result = new MBeanHolder(); + result.mbean = mbean; + result.objectId = mbean.getId(); + return result; + } + + public static MBeanHolder register(Class mbeanClass, + S mbean, + Dictionary properties, + BundleContext bundleContext) { + + MBeanHolder result = create(mbean); + + if (properties != null) { + result.clearProperties(); + Enumeration keys = properties.keys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + result.registrationProperties.put(key, properties.get(key)); + } + } + + if (mbeanClass != null) + result.register(mbeanClass); + else + result.register(); + + return result; + } + + ServiceRegistration registration; + + public String objectId; + + public T mbean; + + Dictionary registrationPropertiesDefaults = new Hashtable<>(); + + Dictionary registrationProperties = new Hashtable<>(); + + BundleContext bundleContext; + + public void clearProperties() { + this.registrationProperties = new Hashtable<>(); + } + + protected void loadDefaultProperties() { + Iterator iter = registrationPropertiesDefaults.keys().asIterator(); + while (iter.hasNext()) { + String key = iter.next(); + registrationProperties.put(key, registrationPropertiesDefaults.get(key)); + } + } + + public void register() { + if (this.mbean == null) + return; + register(this.mbean.getMBeanClass()); + } + + public void register(Class mbeanClass) { + if (this.mbean == null) + return; + + unregister(); + + String[] classes = new String[] { + mbeanClass.getName(), + DynamicMBean.class.getName(), + MBeanRegistration.class.getName() + }; + + loadDefaultProperties(); + + if (registrationProperties.get(ManagementCore.JMX_OBJECTNAME) == null) { + registrationProperties.put(ManagementCore.JMX_OBJECTNAME, + MBeanUtils.addNamespace(MBeanUtils.calculateJmxObjectName(mbean))); + } + + try { + registration = bundleContext.registerService(classes, mbean, registrationProperties); + } catch (Exception e) { + log.error("Error registering MBean [" + mbean.getId() + "]", e); + } + + } + + + public void unregister() { + if (registration != null) { + try { + registration.unregister(); + } catch (Exception ignore) { + // NOOP + } + + registration = null; + + } + clearProperties(); + } +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/MBeanUtils.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/MBeanUtils.java new file mode 100644 index 00000000..3bc47892 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/impl/MBeanUtils.java @@ -0,0 +1,101 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.impl; + +import java.util.Arrays; +import java.util.stream.Collectors; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +public class MBeanUtils { + + + public static EntaxyRuntimeItemMBeanInfo createMBeanInfo(EntaxyRuntimeItemMBean mBean) { + if (EntaxyRuntimeObjectMBean.class.isAssignableFrom(mBean.getMBeanClass())) { + EntaxyRuntimeObjectMBeanInfo mBeanInfo = new EntaxyRuntimeObjectMBeanInfo( + ((EntaxyRuntimeObjectMBean) mBean).getRuntimeObject()); + mBeanInfo.createHolder((EntaxyRuntimeObjectMBean) mBean); + return mBeanInfo; + } else { + EntaxyRuntimeObjectContainerMBeanInfo mBeanInfo = new EntaxyRuntimeObjectContainerMBeanInfo(); + mBeanInfo.createHolder((EntaxyRuntimeObjectContainerMBean) mBean); + return mBeanInfo; + } + } + + public static String calculateJmxObjectName(EntaxyRuntimeItemMBean mbean) { + return calculateJmxObjectName(mbean, EntaxyRuntimeItemMBean.JMX_SUBPATH_QUALIFIER); + } + + public static String calculateJmxObjectName(EntaxyRuntimeItemMBean mbean, String subPathQualifier) { + String finalName = mbean.getJMXSubQualifier(); + EntaxyRuntimeItemMBean currentMbean = mbean.getParentMBean(); + String parentSubPath = mbean.getParentSubPath(); + + String levelPlaceholderConstant = "@LEVEL@"; + + finalName = finalName.replace(EntaxyRuntimeItemMBean.JMX_SUBQUALIFIER_AUTO, + subPathQualifier.concat("_").concat(levelPlaceholderConstant)); + + while (currentMbean != null) { + String newName = currentMbean.getJMXSubQualifier(); + if (CommonUtils.isValid(parentSubPath)) { + // we must create unique, but idempotent set of keys + // as a key we'll use subPathQualifier with level index + String subpath = Arrays.asList(parentSubPath.split("/")) + .stream() + .map(s -> subPathQualifier.concat("_").concat(levelPlaceholderConstant).concat("=").concat(s)) + .collect(Collectors.joining(",")); + if (CommonUtils.isValid(subpath)) + newName = newName.concat(",").concat(subpath); + } + + finalName = newName.concat(",").concat(finalName); + parentSubPath = currentMbean.getParentSubPath(); + currentMbean = currentMbean.getParentMBean(); + } + + // replace placeholder with overall level value + String[] splitted = finalName.split(","); + for (int i = 0; i < splitted.length; i++) { + splitted[i] = splitted[i].replace(levelPlaceholderConstant, "" + i); + } + finalName = Arrays.asList(splitted).stream().collect(Collectors.joining(",")); + + return finalName; + } + + public static String addNamespace(String qualifier) { + if (qualifier.contains(":")) + return qualifier; + return ManagementCore.ENTAXY_JMX_DOMAIN.concat(":").concat(qualifier); + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/EntaxyRuntimeObjectMBeanManagerSupport.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/EntaxyRuntimeObjectMBeanManagerSupport.java new file mode 100644 index 00000000..9f70018d --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/EntaxyRuntimeObjectMBeanManagerSupport.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.shell; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; + +import ru.entaxy.platform.core.management.object.impl.EntaxyRuntimeObjectMBeanManager; + +public class EntaxyRuntimeObjectMBeanManagerSupport { + + public static final String COMMAND_SCOPE = "entaxy"; + + @Reference + public EntaxyRuntimeObjectMBeanManager mBeanManager; + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/ListMBeanFactories.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/ListMBeanFactories.java new file mode 100644 index 00000000..74329199 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/ListMBeanFactories.java @@ -0,0 +1,59 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.shell; + +import java.util.HashSet; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; + +@Service +@Command(scope = EntaxyRuntimeObjectMBeanManagerSupport.COMMAND_SCOPE, name = "object-mbean-factory-list") +public class ListMBeanFactories extends EntaxyRuntimeObjectMBeanManagerSupport implements Action { + + @Override + public Object execute() throws Exception { + ShellTableFixed shellTable = new ShellTableFixed(); + shellTable.column("Id"); + shellTable.column("Supported types"); + + for (EntaxyRuntimeObjectMBeanFactory factory : new HashSet<>(mBeanManager.getFactoriesMap().values())) { + shellTable.addRow().addContent( + factory.getId(), + factory.getSupportedTypes().stream().collect(Collectors.joining("\n"))); + } + + shellTable.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/ListMBeans.java b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/ListMBeans.java new file mode 100644 index 00000000..28a0a0c6 --- /dev/null +++ b/platform/runtime/core/management/object-management/src/main/java/ru/entaxy/platform/core/management/object/shell/ListMBeans.java @@ -0,0 +1,77 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.object.shell; + +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableFixed; +import ru.entaxy.platform.core.management.object.impl.EntaxyRuntimeItemMBeanInfo; +import ru.entaxy.platform.core.management.object.impl.EntaxyRuntimeObjectMBeanInfo; + +@Service +@Command(scope = EntaxyRuntimeObjectMBeanManagerSupport.COMMAND_SCOPE, name = "object-mbean-list") +public class ListMBeans extends EntaxyRuntimeObjectMBeanManagerSupport implements Action { + + @Override + public Object execute() throws Exception { + ShellTableFixed shellTable = new ShellTableFixed(); + shellTable.column("Object Id"); + shellTable.column("Type"); + shellTable.column("Class name"); + shellTable.column("Registered"); + shellTable.column("Parent Id"); + shellTable.column("Ghost"); + + Map> map = mBeanManager.getInfoById(); + for (Entry> entry : map.entrySet()) { + + EntaxyRuntimeItemMBeanInfo info = entry.getValue(); + + shellTable.addRow().addContent( + entry.getKey(), + info instanceof EntaxyRuntimeObjectMBeanInfo ? "OBJECT" : "CONTAINER", + info.mbeanHolder.mbean == null ? "" : info.mbeanHolder.mbean.getClass().getName(), + info.isRegistered() ? "*" : "", + info.mbeanHolder.mbean == null ? "" + : info.mbeanHolder.mbean.getParentMBean() == null ? "" + : info.mbeanHolder.mbean.getParentMBean().getId(), + info instanceof EntaxyRuntimeObjectMBeanInfo + ? ((EntaxyRuntimeObjectMBeanInfo) info).isGhost() ? "*" : "" + : ""); + + } + + shellTable.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/AccountHelper.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/AccountHelper.java new file mode 100644 index 00000000..fb0fa4c9 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/AccountHelper.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import ru.entaxy.platform.core.management.profile.support.legacy.AccountManager; + +public interface AccountHelper extends AccountManager { + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/AccountHelperImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/AccountHelperImpl.java new file mode 100644 index 00000000..b062c074 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/AccountHelperImpl.java @@ -0,0 +1,95 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.profile.NotBackwardCompatibleException; +import ru.entaxy.platform.core.management.profile.support.legacy.AccountManager; + +@Component(service = AccountHelper.class, immediate = true) +public class AccountHelperImpl implements AccountHelper { + + private static final Logger LOG = LoggerFactory.getLogger(AccountHelperImpl.class); + + protected AccountManager accountManager = null; + + protected AccountManager nullAccountManager = null; + + @Activate + public void activate() { + this.nullAccountManager = new AccountManager() { + + @Override + public String getAccountForSystem(String systemUuid) throws Exception { + throw new NotBackwardCompatibleException(Helpers.BACKWARD_COMPATIBILITY_DISABLED); + } + + @Override + public void createAccountForSystem(String login, String password, String systemUUID, String createdBy, + String editedBy) throws Exception { + throw new NotBackwardCompatibleException(Helpers.BACKWARD_COMPATIBILITY_DISABLED); + } + + }; + } + + @Reference(collectionType = CollectionType.SERVICE, cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, + service = AccountManager.class, unbind = "unsetAccountManager") + public void setAccountManager(AccountManager accountManager) { + this.accountManager = accountManager; + } + + public void unsetAccountManager(AccountManager accountManager) { + this.accountManager = null; + } + + protected AccountManager getEffectiveAccountManager() { + return accountManager != null ? accountManager : nullAccountManager; + } + + @Override + public String getAccountForSystem(String systemUuid) throws Exception { + return getEffectiveAccountManager().getAccountForSystem(systemUuid); + } + + @Override + public void createAccountForSystem(String login, String password, String systemUUID, String createdBy, + String editedBy) throws Exception { + getEffectiveAccountManager().createAccountForSystem(login, password, systemUUID, createdBy, editedBy); + } + + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ConnectorHelper.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ConnectorHelper.java new file mode 100644 index 00000000..fc6e95a4 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ConnectorHelper.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import ru.entaxy.platform.core.management.profile.support.legacy.ConnectorManager; + +public interface ConnectorHelper extends ConnectorManager { + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ConnectorHelperImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ConnectorHelperImpl.java new file mode 100644 index 00000000..fcf8a84b --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ConnectorHelperImpl.java @@ -0,0 +1,122 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import java.util.Map; + +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.profile.NotBackwardCompatibleException; +import ru.entaxy.platform.core.management.profile.support.legacy.ConnectorManager; + +@Component(service = ConnectorHelper.class, immediate = true) +public class ConnectorHelperImpl implements ConnectorHelper { + + private static final Logger log = LoggerFactory.getLogger(ProfileHelperImpl.class); + + protected static final String EXPLANATION = Helpers.BACKWARD_COMPATIBILITY_DISABLED; + + protected ConnectorManager connectorManager = null; + + protected ConnectorManager nullConnectorManager = null; + + @Activate + public void activate(ComponentContext componentContext) { + this.nullConnectorManager = new ConnectorManager() { + + @Override + public void stopConnector(String idOrName, String connectorName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void startConnector(String idOrName, String connectorName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void removeConnector(String idOrName, String connectorName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void addConnector(String idOrName, String connectorFactoryId, Map parameters) + throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + }; + } + + public ConnectorManager getEffectiveConnectorManager() { + return connectorManager != null ? connectorManager : nullConnectorManager; + } + + @Reference(collectionType = CollectionType.SERVICE, cardinality = ReferenceCardinality.OPTIONAL, + policyOption = ReferencePolicyOption.GREEDY, policy = ReferencePolicy.DYNAMIC, + service = ConnectorManager.class, + unbind = "unsetConnectorManager") + public void setConnectorManager(ConnectorManager connectorManager) { + this.connectorManager = connectorManager; + log.debug(">> ConnectorManager is bound"); + } + + public void unsetConnectorManager(ConnectorManager connectorManager) { + this.connectorManager = null; + log.debug(">> ConnectorManager is unbound"); + } + + + @Override + public void addConnector(String idOrName, String connectorFactoryId, Map parameters) + throws Exception { + getEffectiveConnectorManager().addConnector(idOrName, connectorFactoryId, parameters); + } + + @Override + public void removeConnector(String idOrName, String connectorName) throws Exception { + getEffectiveConnectorManager().removeConnector(idOrName, connectorName); + } + + @Override + public void startConnector(String idOrName, String connectorName) throws Exception { + getEffectiveConnectorManager().startConnector(idOrName, connectorName); + } + + @Override + public void stopConnector(String idOrName, String connectorName) throws Exception { + getEffectiveConnectorManager().stopConnector(idOrName, connectorName); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/Helpers.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/Helpers.java new file mode 100644 index 00000000..de7869de --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/Helpers.java @@ -0,0 +1,68 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.platform.base.objects.EntaxyObjectService; + +@Component(service = Helpers.class, immediate = true) +public class Helpers { + + public static final String BACKWARD_COMPATIBILITY_DISABLED = + "You're calling deprecated API, to use it backward compatibility modules must be installed"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public ProfileHelper profileHelper; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public ConnectorHelper connectorHelper; + + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public PermissionHelper permissionHelper; + + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public EntaxyObjectService entaxyObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public SystemHelper systemHelper; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public AccountHelper accountHelper; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/PermissionHelper.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/PermissionHelper.java new file mode 100644 index 00000000..9b3a8c73 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/PermissionHelper.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import ru.entaxy.platform.core.management.profile.support.legacy.PermissionManager; + +public interface PermissionHelper extends PermissionManager { + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/PermissionHelperImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/PermissionHelperImpl.java new file mode 100644 index 00000000..c4911696 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/PermissionHelperImpl.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import java.util.List; + +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.profile.NotBackwardCompatibleException; +import ru.entaxy.platform.core.management.profile.support.legacy.PermissionManager; + +@Component(service = PermissionHelper.class, immediate = true) +public class PermissionHelperImpl implements PermissionHelper { + + private static final Logger log = LoggerFactory.getLogger(PermissionHelperImpl.class); + + protected static final String EXPLANATION = Helpers.BACKWARD_COMPATIBILITY_DISABLED; + + protected PermissionManager permissionManager = null; + + protected PermissionManager nullPermissionManager = null; + + @Activate + public void activate(ComponentContext componentContext) { + this.nullPermissionManager = new PermissionManager() { + + @Override + public List getSubjectPermissions(String subjectId) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public List getObjectPermissions(String objectId) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void createPermission(String objectId, String subjectId) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + }; + } + + public PermissionManager getEffectivePermissionManager() { + return this.permissionManager != null ? this.permissionManager : this.nullPermissionManager; + } + + @Reference(collectionType = CollectionType.SERVICE, cardinality = ReferenceCardinality.OPTIONAL, + policyOption = ReferencePolicyOption.GREEDY, service = PermissionManager.class, + unbind = "unsetPermissionManager") + public void setPermissionManager(PermissionManager permissionManager) { + this.permissionManager = permissionManager; + log.debug(">> PermissionManager is bound"); + } + + public void unsetPermissionManager(PermissionManager permissionManager) { + this.permissionManager = null; + log.debug(">> PermissionManager is unbound"); + } + + + + @Override + public List getObjectPermissions(String objectId) throws Exception { + return getEffectivePermissionManager().getObjectPermissions(objectId); + } + + @Override + public List getSubjectPermissions(String subjectId) throws Exception { + return getEffectivePermissionManager().getSubjectPermissions(subjectId); + } + + @Override + public void createPermission(String objectId, String subjectId) throws Exception { + getEffectivePermissionManager().createPermission(objectId, subjectId); + } +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ProfileHelper.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ProfileHelper.java new file mode 100644 index 00000000..9cebf6c0 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ProfileHelper.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import ru.entaxy.platform.core.management.profile.support.legacy.ProfileManager; + +public interface ProfileHelper extends ProfileManager { + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ProfileHelperImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ProfileHelperImpl.java new file mode 100644 index 00000000..c532552a --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/ProfileHelperImpl.java @@ -0,0 +1,133 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.profile.NotBackwardCompatibleException; +import ru.entaxy.platform.core.management.profile.support.legacy.ProfileManager; + +@Component(service = {ProfileHelper.class}, + immediate = true) +public class ProfileHelperImpl implements ProfileHelper { + + private static final Logger log = LoggerFactory.getLogger(ProfileHelperImpl.class); + + protected static final String EXPLANATION = Helpers.BACKWARD_COMPATIBILITY_DISABLED; + + protected ProfileManager profileManager = null; + + protected ProfileManager nullProfileManager = null; + + @Activate + public void activate(ComponentContext componentContext) { + + this.nullProfileManager = new ProfileManager() { + + @Override + public void uninstallProfile(String idOrName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void stopProfile(String idOrName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void startProfile(String idOrName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public void createProfile(String id, String name, String description) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + + @Override + public String getProfileConfig(String idOrName) throws Exception { + throw new NotBackwardCompatibleException(EXPLANATION); + } + }; + + } + + + + public ProfileManager getEffectiveProfileManager() { + return profileManager != null ? profileManager : nullProfileManager; + } + + @Reference(collectionType = CollectionType.SERVICE, cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, + service = ProfileManager.class, unbind = "unsetProfileManager") + public void setProfileManager(ProfileManager profileManager) { + this.profileManager = profileManager; + log.debug(">> ProfileManager is bound"); + } + + public void unsetProfileManager(ProfileManager profileManager) { + this.profileManager = null; + log.debug(">> ProfileManager is unbound"); + } + + + + @Override + public void createProfile(String id, String name, String description) throws Exception { + getEffectiveProfileManager().createProfile(id, name, description); + } + + @Override + public String getProfileConfig(String idOrName) throws Exception { + return getEffectiveProfileManager().getProfileConfig(idOrName); + } + + @Override + public void startProfile(String idOrName) throws Exception { + getEffectiveProfileManager().startProfile(idOrName); + } + + @Override + public void stopProfile(String idOrName) throws Exception { + getEffectiveProfileManager().stopProfile(idOrName); + } + + @Override + public void uninstallProfile(String idOrName) throws Exception { + getEffectiveProfileManager().uninstallProfile(idOrName); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/SystemHelper.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/SystemHelper.java new file mode 100644 index 00000000..2010b7e6 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/SystemHelper.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import ru.entaxy.platform.core.management.profile.support.legacy.SystemManager; + +public interface SystemHelper extends SystemManager { + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/SystemHelperImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/SystemHelperImpl.java new file mode 100644 index 00000000..4416f6b5 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/esb/platform/core/management/profile/helper/SystemHelperImpl.java @@ -0,0 +1,81 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.platform.core.management.profile.helper; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.profile.NotBackwardCompatibleException; +import ru.entaxy.platform.core.management.profile.support.legacy.SystemManager; + +@Component(service = SystemHelper.class, immediate = true) +public class SystemHelperImpl implements SystemHelper { + + private static final Logger LOG = LoggerFactory.getLogger(SystemHelperImpl.class); + + protected SystemManager systemManager = null; + + protected SystemManager nullSystemManager = null; + + @Activate + public void activate() { + this.nullSystemManager = new SystemManager() { + + @Override + public String getUUIDbyName(String name) throws Exception { + throw new NotBackwardCompatibleException(Helpers.BACKWARD_COMPATIBILITY_DISABLED); + } + }; + } + + @Reference(collectionType = CollectionType.SERVICE, cardinality = ReferenceCardinality.OPTIONAL, + policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, + service = SystemManager.class, unbind = "unsetSystemManager") + public void setSystemManager(SystemManager systemManager) { + this.systemManager = systemManager; + } + + public void unsetSystemManager(SystemManager systemManager) { + this.systemManager = null; + } + + protected SystemManager getEffectiveSystemManager() { + return systemManager != null ? systemManager : nullSystemManager; + } + + @Override + public String getUUIDbyName(String name) throws Exception { + return getEffectiveSystemManager().getUUIDbyName(name); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ConnectorMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ConnectorMBean.java new file mode 100644 index 00000000..686b00a8 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ConnectorMBean.java @@ -0,0 +1,75 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ConnectorMBean extends EntaxyRuntimeObjectMBean { + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.connector"; + + public static final String CONNECTOR_KEY = "connector"; + + public static final String CONNECTOR_KEY_VALUE_DEFAULT = "default"; + + // TODO implement if needed + // public boolean isDefault(); + + @Attribute(desc = "Connector name") + default String getName() { + return getObjectId(); + }; + + @Attribute(desc = "Connector registered name used in registry") + public String getRegisteredName(); + + @Attribute(desc = "Connector system") + public String getSystem(); + + @Attribute(desc = "Connector classifier") + public String getClassifier(); + + @Attribute(desc = "Connector display name") + public String getDisplayName(); + + @Attribute(desc = "Connector direction") + public String getDirection(); + + @Attribute(desc = "Connector protocol") + public String getProtocol(); + + @Operation(desc = "Starts the connector") + public void start() throws Exception; + + @Operation(desc = "Stops the connector") + public void stop() throws Exception; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/DefaultRouteMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/DefaultRouteMBean.java new file mode 100644 index 00000000..c87a8f7a --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/DefaultRouteMBean.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface DefaultRouteMBean extends EntaxyRuntimeObjectMBean { + + public static interface Helper { + + public static Qualifier getQualifier(String profileName) { + return RoutesMBean.Helper.getQualifier(profileName).qualifier(ROUTE_KEY, ROUTE_KEY_VALUE_DEFAULT); + } + + } + + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.default-route"; + + public static final String ROUTE_KEY = "route"; + + public static final String ROUTE_KEY_VALUE_DEFAULT = "default"; + + default boolean isDefault() { + return true; + }; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Gets route's configuration") + default public String doGetRouteConfig() throws Exception { + return readConfiguration(); + }; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/NotBackwardCompatibleException.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/NotBackwardCompatibleException.java new file mode 100644 index 00000000..2d25e928 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/NotBackwardCompatibleException.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile; + +import javax.naming.OperationNotSupportedException; + +public class NotBackwardCompatibleException extends OperationNotSupportedException { + + private static final long serialVersionUID = 1L; + + public NotBackwardCompatibleException() { + super(); + } + + public NotBackwardCompatibleException(String message) { + super(message); + } +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ProfileMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ProfileMBean.java new file mode 100644 index 00000000..c55d3744 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ProfileMBean.java @@ -0,0 +1,135 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import javax.management.MBeanOperationInfo; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ProfileMBean extends EntaxyRuntimeObjectMBean { + + public static interface Helper { + + public static Qualifier getQualifier(String name) { + return ProfilesMBean.Q_PROFILES.qualifier(PROFILE_KEY, name); + } + + } + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.profile"; + + public static final String PROFILE_KEY = "profile"; + + @Attribute + default public String getName() { + return getObjectId(); + }; + + @Attribute + public String getDescription(); + + @Deprecated(since = "1.10", forRemoval = true) + @Attribute + default public String getBasicAuthAccount() { + return ""; + }; + + @Deprecated(since = "1.10", forRemoval = true) + @Attribute + default public String getUuid() { + return getObjectId(); + }; + + @Deprecated(since = "1.10", forRemoval = true) + @Attribute(desc = "Systems the current can send messages to") + default public List getAllowedTargets() { + return Collections.emptyList(); + }; + + @Deprecated(since = "1.10", forRemoval = true) + @Attribute(desc = "Systems the current can receive messages from") + default public List getAllowedSources() { + return Collections.emptyList(); + }; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Adds connector to profile") + public void addConnector( + @Parameter(name = "factoryId", desc = "Connector factory ID") String connectorFactoryId, + @Parameter(name = "parameters", desc = "Connector parameters") Map parameters) + throws Exception; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Removes connector from profile") + public void removeConnector( + @Parameter(name = "connectorName", desc = "Connector name") String connectorName) throws Exception; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Starts connector in profile") + public void startConnector( + @Parameter(name = "connectorName", desc = "Connector name") String connectorName) throws Exception; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Stops connector in profile") + public void stopConnector( + @Parameter(name = "connectorName", desc = "Connector name") String connectorName) throws Exception; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Gets connector's configuration") + public String getConnectorConfig( + @Parameter(name = "connectorName", desc = "Connector name") String connectorName) throws Exception; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Creates account for this system", impact = MBeanOperationInfo.ACTION) + default public void createAccount( + @Parameter(name = "login", desc = "Login") String login, + @Parameter(name = "password", desc = "Password") String password) throws Exception {}; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Allow this system to send messages to other system") + default public void allowTarget( + @Parameter(name = "targetIdOrName", desc = "Target system Id or Name") String idOrName) throws Exception { + + }; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Allow this system to receive messages from other system") + default public void allowSource( + @Parameter(name = "sourceIdOrName", desc = "Source system Id or Name") String idOrName) throws Exception { + + }; +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ProfilesMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ProfilesMBean.java new file mode 100644 index 00000000..16895117 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/ProfilesMBean.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; +import ru.entaxy.platform.core.management.profile.support.legacy.ProfileManager; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ProfilesMBean extends EntaxyRuntimeObjectContainerMBean, ProfileManager { + + public static final String CAPABILITY_NAMESPACE_DEFAULT_ROUTE = "entaxy.runtime.default-route"; + + public static final String PROFILES_KEY = "category"; + + public static final String PROFILES_KEY_VALUE = "profiles"; + + public static final Qualifier Q_PROFILES = ManagementCore.Q_RUNTIME + .qualifier(ProfilesMBean.PROFILES_KEY, ProfilesMBean.PROFILES_KEY_VALUE); + + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/RoutesMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/RoutesMBean.java new file mode 100644 index 00000000..97888c3f --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/RoutesMBean.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; + +public interface RoutesMBean { + + public static interface Helper { + public static Qualifier getQualifier(String profileName) { + return ProfileMBean.Helper + .getQualifier(profileName) + .qualifier(ROUTES_KEY, ROUTES_KEY_VALUE); + } + + } + + public static final String ROUTES_KEY = "section"; + public static final String ROUTES_KEY_VALUE = "routes"; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ConnectorMBeanFactory.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ConnectorMBeanFactory.java new file mode 100644 index 00000000..4dc797d0 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ConnectorMBeanFactory.java @@ -0,0 +1,79 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + + +@MBeanFactory(id = "connector-factory", supportedTypes = {"entaxy.runtime.connector"}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class ConnectorMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(ConnectorMBeanFactory.class); + +// @Reference(cardinality = ReferenceCardinality.MANDATORY, policyOption = ReferencePolicyOption.GREEDY) +// ProfilesMBean profilesMBean; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policyOption = ReferencePolicyOption.GREEDY) + Helpers helpers; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + ConnectorMBeanImpl beanImpl; + try { + beanImpl = new ConnectorMBeanImpl(entaxyRuntimeObject, helpers); + // beanImpl.setParentMBean(profilesMBean); + } catch (NotCompliantMBeanException e) { + log.error("Error creating ProfileMBeanImpl for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + return (T) beanImpl; + } + + @Override + public List createMBeans() { + return Collections.emptyList(); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ConnectorMBeanImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ConnectorMBeanImpl.java new file mode 100644 index 00000000..7d46960e --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ConnectorMBeanImpl.java @@ -0,0 +1,99 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.profile.ConnectorMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +// @TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.connector") +@ObjectMBean(subQualifierName = "connector") +public class ConnectorMBeanImpl extends AbstractObjectMBean implements ConnectorMBean { + + protected Helpers helpers; + + public ConnectorMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject, Helpers helpers) + throws NotCompliantMBeanException { + super(ConnectorMBean.class, entaxyRuntimeObject); + this.helpers = helpers; + } + + @Override + public String getJMXSubQualifierValue() { + return getObjectId(); + } + + @Override + public String getFactoryId() { + return this.entaxyRuntimeObject.getAttributeOrDefault("templateId", super.getFactoryId()).toString(); + } + + @Override + public String getRegisteredName() { + return this.entaxyRuntimeObject.getAttributeOrDefault("bundleName", "").toString(); + } + + @Override + public String getSystem() { + return this.entaxyRuntimeObject.getAttributeOrDefault("system", "").toString(); + } + + @Override + public String getClassifier() { + return this.entaxyRuntimeObject.getAttributeOrDefault("classifier", "").toString(); + } + + @Override + public String getDisplayName() { + return this.entaxyRuntimeObject.getAttributeOrDefault("displayName", getObjectId()).toString(); + } + + @Override + public String getDirection() { + return this.entaxyRuntimeObject.getAttributeOrDefault("direction", getObjectId()).toString(); + } + + @Override + public String getProtocol() { + return this.entaxyRuntimeObject.getAttributeOrDefault("protocol", getObjectId()).toString(); + } + + @Override + public void start() throws Exception { + this.helpers.connectorHelper.startConnector(getSystem(), this.getRegisteredName()); + } + + @Override + public void stop() throws Exception { + this.helpers.connectorHelper.stopConnector(getSystem(), this.getRegisteredName()); + } +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/DefaultRouteMBeanFactory.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/DefaultRouteMBeanFactory.java new file mode 100644 index 00000000..98e621fb --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/DefaultRouteMBeanFactory.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + + +@MBeanFactory(id = "default-route-factory", supportedTypes = {"entaxy.runtime.default-route"}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class DefaultRouteMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(DefaultRouteMBeanFactory.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policyOption = ReferencePolicyOption.GREEDY) + Helpers helpers; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + DefaultRouteMBeanImpl beanImpl; + try { + beanImpl = new DefaultRouteMBeanImpl(entaxyRuntimeObject, helpers); + // beanImpl.setParentMBean(profilesMBean); + } catch (NotCompliantMBeanException e) { + log.error("Error creating ProfileMBeanImpl for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + return (T) beanImpl; + } + + @Override + public List createMBeans() { + return Collections.emptyList(); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/DefaultRouteMBeanImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/DefaultRouteMBeanImpl.java new file mode 100644 index 00000000..e0548071 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/DefaultRouteMBeanImpl.java @@ -0,0 +1,95 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.profile.DefaultRouteMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +// @TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.default-route") +@ObjectMBean(subQualifierName = "route") +public class DefaultRouteMBeanImpl extends AbstractObjectMBean implements DefaultRouteMBean { + + Helpers helpers; + + public DefaultRouteMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject, Helpers helpers) + throws NotCompliantMBeanException { + super(DefaultRouteMBean.class, entaxyRuntimeObject); + this.helpers = helpers; + } + + /** + * methood is overridden for compatibility with current UI + * + * TODO: remove after the above is not actual + */ + @Override + public String getJMXSubQualifierName() { + return "route"; + } + + /** + * methood is overridden for compatibility with current UI + * + * TODO: remove after the above is not actual + */ + @Override + public String getJMXSubQualifierValue() { + return "default"; + } + + /** + * methood is overridden for compatibility with current UI + * + * TODO: remove after the above is not actual + */ + /* + @Override + public String getParentSubPath() { + // TODO remove after the above is not actual + return ""; + } + */ + + /** + * methood is overridden for compatibility with current UI + * + * TODO: remove after the above is not actual + */ + /* + @Override + public String getJMXSubQualifier() { + return "section=routes," + super.getJMXSubQualifier(); + } + */ + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfileMBeanFactory.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfileMBeanFactory.java new file mode 100644 index 00000000..4b26ca9a --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfileMBeanFactory.java @@ -0,0 +1,81 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + + +@MBeanFactory(id = "profile-factory", supportedTypes = {"entaxy.runtime.profile"}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class ProfileMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(ProfileMBeanFactory.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ProfilesMBeanImpl profilesMBean; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile Helpers helpers; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + ProfileMBeanImpl beanImpl; + try { + beanImpl = new ProfileMBeanImpl(entaxyRuntimeObject, helpers); + beanImpl.setParentMBean(profilesMBean); + } catch (NotCompliantMBeanException e) { + log.error("Error creating ProfileMBeanImpl for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + return (T) beanImpl; + } + + @Override + public List createMBeans() { + return Collections.singletonList(profilesMBean); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfileMBeanImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfileMBeanImpl.java new file mode 100644 index 00000000..31b0710a --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfileMBeanImpl.java @@ -0,0 +1,188 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.management.NotCompliantMBeanException; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.profile.NotBackwardCompatibleException; +import ru.entaxy.platform.core.management.profile.ProfileMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +// @TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.profile") +@ObjectMBean(subQualifierName = "profile") +public class ProfileMBeanImpl extends AbstractObjectMBean implements ProfileMBean { + + private static final Logger log = LoggerFactory.getLogger(ProfileMBeanImpl.class); + + Helpers helpers; + + // BundleContext bundleContext; + + public ProfileMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject, /* + * BundleContext bundleContext, + */ + Helpers helpers) + throws NotCompliantMBeanException { + super(ProfileMBean.class, entaxyRuntimeObject); + // this.bundleContext = bundleContext; + this.helpers = helpers; + setJMXSubQualifierValue(entaxyRuntimeObject.getId()); + } + + @Override + public String getJMXSubQualifierName() { + // TODO Auto-generated method stub + return super.getJMXSubQualifierName(); + } + + @Override + public String getJMXSubQualifierValue() { + return getObjectId(); + } + + @Override + public String getName() { + return entaxyRuntimeObject.getAttributeOrDefault("name", "").toString(); + } + + @Override + public String getDescription() { + return entaxyRuntimeObject.getAttributeOrDefault("name", "").toString(); + } + + @Override + @Deprecated + public String getUuid() { + try { + return internalGetUuid(); + } catch (Exception ignore) { + } ; + return getObjectId(); + } + + @Deprecated + protected String internalGetUuid() throws Exception { + return helpers.systemHelper.getUUIDbyName(getName()); + } + + @Override + public String getBasicAuthAccount() { + try { + return internalGetBasicAuthAccount(); + } catch (Exception ignore) { + + } + return ""; + } + + protected String internalGetBasicAuthAccount() throws Exception { + return helpers.accountHelper.getAccountForSystem(internalGetUuid()); + } + + @Override + public void createAccount(String login, String password) throws Exception { + if (CommonUtils.isValid(getBasicAuthAccount())) + throw new IllegalArgumentException("Account already exists"); + + // FIXME remove hardcoded + this.helpers.accountHelper.createAccountForSystem(login, password, getUuid(), "admin", "admin"); + + } + + @Override + public void addConnector(String connectorFactoryId, Map parameters) throws Exception { + this.helpers.connectorHelper.addConnector(getName(), connectorFactoryId, parameters); + } + + @Override + public void removeConnector(String connectorName) throws Exception { + this.helpers.connectorHelper.removeConnector(getName(), connectorName); + } + + @Override + public void startConnector(String connectorName) throws Exception { + this.helpers.connectorHelper.startConnector(getName(), connectorName); + } + + @Override + public void stopConnector(String connectorName) throws Exception { + this.helpers.connectorHelper.stopConnector(getName(), connectorName); + } + + @Override + public String getConnectorConfig(String connectorName) throws Exception { + return helpers.entaxyObjectService.findObject(connectorName, "entaxy.runtime.connector").getConfiguration(); + } + + @Override + public List getAllowedTargets() { + try { + return helpers.permissionHelper.getObjectPermissions(internalGetUuid()); + } catch (NotBackwardCompatibleException ignore) { + // + } catch (Exception e) { + log.warn("getAllowedTargets not succeded", e); + } + return new ArrayList<>(); + } + + @Override + public List getAllowedSources() { + try { + return helpers.permissionHelper.getSubjectPermissions(internalGetUuid()); + } catch (NotBackwardCompatibleException ignore) { + // + } catch (Exception e) { + log.warn("getAllowedSources not succeded", e); + } + return new ArrayList<>(); + } + + @Override + public void allowSource(String idOrName) throws Exception { + helpers.permissionHelper.createPermission(idOrName, internalGetUuid()); + } + + @Override + public void allowTarget(String idOrName) throws Exception { + helpers.permissionHelper.createPermission(internalGetUuid(), idOrName); + + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfilesMBeanImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfilesMBeanImpl.java new file mode 100644 index 00000000..ba53a0b1 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/impl/ProfilesMBeanImpl.java @@ -0,0 +1,106 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.impl; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.osgi.service.component.annotations.ServiceScope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; +import ru.entaxy.platform.core.management.profile.ProfilesMBean; + +@Component(service = {ProfilesMBeanImpl.class}, scope = ServiceScope.SINGLETON, + immediate = true) +@ContainerMBean(id = "profiles", subQualifierValue = "profiles") +public class ProfilesMBeanImpl extends AbstractObjectContainerMBean + implements ProfilesMBean { + + private static final Logger log = LoggerFactory.getLogger(ProfilesMBeanImpl.class); + + protected BundleContext bundleContext; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, service = Helpers.class, + collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile Helpers helpers; + + public ProfilesMBeanImpl() throws NotCompliantMBeanException { + super(ProfilesMBean.class); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + + } + + @Deactivate + public void deactivate() {} + + /* + * ProfileManager implementation + */ + + @Override + public void createProfile(String id, String name, String description) throws Exception { + this.helpers.profileHelper.createProfile(id, name, description); + } + + @Override + public String getProfileConfig(String idOrName) throws Exception { + return this.helpers.entaxyObjectService.findObject(idOrName, "entaxy.runtime.profile").getConfiguration(); + } + + @Override + public void startProfile(String idOrName) throws Exception { + this.helpers.profileHelper.startProfile(idOrName); + } + + @Override + public void stopProfile(String idOrName) throws Exception { + this.helpers.profileHelper.stopProfile(idOrName); + } + + @Override + public void uninstallProfile(String idOrName) throws Exception { + this.helpers.profileHelper.uninstallProfile(idOrName); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/AccountManager.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/AccountManager.java new file mode 100644 index 00000000..67e4ce0b --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/AccountManager.java @@ -0,0 +1,35 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +public interface AccountManager { + + public String getAccountForSystem(String systemUuid) throws Exception; + + public void createAccountForSystem(String login, String password, String systemUUID, String createdBy, + String editedBy) throws Exception; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorMBean.java new file mode 100644 index 00000000..92166180 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorMBean.java @@ -0,0 +1,83 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.RuntimeTypedMBean; +import ru.entaxy.esb.platform.base.management.core.utils.BundleAwareMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATION_ENRICH) +public interface ConnectorMBean extends BundleAwareMBean, RuntimeTypedMBean { + + public static interface Helper { + + public static Qualifier getQualifier(String profileName, String connectorName) { + return ConnectorsMBean.Helper.getQualifier(profileName).qualifier(CONNECTOR_KEY, connectorName); + } + + } + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.connector"; + + public static final String CONNECTOR_KEY = "connector"; + + public static final String CONNECTOR_KEY_VALUE_DEFAULT = "default"; + + // TODO implement if needed + // public boolean isDefault(); + + @Attribute(desc = "Factory ID used to create the connector") + public String getFactoryId(); + + @Attribute(desc = "Connector name") + public String getName(); + + @Attribute(desc = "Connector registered name used in registry") + public String getRegisteredName(); + + @Attribute(desc = "Connector system") + public String getSystem(); + + @Attribute(desc = "Connector classifier") + public String getClassifier(); + + @Attribute(desc = "Connector display name") + public String getDisplayName(); + + @Attribute(desc = "Connector direction") + public String getDirection(); + + @Operation(desc = "Starts the connector") + public void start() throws Exception; + + @Operation(desc = "Stops the connector") + public void stop() throws Exception; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorManager.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorManager.java new file mode 100644 index 00000000..5b38c3f5 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorManager.java @@ -0,0 +1,40 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import java.util.Map; + +public interface ConnectorManager { + + public void addConnector(String idOrName, String connectorFactoryId, Map parameters) throws Exception; + + public void removeConnector(String idOrName, String connectorName) throws Exception; + + public void startConnector(String idOrName, String connectorName) throws Exception; + + public void stopConnector(String idOrName, String connectorName) throws Exception; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorsMBean.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorsMBean.java new file mode 100644 index 00000000..a1cd5eb5 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ConnectorsMBean.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.platform.core.management.profile.ProfileMBean; + +public interface ConnectorsMBean { + public static interface Helper { + public static Qualifier getQualifier(String profileName) { + return ProfileMBean.Helper + .getQualifier(profileName) + .qualifier(CONNECTORS_KEY, CONNECTORS_KEY_VALUE); + } + + } + + public static final String CONNECTORS_KEY = "section"; + public static final String CONNECTORS_KEY_VALUE = "connectors"; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/DeployedLegacyConnectorCustomizer.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/DeployedLegacyConnectorCustomizer.java new file mode 100644 index 00000000..a540c78b --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/DeployedLegacyConnectorCustomizer.java @@ -0,0 +1,113 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleEvent; +import org.osgi.framework.wiring.BundleCapability; + +import ru.entaxy.esb.platform.base.management.core.utils.ExtendedBundleTrackerCustomizer; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleCapabilityFilter; + +public class DeployedLegacyConnectorCustomizer extends ExtendedBundleTrackerCustomizer> { + + @Override + protected List createManagedObject(Bundle bundle, BundleEvent event, + Map> filterResults) { + @SuppressWarnings("unchecked") + List capabilities = + (List) filterResults.get(BundleCapabilityFilter.DEFAULT_FILTER_ID); + if (capabilities == null) + capabilities = new ArrayList<>(); + List result = new ArrayList<>(); + + + for (BundleCapability capability : capabilities) { + + // process only legacy connectors + if (capability.getAttributes().containsKey("objectId") + && capability.getAttributes().containsKey("factory")) { + // it's factory-based connector + continue; + } + + + Object val = capability.getAttributes().get("name"); + String name = val == null ? "" : val.toString(); + if (!CommonUtils.isValid(name)) + continue; + val = capability.getAttributes().get("system"); + String system = val == null ? "" : val.toString(); + if (!CommonUtils.isValid(system)) + continue; + + val = capability.getAttributes().get("templateId"); + String factoryId = val == null ? "" : val.toString(); + + val = capability.getAttributes().get("factory"); + factoryId = val == null ? factoryId : val.toString(); + + val = capability.getAttributes().get("bundleName"); + String registeredName = val == null ? "" : val.toString(); + + val = capability.getAttributes().get("classifier"); + String classifier = val == null ? "" : val.toString(); + + val = capability.getAttributes().get("displayName"); + String displayName; + try { + displayName = + val == null ? "" : new String(val.toString().getBytes(StandardCharsets.ISO_8859_1), "UTF-8"); + } catch (UnsupportedEncodingException e) { + displayName = val == null ? "" : val.toString(); + } + + val = capability.getAttributes().get("direction"); + String direction = val == null ? "" : val.toString(); + + + ManagedLegacyConnector mc = (new ManagedLegacyConnector()) + .name(name) + .system(system) + .factoryId(factoryId) + .registeredName(registeredName) + .classifier(classifier) + .displayName(displayName) + .direction(direction); + enrich(bundle, event, filterResults, mc); + result.add(mc); + } + return result; + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/LegacyConnectorMBeanImpl.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/LegacyConnectorMBeanImpl.java new file mode 100644 index 00000000..0e4e050c --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/LegacyConnectorMBeanImpl.java @@ -0,0 +1,94 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.framework.BundleContext; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.esb.platform.base.management.core.utils.BundleAwareMBeanImpl; +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; + +// @TODO move string to constant +@EntaxyRuntimeTyped(name = "entaxy.runtime.connector") +public class LegacyConnectorMBeanImpl extends BundleAwareMBeanImpl + implements ConnectorMBean { + + protected Helpers helpers; + + public LegacyConnectorMBeanImpl(BundleContext bundleContext, ManagedLegacyConnector managedObject, Helpers helpers) + throws NotCompliantMBeanException { + super(ConnectorMBean.class, managedObject); + this.bundleContext = bundleContext; + this.helpers = helpers; + } + + @Override + public String getFactoryId() { + return this.managedObject.getFactoryId(); + } + + @Override + public String getName() { + return this.managedObject.getName(); + } + + @Override + public String getRegisteredName() { + return this.managedObject.getRegisteredName(); + } + + @Override + public String getSystem() { + return this.managedObject.getSystem(); + } + + @Override + public String getClassifier() { + return this.managedObject.getClassifier(); + } + + @Override + public String getDisplayName() { + return this.managedObject.getDisplayName(); + } + + @Override + public String getDirection() { + return this.managedObject.getDirection(); + } + + @Override + public void start() throws Exception { + this.helpers.connectorHelper.startConnector(this.managedObject.getSystem(), this.getRegisteredName()); + } + + @Override + public void stop() throws Exception { + this.helpers.connectorHelper.stopConnector(this.managedObject.getSystem(), this.getRegisteredName()); + } +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/LegacyConnectorManager.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/LegacyConnectorManager.java new file mode 100644 index 00000000..55d4d446 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/LegacyConnectorManager.java @@ -0,0 +1,72 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import java.util.List; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.util.tracker.BundleTracker; + +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; +import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerUtils; +import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleCapabilityFilter; + +@Component(service = LegacyConnectorManager.class, immediate = true) +public class LegacyConnectorManager { + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.connector"; + + protected BundleTracker> connectorTracker; + + protected BundleContext bundleContext; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, service = Helpers.class, + collectionType = CollectionType.SERVICE) + Helpers helpers; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + connectorTracker = BundleTrackerUtils.>createBuilder() + .customizer( + (new DeployedLegacyConnectorCustomizer()) + .listener(new ManagedLegacyConnectorsListener(bundleContext, this.helpers))) + .addFilter( + (new BundleCapabilityFilter()).namespace(CAPABILITY_NAMESPACE)) + .bundleContext(bundleContext) + .bundleState(Bundle.ACTIVE | Bundle.INSTALLED | Bundle.RESOLVED | Bundle.STARTING | Bundle.STOPPING) + .get(); + connectorTracker.open(); + + } +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ManagedLegacyConnector.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ManagedLegacyConnector.java new file mode 100644 index 00000000..2119915e --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ManagedLegacyConnector.java @@ -0,0 +1,136 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import ru.entaxy.esb.platform.base.management.core.utils.BundleAwareManagedObjectImpl; + +public class ManagedLegacyConnector extends BundleAwareManagedObjectImpl { + + protected String system; + + protected String name; + + protected String registeredName; + + protected String factoryId; + + protected String classifier; + + protected String displayName; + + protected String direction; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public ManagedLegacyConnector name(String name) { + setName(name); + return this; + } + + public String getSystem() { + return system; + } + + public void setSystem(String system) { + this.system = system; + } + + public ManagedLegacyConnector system(String system) { + setSystem(system); + return this; + } + + public String getFactoryId() { + return factoryId; + } + + public void setFactoryId(String factoryId) { + this.factoryId = factoryId; + } + + public ManagedLegacyConnector factoryId(String factoryIdValue) { + this.setFactoryId(factoryIdValue); + return this; + } + + public String getRegisteredName() { + return registeredName; + } + + public void setRegisteredName(String registeredName) { + this.registeredName = registeredName; + }; + + public ManagedLegacyConnector registeredName(String registeredNameValue) { + this.setRegisteredName(registeredNameValue); + return this; + }; + + public String getClassifier() { + return classifier; + } + + public void setClassifier(String classifier) { + this.classifier = classifier; + } + + public ManagedLegacyConnector classifier(String classifierValue) { + this.setClassifier(classifierValue); + return this; + } + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + public ManagedLegacyConnector displayName(String displayNameValue) { + this.setDisplayName(displayNameValue); + return this; + } + + public String getDirection() { + return direction; + } + + public void setDirection(String direction) { + this.direction = direction; + } + + public ManagedLegacyConnector direction(String directionValue) { + this.setDirection(directionValue); + return this; + } +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ManagedLegacyConnectorsListener.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ManagedLegacyConnectorsListener.java new file mode 100644 index 00000000..bd170dc4 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ManagedLegacyConnectorsListener.java @@ -0,0 +1,77 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import java.util.Iterator; +import java.util.List; + +import org.osgi.framework.BundleContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.base.management.core.utils.ManagedObjectsListener; +import ru.entaxy.esb.platform.core.management.profile.helper.Helpers; + +public class ManagedLegacyConnectorsListener extends + ManagedObjectsListener, ManagedLegacyConnector, ConnectorMBean, LegacyConnectorMBeanImpl> { + + private static final Logger log = LoggerFactory.getLogger(ManagedLegacyConnectorsListener.class); + + protected Helpers helpers; + + public ManagedLegacyConnectorsListener(BundleContext bundleContext, Helpers helpers) { + super(bundleContext, ConnectorMBean.class); + this.helpers = helpers; + } + + @Override + protected Iterator getIterator(List managedObject) { + return managedObject.iterator(); + } + + @Override + protected String getKeyValue(ManagedLegacyConnector object) { + return object.getName(); + } + + @Override + protected LegacyConnectorMBeanImpl createService(ManagedLegacyConnector managedObject) { + try { + return new LegacyConnectorMBeanImpl(bundleContext, managedObject, helpers); + } catch (Exception e) { + log.error("Error creating service", e); + return null; + } + } + + @Override + protected String getJmxObjectName(ManagedLegacyConnector managedObject) { + return ConnectorMBean.Helper.getQualifier( + managedObject.getSystem(), + managedObject.getName()).getValue(); + } + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/PermissionManager.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/PermissionManager.java new file mode 100644 index 00000000..59236ba4 --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/PermissionManager.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import java.util.List; + +public interface PermissionManager { + + public List getObjectPermissions(String objectId) throws Exception; + + public List getSubjectPermissions(String subjectId) throws Exception; + + public void createPermission(String objectId, String subjectId) throws Exception; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ProfileManager.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ProfileManager.java new file mode 100644 index 00000000..a62bb30c --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/ProfileManager.java @@ -0,0 +1,57 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; + +@Deprecated(since = "1.10", forRemoval = true) +public interface ProfileManager { + + @Operation(desc = "Create and deploy new profile") + public void createProfile( + @Parameter(desc = "Profile ID", name = "id") String id, + @Parameter(desc = "System name", name = "name") String name, + @Parameter(desc = "Description", name = "description") String description) throws Exception; + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Get profile configuration") + public String getProfileConfig(@Parameter(desc = "Profile ID or system name", name = "idOrName") String idOrName) + throws Exception; + + @Operation(desc = "Start profile") + public void startProfile(@Parameter(desc = "Profile ID or system name", name = "idOrName") String idOrName) + throws Exception; + + @Operation(desc = "Stop profile") + public void stopProfile(@Parameter(desc = "Profile ID or system name", name = "idOrName") String idOrName) + throws Exception; + + @Operation(desc = "Uninstall profile") + public void uninstallProfile(@Parameter(desc = "Profile ID or system name", name = "idOrName") String idOrName) + throws Exception; + +} diff --git a/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/SystemManager.java b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/SystemManager.java new file mode 100644 index 00000000..06f96a1d --- /dev/null +++ b/platform/runtime/core/management/profile-management/src/main/java/ru/entaxy/platform/core/management/profile/support/legacy/SystemManager.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.profile.support.legacy; + +public interface SystemManager { + + String getUUIDbyName(String name) throws Exception; + +} diff --git a/platform/runtime/core/management/repository-management/LICENSE.txt b/platform/runtime/core/management/repository-management/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/management/repository-management/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/management/repository-management/pom.xml b/platform/runtime/core/management/repository-management/pom.xml new file mode 100644 index 00000000..4a849e11 --- /dev/null +++ b/platform/runtime/core/management/repository-management/pom.xml @@ -0,0 +1,46 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + management + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.management + repository-management + bundle + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: MANAGEMENT :: REPOSITORY MANAGEMENT + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: MANAGEMENT :: REPOSITORY MANAGEMENT + + + + ru.entaxy.esb.platform.runtime.core.management + object-management + ${project.version} + + + org.osgi + org.osgi.service.component.annotations + 1.4.0 + compile + + + org.apache.felix + org.apache.felix.scr + 2.1.20 + + + + ru.entaxy.esb.platform.runtime.base + + base-support + ${project.version} + + + ru.entaxy.esb.platform.runtime.base + management-core + ${project.version} + + + + + diff --git a/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/RepositoriesMBean.java b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/RepositoriesMBean.java new file mode 100644 index 00000000..1da6880a --- /dev/null +++ b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/RepositoriesMBean.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * repository-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.repository; + +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RepositoriesMBean extends EntaxyRuntimeObjectContainerMBean { + + @Operation(desc = "Start repository") + void startRepository( + @Parameter(name = "idOrName", desc = "Id or name of the repository") String idOrName) throws Exception; + + @Operation(desc = "Stop repository") + void stopRepository( + @Parameter(name = "idOrName", desc = "Id or name of the repository") String idOrName) throws Exception; + + @Operation(desc = "Uninstall repository") + void uninstallRepository( + @Parameter(name = "idOrName", desc = "Id or name of the repository") String idOrName) throws Exception; +} diff --git a/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/RepositoryMBean.java b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/RepositoryMBean.java new file mode 100644 index 00000000..c9ac5d7f --- /dev/null +++ b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/RepositoryMBean.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * repository-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.repository; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RepositoryMBean extends EntaxyRuntimeObjectMBean { + + @Attribute(desc = "Repository name") + default String getName() { + return getObjectId(); + } + +} diff --git a/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoriesMBeanImpl.java b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoriesMBeanImpl.java new file mode 100644 index 00000000..c1646245 --- /dev/null +++ b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoriesMBeanImpl.java @@ -0,0 +1,75 @@ +/*- + * ~~~~~~licensing~~~~~~ + * repository-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.repository.impl; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.*; + +import ru.entaxy.platform.base.objects.EntaxyObjectService; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; +import ru.entaxy.platform.core.management.repository.RepositoriesMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager; + +@Component(service = {RepositoriesMBeanImpl.class}, scope = ServiceScope.SINGLETON, + immediate = true) +@ContainerMBean(id = "repositories", subQualifierValue = "repositories") +public class RepositoriesMBeanImpl extends AbstractObjectContainerMBean + implements RepositoriesMBean { + + private String REPOSITORY_RUNTIME_TYPE = "entaxy.runtime.repository"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public EntaxyObjectService entaxyObjectService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile private EntaxyRuntimeObjectManager entaxyRuntimeObjectManager; + + public RepositoriesMBeanImpl() throws NotCompliantMBeanException { + super(RepositoriesMBean.class); + } + + @Override + public void startRepository(String idOrName) throws Exception { + entaxyRuntimeObjectManager + .start(entaxyObjectService.findObject(idOrName, REPOSITORY_RUNTIME_TYPE).getObjectFullId()); + } + + @Override + public void stopRepository(String idOrName) throws Exception { + entaxyRuntimeObjectManager + .stopForced(entaxyObjectService.findObject(idOrName, REPOSITORY_RUNTIME_TYPE).getObjectFullId()); + } + + @Override + public void uninstallRepository(String idOrName) throws Exception { + entaxyRuntimeObjectManager + .uninstallForced(entaxyObjectService.findObject(idOrName, REPOSITORY_RUNTIME_TYPE).getObjectFullId()); + } +} diff --git a/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoryMBeanFactory.java b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoryMBeanFactory.java new file mode 100644 index 00000000..954df2b6 --- /dev/null +++ b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoryMBeanFactory.java @@ -0,0 +1,73 @@ +/*- + * ~~~~~~licensing~~~~~~ + * repository-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.repository.impl; + +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@MBeanFactory(id = "repository-factory", supportedTypes = {"entaxy.runtime.repository"}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class RepositoryMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(RepositoryMBeanFactory.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + RepositoriesMBeanImpl repositoriesMBean; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + RepositoryMBeanImpl beanImpl; + try { + beanImpl = new RepositoryMBeanImpl(entaxyRuntimeObject); + beanImpl.setParentMBean(repositoriesMBean); + } catch (NotCompliantMBeanException e) { + log.error("Error creating ProfileMBeanImpl for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + return (T) beanImpl; + } + + @Override + public List createMBeans() { + return Collections.singletonList(repositoriesMBean); + } + +} diff --git a/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoryMBeanImpl.java b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoryMBeanImpl.java new file mode 100644 index 00000000..1e9a634d --- /dev/null +++ b/platform/runtime/core/management/repository-management/src/main/java/ru/entaxy/platform/core/management/repository/impl/RepositoryMBeanImpl.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * repository-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.repository.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.repository.RepositoryMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@EntaxyRuntimeTyped(name = "entaxy.runtime.repository") +@ObjectMBean(subQualifierName = "repository") +public class RepositoryMBeanImpl extends AbstractObjectMBean implements RepositoryMBean { + + public RepositoryMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(RepositoryMBean.class, entaxyRuntimeObject); + } +} diff --git a/platform/runtime/core/management/route-management/LICENSE.txt b/platform/runtime/core/management/route-management/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/management/route-management/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/management/route-management/pom.xml b/platform/runtime/core/management/route-management/pom.xml new file mode 100644 index 00000000..9d539f8b --- /dev/null +++ b/platform/runtime/core/management/route-management/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + management + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.management + route-management + bundle + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: MANAGEMENT :: ROUTE MANAGEMENT + ENTAXY :: PLATFORM :: RUNTIME :: CORE :: MANAGEMENT :: ROUTE MANAGEMENT + + + ru.entaxy.platform.core.management.route + ru.entaxy.platform.core.management.route.impl + + + + + ru.entaxy.esb.platform.runtime.core.management + object-management + ${project.version} + + + ru.entaxy.esb.platform.runtime.core.objects-implementations.route-implementation + route-producing + ${project.version} + + + + diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteComponentLibrariesMBean.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteComponentLibrariesMBean.java new file mode 100644 index 00000000..17f99ec2 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteComponentLibrariesMBean.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RouteComponentLibrariesMBean { + + String ROUTE_COMPONENT_LIBRARIES_KEY = "util"; + String ROUTE_COMPONENT_LIBRARIES_KEY_VALUE = "route-component-libraries"; + + String JMX_OBJECT_NAME = ManagementCore.Q_PLATFORM_S + "," + + RouteComponentLibrariesMBean.ROUTE_COMPONENT_LIBRARIES_KEY + "=" + + RouteComponentLibrariesMBean.ROUTE_COMPONENT_LIBRARIES_KEY_VALUE; + + @Operation(desc = "Gets all tag descriptors") + String readAllTagDescriptors() throws Exception; +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteLibrariesMBean.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteLibrariesMBean.java new file mode 100644 index 00000000..d2228337 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteLibrariesMBean.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RouteLibrariesMBean extends EntaxyRuntimeObjectContainerMBean { + + public static final String ROUTE_LIBRARIES_KEY = "category"; + + public static final String ROUTE_LIBRARIES_VALUE = "route-libraries"; + + public static final Qualifier Q_ROUTE_LIBRARIES = ManagementCore.Q_RUNTIME + .qualifier(RouteLibrariesMBean.ROUTE_LIBRARIES_KEY, RouteLibrariesMBean.ROUTE_LIBRARIES_VALUE); + + +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteLibraryMBean.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteLibraryMBean.java new file mode 100644 index 00000000..adaf49f2 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteLibraryMBean.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RouteLibraryMBean extends EntaxyRuntimeObjectMBean { + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.route-library"; + + public static final String ROUTE_LIBRARY_KEY = "route-library"; + + public static interface Helper { + + public static Qualifier getQualifier(String name) { + return RouteLibrariesMBean.Q_ROUTE_LIBRARIES.qualifier(ROUTE_LIBRARY_KEY, name); + } + + } + +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteMBean.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteMBean.java new file mode 100644 index 00000000..b043cfce --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RouteMBean.java @@ -0,0 +1,79 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RouteMBean extends EntaxyRuntimeObjectMBean { + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.route"; + + public static final String ROUTE_KEY = "route"; + + String ROUTE_ATTR_ROUTE_ID = "routeId"; + String ROUTE_ATTR_ROUTE_TYPE = "routeType"; + String ROUTE_ATTR_IS_CALLABLE = "routeIsCallable"; + String ROUTE_ATTR_GLOBAL_CALL_MODE = "routeGlobalCallMode"; + String ROUTE_ATTR_LOCAL_CALL_MODE = "routeLocalCallMode"; + + + @Override + @Attribute + default String getDisplayName() { + return CommonUtils.getValid(getRuntimeObject().getDisplayName(), getRouteId()); + } + + @Attribute + default String getRouteId() { + return getRuntimeObject().getAttributeOrDefault(ROUTE_ATTR_ROUTE_ID, getObjectId()).toString(); + }; + + @Attribute + default String getRouteType() { + return getRuntimeObject().getAttributeOrDefault(ROUTE_ATTR_ROUTE_TYPE, "UNKNOWN").toString(); + } + + @Attribute + default boolean isCallable() { + return Boolean + .parseBoolean(getRuntimeObject().getAttributeOrDefault(ROUTE_ATTR_IS_CALLABLE, "false").toString()); + }; + + @Attribute + default String getGlobalCallMode() { + return getRuntimeObject().getAttributeOrDefault(ROUTE_ATTR_GLOBAL_CALL_MODE, "NONE").toString(); + } + + @Attribute + default String getLocalCallMode() { + return getRuntimeObject().getAttributeOrDefault(ROUTE_ATTR_LOCAL_CALL_MODE, "NONE").toString(); + } +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RoutesMBean.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RoutesMBean.java new file mode 100644 index 00000000..b2c764f9 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/RoutesMBean.java @@ -0,0 +1,82 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import javax.management.MBeanOperationInfo; + +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.NotExported; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface RoutesMBean extends EntaxyRuntimeObjectMBean { + + String ATTR_ROUTE_CONTAINER_TYPE = "routeContainerType"; + + String JMX_SUBQUALIFIER_VALUE = "routes"; + + String RUNTIME_TYPE = "entaxy.runtime.route-container"; + + @Attribute + default String getRouteContainerType() { + return getRuntimeObject().getAttributeOrDefault(ATTR_ROUTE_CONTAINER_TYPE, "NONE").toString(); + } + + @Operation(desc = "List all included routes", impact = MBeanOperationInfo.INFO) + default List> listRoutes() { + return Collections.emptyList(); + }; + + @Override + default String getJMXSubQualifierValue() { + return JMX_SUBQUALIFIER_VALUE; + } + + @Override + @Attribute + default String getRuntimeType() { + return EntaxyRuntimeObjectMBean.super.getRuntimeType(); + } + + @Override + @NotExported + String readConfiguration(); + + @Override + @NotExported + Map> readExtendedData(); + + @Override + @NotExported + void refreshBundleInfo(); +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteComponentLibrariesMBeanImpl.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteComponentLibrariesMBeanImpl.java new file mode 100644 index 00000000..d5bdb32d --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteComponentLibrariesMBeanImpl.java @@ -0,0 +1,71 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route.impl; + +import org.osgi.service.component.annotations.*; +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.api.AnnotatedMBean; +import ru.entaxy.esb.resources.EntaxyResourceService; +import ru.entaxy.platform.core.management.route.RouteComponentLibrariesMBean; +import ru.entaxy.platform.routes.design.library.ComponentLibrary; +import ru.entaxy.platform.routes.design.library.ComponentLibraryManager; + +import javax.management.DynamicMBean; +import javax.management.MBeanRegistration; +import javax.management.NotCompliantMBeanException; +import java.util.List; +import java.util.stream.Collectors; + +@Component( + service = {RouteComponentLibrariesMBean.class, DynamicMBean.class, MBeanRegistration.class}, + property = {ManagementCore.JMX_OBJECTNAME + "=" + RouteComponentLibrariesMBean.JMX_OBJECT_NAME}, + scope = ServiceScope.SINGLETON, + immediate = true) +public class RouteComponentLibrariesMBeanImpl extends AnnotatedMBean + implements RouteComponentLibrariesMBean { + + @Reference + ComponentLibraryManager componentLibraryManager; + + @Reference(cardinality = ReferenceCardinality.MANDATORY + , service = EntaxyResourceService.class + , collectionType = CollectionType.SERVICE) + EntaxyResourceService entaxyResourceService; + + public RouteComponentLibrariesMBeanImpl() throws NotCompliantMBeanException { + super(RouteComponentLibrariesMBean.class); + } + + @Override + public String readAllTagDescriptors() { + List schemas = componentLibraryManager.getAllSchemasWithUiDescriptor(); + return schemas.stream().map(s -> { + return entaxyResourceService + .getResource(s.getLibrary().getUrl() + "/" + s.getUiDescriptor()) + .getAsString(); + }).collect(Collectors.toList()).toString(); + } +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteLibrariesMBeanImpl.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteLibrariesMBeanImpl.java new file mode 100644 index 00000000..e320c4c4 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteLibrariesMBeanImpl.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route.impl; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.ServiceScope; + +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; +import ru.entaxy.platform.core.management.route.RouteLibrariesMBean; + +@Component(service = {RouteLibrariesMBeanImpl.class}, scope = ServiceScope.SINGLETON, + immediate = true) +@ContainerMBean(id = "route-libraries", subQualifierValue = "route-libraries") +public class RouteLibrariesMBeanImpl extends AbstractObjectContainerMBean + implements RouteLibrariesMBean { + + public RouteLibrariesMBeanImpl() throws NotCompliantMBeanException { + super(RouteLibrariesMBean.class); + } + + +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteLibraryMBeanImpl.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteLibraryMBeanImpl.java new file mode 100644 index 00000000..ec769ee7 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteLibraryMBeanImpl.java @@ -0,0 +1,46 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.route.RouteLibraryMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@EntaxyRuntimeTyped(name = "entaxy.runtime.route-library") +@ObjectMBean(subQualifierName = "route-library") +public class RouteLibraryMBeanImpl extends AbstractObjectMBean implements RouteLibraryMBean { + + protected RouteLibraryMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(RouteLibraryMBean.class, entaxyRuntimeObject); + setJMXSubQualifierValue(entaxyRuntimeObject.getId()); + } + +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteMBeanImpl.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteMBeanImpl.java new file mode 100644 index 00000000..704feac2 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteMBeanImpl.java @@ -0,0 +1,43 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.route.RouteMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@EntaxyRuntimeTyped(name = "entaxy.runtime.route") +public class RouteMBeanImpl extends AbstractObjectMBean implements RouteMBean { + + protected RouteMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(RouteMBean.class, entaxyRuntimeObject); + } + +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteMbeanFactory.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteMbeanFactory.java new file mode 100644 index 00000000..e47eec81 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RouteMbeanFactory.java @@ -0,0 +1,142 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route.impl; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanCustomizer; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.core.management.route.RoutesMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@MBeanFactory(id = "route-factory", supportedTypes = {"entaxy.runtime.route-library", "entaxy.runtime.route"}) +@Component(service = {EntaxyRuntimeObjectMBeanFactory.class, EntaxyRuntimeObjectMBeanCustomizer.class}, + immediate = true) +public class RouteMbeanFactory extends AbstractMBeanFactory implements EntaxyRuntimeObjectMBeanCustomizer { + + private static final Logger LOG = LoggerFactory.getLogger(RouteMbeanFactory.class); + + protected static String ROUTE_TYPE = "entaxy.runtime.route"; + protected static String ROUTE_LIBRARY_TYPE = "entaxy.runtime.route-library"; + + protected static String ROUTE_CONTAINER_MARKER = "isRouteContainer"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + RouteLibrariesMBeanImpl routeLibrariesMBean; + + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + + EntaxyRuntimeObjectMBean bean = null; + + if (entaxyRuntimeObject.getType().equals(ROUTE_TYPE) + || entaxyRuntimeObject.getType().startsWith(ROUTE_TYPE + ".")) { + try { + bean = new RouteMBeanImpl(entaxyRuntimeObject); + } catch (Exception e) { + LOG.error("Error creating RouteMBeanImpl", e); + } + } else if (entaxyRuntimeObject.getType().equals(ROUTE_LIBRARY_TYPE) + || entaxyRuntimeObject.getType().startsWith(ROUTE_LIBRARY_TYPE)) { + try { + bean = new RouteLibraryMBeanImpl(entaxyRuntimeObject); + bean.setParentMBean(routeLibrariesMBean); + } catch (Exception e) { + LOG.error("Error creating RouteLibraryMBeanImpl", e); + } + } + return (T) bean; + } + + @Override + public List createMBeans() { + return Collections.singletonList(routeLibrariesMBean); + } + + /* EntaxyRuntimeObjectMBeanCustomizer */ + + @Override + public boolean isAccepted(EntaxyRuntimeObjectMBean bean) { + boolean result = false; + try { + result = Boolean.parseBoolean( + bean.getRuntimeObject().getAttributeOrDefault(ROUTE_CONTAINER_MARKER, "false").toString()); + } catch (Exception ignore) { + // NOOP + } + return result; + } + + @Override + public Customized customize(EntaxyRuntimeObjectMBean bean) { + CustomizedImpl result = new CustomizedImpl(); + result.mBean = bean; + + try { + RoutesMBeanImpl routesMBeanImpl = new RoutesMBeanImpl(bean.getRuntimeObject()); + routesMBeanImpl.setParentMBean(bean); + result.additionalMBeans.add(routesMBeanImpl); + } catch (NotCompliantMBeanException e) { + LOG.error(String.format("Error creating customized bean [%s] for [%s]", RoutesMBean.class.getName(), + bean.getRuntimeObject()), e); + } + + return result; + } + + protected static class CustomizedImpl implements Customized { + + EntaxyRuntimeObjectMBean mBean; + + List additionalMBeans = new ArrayList<>(); + + @Override + public EntaxyRuntimeObjectMBean getCustomizedMBean() { + return mBean; + } + + @Override + public List getAdditionalMBeans() { + return additionalMBeans; + } + + } + +} diff --git a/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RoutesMBeanImpl.java b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RoutesMBeanImpl.java new file mode 100644 index 00000000..c5bec8a6 --- /dev/null +++ b/platform/runtime/core/management/route-management/src/main/java/ru/entaxy/platform/core/management/route/impl/RoutesMBeanImpl.java @@ -0,0 +1,65 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.route.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.route.RoutesMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@EntaxyRuntimeTyped(name = RoutesMBean.RUNTIME_TYPE) +@ObjectMBean(subQualifierName = EntaxyRuntimeItemMBean.JMX_SUBQUALIFIER_AUTO) +public class RoutesMBeanImpl extends AbstractObjectMBean implements RoutesMBean { + + protected RoutesMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(RoutesMBean.class, entaxyRuntimeObject); + } + + @Override + public String getJMXSubQualifierValue() { + return RoutesMBean.JMX_SUBQUALIFIER_VALUE; + } + + @Override + public String getId() { + return super.getId().concat("_routes"); + } + + @Override + public String getDisplayName() { + return "routes"; + } + + @Override + public String getRuntimeType() { + return RoutesMBean.super.getRuntimeType(); + } +} diff --git a/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/ServiceMBean.java b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/ServiceMBean.java new file mode 100644 index 00000000..d6de2497 --- /dev/null +++ b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/ServiceMBean.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.service; + +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.Attribute; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ServiceMBean extends EntaxyRuntimeObjectMBean { + + public static interface Helper { + + public static Qualifier getQualifier(String name) { + return ServicesMBean.Q_SERVICES.qualifier(SERVICE_KEY, name); + } + + } + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.service"; + + public static final String SERVICE_KEY = "service"; + + @Attribute + default String getName() { + return getObjectId(); + }; +} diff --git a/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/ServicesMBean.java b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/ServicesMBean.java new file mode 100644 index 00000000..7eb2ef2c --- /dev/null +++ b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/ServicesMBean.java @@ -0,0 +1,65 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.service; + +import ru.entaxy.esb.platform.base.management.core.ManagementCore; +import ru.entaxy.esb.platform.base.management.core.Qualifier; +import ru.entaxy.esb.platform.base.management.core.api.MBeanAnnotated; +import ru.entaxy.esb.platform.base.management.core.api.MBeanExportPolicy; +import ru.entaxy.esb.platform.base.management.core.api.Operation; +import ru.entaxy.esb.platform.base.management.core.api.Parameter; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectContainerMBean; + +@MBeanAnnotated(policy = MBeanExportPolicy.ANNOTATED_ONLY) +public interface ServicesMBean extends EntaxyRuntimeObjectContainerMBean { + + public static final String CAPABILITY_NAMESPACE = "entaxy.runtime.service"; + + public static final String SERVICES_KEY = "category"; + + public static final String SERVICES_KEY_VALUE = "services"; + + public static final Qualifier Q_SERVICES = ManagementCore.Q_RUNTIME + .qualifier(ServicesMBean.SERVICES_KEY, ServicesMBean.SERVICES_KEY_VALUE); + + @Deprecated(since = "1.10", forRemoval = true) + @Operation(desc = "Gets service's configuration") + public String getServiceConfig( + @Parameter(name = "idOrName", desc = "Service id or name") String idOrName) throws Exception; + + @Operation(desc = "Start service") + public void startService( + @Parameter(name = "idOrName", desc = "Service id or name") String idOrName) throws Exception; + + @Operation(desc = "Stop service") + public void stopService( + @Parameter(name = "idOrName", desc = "Service id or name") String idOrName) throws Exception; + + @Operation(desc = "Uninstall service") + public void uninstallService( + @Parameter(name = "idOrName", desc = "Service id or name") String idOrName) throws Exception; + +} diff --git a/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServiceMBeanFactory.java b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServiceMBeanFactory.java new file mode 100644 index 00000000..7e3b729d --- /dev/null +++ b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServiceMBeanFactory.java @@ -0,0 +1,101 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.service.impl; + +import java.util.Collections; +import java.util.List; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.management.object.EntaxyRuntimeItemMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBean; +import ru.entaxy.platform.core.management.object.EntaxyRuntimeObjectMBeanFactory; +import ru.entaxy.platform.core.management.object.MBeanFactory; +import ru.entaxy.platform.core.management.object.factory.AbstractMBeanFactory; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + + +@MBeanFactory(id = "service-factory", supportedTypes = {"entaxy.runtime.service", "entaxy.runtime.service.*"}) +@Component(service = EntaxyRuntimeObjectMBeanFactory.class, immediate = true) +public class ServiceMBeanFactory extends AbstractMBeanFactory { + + private static final Logger log = LoggerFactory.getLogger(ServiceMBeanFactory.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.STATIC, + policyOption = ReferencePolicyOption.RELUCTANT) + ServicesMBeanImpl servicesMBean; + +/* +@Activate +public void activate(ComponentContext componentContext) { + log.info("Activating ServiceMBeanFactory"); +} + +@Deactivate +public void deactivate() { + log.info("DeActivating ServiceMBeanFactory"); +} + +*/ + @Override + public T createMBean(EntaxyRuntimeObject entaxyRuntimeObject) { + ServiceMBeanImpl beanImpl; + try { + beanImpl = new ServiceMBeanImpl(entaxyRuntimeObject); + beanImpl.setParentMBean(servicesMBean); + } catch (NotCompliantMBeanException e) { + log.error("Error creating ProfileMBeanImpl for [" + entaxyRuntimeObject.getObjectFullId() + "]", e); + return null; + } + return (T) beanImpl; + } + + +/* +public void setServicesMBean(ServicesMBeanImpl servicesMBean) { + log.info("setServicesMBean"); + this.servicesMBean = servicesMBean; +} + +public void unsetServicesMBean(ServicesMBeanImpl servicesMBean) { + log.info("unsetServicesMBean"); + this.servicesMBean = null; +} +*/ + @Override + public List createMBeans() { + return Collections.singletonList(servicesMBean); + } + +} diff --git a/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServiceMBeanImpl.java b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServiceMBeanImpl.java new file mode 100644 index 00000000..56a01d6b --- /dev/null +++ b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServiceMBeanImpl.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.service.impl; + +import javax.management.NotCompliantMBeanException; + +import ru.entaxy.esb.platform.base.management.core.api.EntaxyRuntimeTyped; +import ru.entaxy.platform.core.management.object.ObjectMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectMBean; +import ru.entaxy.platform.core.management.service.ServiceMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@EntaxyRuntimeTyped(name = "entaxy.runtime.service") +@ObjectMBean(subQualifierName = ServiceMBean.SERVICE_KEY) +public class ServiceMBeanImpl extends AbstractObjectMBean implements ServiceMBean { + + public ServiceMBeanImpl(EntaxyRuntimeObject entaxyRuntimeObject) + throws NotCompliantMBeanException { + super(ServiceMBean.class, entaxyRuntimeObject); + } + + + /** + * methood is overridden for compatibility with current UI + * + * TODO: remove after the above is not actual + */ + @Override + public String getJMXSubQualifierName() { + return SERVICE_KEY; + } + + @Override + public String getJMXSubQualifierValue() { + return getObjectId(); + } + +} diff --git a/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServicesMBeanImpl.java b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServicesMBeanImpl.java new file mode 100644 index 00000000..4f184e32 --- /dev/null +++ b/platform/runtime/core/management/service-management/src/main/java/ru/entaxy/platform/core/management/service/impl/ServicesMBeanImpl.java @@ -0,0 +1,141 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-management + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.management.service.impl; + +import javax.management.NotCompliantMBeanException; + +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.osgi.service.component.annotations.ServiceScope; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.objects.EntaxyObjectService; +import ru.entaxy.platform.core.management.object.ContainerMBean; +import ru.entaxy.platform.core.management.object.factory.AbstractObjectContainerMBean; +import ru.entaxy.platform.core.management.service.ServicesMBean; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectManager; + +@Component(service = {ServicesMBeanImpl.class}, scope = ServiceScope.SINGLETON, immediate = true) +@ContainerMBean(id = "services", subQualifierName = "category", subQualifierValue = "services") +public class ServicesMBeanImpl extends AbstractObjectContainerMBean implements ServicesMBean { + + private static final Logger log = LoggerFactory.getLogger(ServicesMBeanImpl.class); + + protected BundleContext bundleContext; + + private String SERVICE_RUNTIME_TYPE = "entaxy.runtime.service"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile public EntaxyObjectService entaxyObjectService; +/* +@Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, +policyOption = ReferencePolicyOption.GREEDY) +volatile private BundleManager bundleManager; +*/ + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile private EntaxyRuntimeObjectManager entaxyRuntimeObjectManager; + + public ServicesMBeanImpl() throws NotCompliantMBeanException { + super(ServicesMBean.class); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + // log.info("Activating ServicesMBeanImpl"); + } + +/* +public void setEntaxyObjectService(EntaxyObjectService entaxyObjectService) { +log.info("setEntaxyObjectService"); +this.entaxyObjectService = entaxyObjectService; +} + +public void unsetEntaxyObjectService(EntaxyObjectService entaxyObjectService) { +log.info("unsetEntaxyObjectService"); +this.entaxyObjectService = null; +} + +public void setBundleManager(BundleManager bundleManager) { +log.info("setBundleManager"); +this.bundleManager = bundleManager; +} + +public void unsetBundleManager(BundleManager bundleManager) { +log.info("unsetBundleManager"); +this.bundleManager = null; +} +*/ + @Deactivate + public void deactivate() { + log.info("Deactivating ServicesMBeanImpl"); + } + + @Override + public String getServiceConfig(String idOrName) { + return entaxyObjectService.findObject(idOrName, SERVICE_RUNTIME_TYPE).getConfiguration(); + } + + @Override + public void startService(String idOrName) throws Exception { + // long bundleId = entaxyObjectService.findObject(idOrName, + // SERVICE_RUNTIME_TYPE).getBundleInfo().getBundleId(); + // bundleManager.startBundle(bundleContext.getBundle(bundleId).getSymbolicName()); + entaxyRuntimeObjectManager + .start(entaxyObjectService.findObject(idOrName, SERVICE_RUNTIME_TYPE).getObjectFullId()); + } + + @Override + public void stopService(String idOrName) throws Exception { + // long bundleId = entaxyObjectService.findObject(idOrName, + // SERVICE_RUNTIME_TYPE).getBundleInfo().getBundleId(); + // bundleManager.stopBundle(bundleContext.getBundle(bundleId).getSymbolicName()); + entaxyRuntimeObjectManager + .stopForced(entaxyObjectService.findObject(idOrName, SERVICE_RUNTIME_TYPE).getObjectFullId()); + } + + @Override + public void uninstallService(String idOrName) throws Exception { + // long bundleId = entaxyObjectService.findObject(idOrName, + // SERVICE_RUNTIME_TYPE).getBundleInfo().getBundleId(); + // Bundle bundle = bundleContext.getBundle(bundleId); + // bundleManager.uninstallBundleByName(bundle.getSymbolicName(), "service", + // bundle.getVersion().toString()); + // todo remove all connected resources + entaxyRuntimeObjectManager + .uninstallForced(entaxyObjectService.findObject(idOrName, SERVICE_RUNTIME_TYPE).getObjectFullId()); + } +} diff --git a/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/audit/ObjectProducerEventConverter.java b/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/audit/ObjectProducerEventConverter.java new file mode 100644 index 00000000..ff9bfefc --- /dev/null +++ b/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/audit/ObjectProducerEventConverter.java @@ -0,0 +1,84 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producer-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.producer.audit; + +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.service.component.annotations.Component; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.audit.data.AuditEvent; +import ru.entaxy.audit.data.Outcome; +import ru.entaxy.audit.data.Severity; +import ru.entaxy.audit.service.EventConverter; +import ru.entaxy.audit.service.EventConverterInfo; +import ru.entaxy.audit.service.InterpretedEvent; +import ru.entaxy.audit.service.jmx.JMXInvokeEvent; + +@Component(service = EventConverter.class, immediate = true) +@EventConverterInfo(classes = {JMXInvokeEvent.class}) +public class ObjectProducerEventConverter implements EventConverter { + + private static final Logger LOG = LoggerFactory.getLogger(ObjectProducerEventConverter.class); + + @Override + public AuditEvent convert(T event) { + if (!JMXInvokeEvent.class.equals(event.getClass())) + return null; + JMXInvokeEvent invokeEvent = (JMXInvokeEvent) event; + Filter filter; + try { + filter = FrameworkUtil + .createFilter( + "(&(jmx.domain=ru.entaxy.esb)(jmx.methodName=createObjectByInstructions)(jmx.property.factoryId=*))"); + } catch (InvalidSyntaxException e) { + LOG.error("Error creating filter", e); + return null; + } + + if (!filter.matches(event.getEventEssense())) { + if (LOG.isDebugEnabled()) + LOG.debug("Event not matches: {}", event.toString()); + return null; + } + + String objectId = invokeEvent.getMethodParams()[0].toString(); + String factoryId = event.getEventEssense().getOrDefault("jmx.property.factoryId", "unknown").toString(); + + AuditEvent result = AuditEvent.AuditLoggingEventBuilder.getInstance() + .target("ENTAXY OBJECTS") + .outcome(Outcome.SUCCESS) + .message(String.format("Object %s of factory %s was changed", objectId, factoryId)) + .severity(Severity.INFO) + .category(String.format("%s:%s", objectId, factoryId)) + .build(); + + return result; + } + +} diff --git a/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/executor/generationmodel/GeneratedObjectsPublishDataStorage.java b/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/executor/generationmodel/GeneratedObjectsPublishDataStorage.java new file mode 100644 index 00000000..c10a934e --- /dev/null +++ b/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/executor/generationmodel/GeneratedObjectsPublishDataStorage.java @@ -0,0 +1,174 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producer-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.producer.executor.generationmodel; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObject; +import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectRef; + +public class GeneratedObjectsPublishDataStorage { + + Map publishData = new HashMap<>(); + + public JsonObject getPublishData(String objectUuid) { + return publishData.getOrDefault(objectUuid, new JsonObject()); + } + + public JsonObject generatePublishData(FactoredObject factoredObject, EntaxyFactory factory, String outputType) { + + JsonObject result = new JsonObject(); + JsonObject originObject = factoredObject.origin; + + result = getFilteredObject(originObject, originObject, factory, outputType); + + publishData.put(factoredObject.getUuid(), result); + + return getPublishData(factoredObject.getUuid()); + } + + protected JsonObject getFilteredObject(JsonObject originObject, JsonObject rootObject, EntaxyFactory factory, + String outputType) { + + JsonObject result = new JsonObject(); + + Map factoryFields = factory.getOutputByType(outputType).getFields().stream() + .collect(Collectors.toMap(fi -> fi.getName(), fi -> fi.getJsonOrigin())); + + for (Entry entry : originObject.entrySet()) { + String name = entry.getKey(); + + if (FactoredObject.EMBEDDED_FIELD.equals(name) || FactoredObject.IGNORE_SECTION.equals(name) + || (name.startsWith("##") && !name.startsWith("##config"))) + continue; + + boolean skip = false; + + // check @INTERNAL directive via factory data + JsonObject joField = factoryFields.getOrDefault(name, new JsonObject()); + if (joField.has(EntaxyFactory.CONFIGURATION.DIRECTIVES.INTERNAL)) { + try { + skip = joField.get(EntaxyFactory.CONFIGURATION.DIRECTIVES.INTERNAL).getAsBoolean(); + } catch (Exception ignore) { + // NOOP + } + } + if (skip) + continue; + + // check @INTERNAL directive via object data + JsonElement je = entry.getValue(); + if (je.isJsonObject()) { + JsonObject jo = je.getAsJsonObject(); + + if (jo.has(EntaxyFactory.CONFIGURATION.DIRECTIVES.INTERNAL)) { + try { + skip = jo.get(EntaxyFactory.CONFIGURATION.DIRECTIVES.INTERNAL).getAsBoolean(); + } catch (Exception e) { + // NOOP + } + if (skip) + continue; + } + } + + // check for @PUBLISH_UNRESOLVED directive + if (joField.has(GenerationModel.DIRECTIVE_PUBLISH_URESOLVED)) { + + JsonElement publishUnresolved = joField.get(GenerationModel.DIRECTIVE_PUBLISH_URESOLVED); + String publishUnresolvedValue = publishUnresolved.getAsString(); + + boolean publishRef = publishUnresolvedValue.equalsIgnoreCase(GenerationModel.PUBLISH_UNRESOLVED_REF); + boolean publishObject = + publishUnresolvedValue.equalsIgnoreCase(GenerationModel.PUBLISH_UNRESOLVED_OBJECT); + + if (publishRef || publishObject) { + + JsonObject unresolvedRef = null; + + // first we must get unresolved ref + if (je.isJsonObject()) { + if (FactoredObjectRef.isRef(je.getAsJsonObject())) { + // ref is found + unresolvedRef = je.getAsJsonObject(); + } + } + if (unresolvedRef == null) { + JsonElement unresolved = JSONUtils.findElementExt(rootObject, + String.format("%s.properties.%s", GenerationModel.UNRESOLVED_CONTAINER_NAME, name)); + if (unresolved != null && unresolved.isJsonObject()) + unresolvedRef = unresolved.getAsJsonObject(); + } + + if (unresolvedRef != null) { + if (publishRef) { + result.add(name, unresolvedRef); + continue; + } else { + + // get target object + JsonElement uuid = unresolvedRef.get(FactoredObjectRef.TARGET_UUID_FIELD); + if (uuid.isJsonPrimitive()) { + String objectUuid = uuid.getAsString(); + if (publishData.containsKey(objectUuid)) { + JsonObject toPublish = publishData.get(objectUuid); + // we nust remove 'isEmbedded' + toPublish.remove(FactoredObject.IS_EMBEDDED_FIELD); + result.add(name, toPublish); + continue; + } + } + + } + } + + } + + } + + if (je.isJsonObject()) { + JsonObject filtered = getFilteredObject(je.getAsJsonObject(), rootObject, factory, outputType); + if (filtered != null) + result.add(name, filtered); + } else { + result.add(name, je); + } + + + } + return result; + + } + +} diff --git a/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/impl/UniformExtendableProducer.java b/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/impl/UniformExtendableProducer.java new file mode 100644 index 00000000..05819e19 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producer-core/src/main/java/ru/entaxy/platform/core/producer/impl/UniformExtendableProducer.java @@ -0,0 +1,186 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producer-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.producer.impl; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtension; +import ru.entaxy.esb.platform.runtime.base.extensions.api.EntaxyExtensionsAware; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.core.producer.api.EntaxyProducer; +import ru.entaxy.platform.core.producer.wrapper.AbstractFactoryWrapper; +import ru.entaxy.platform.core.producer.wrapper.DefaultFactoryWrapper; + +@Component(service = {EntaxyProducer.class}, immediate = true, name = "UniformExtendableProducer") +public class UniformExtendableProducer extends CommonObjectProducer implements EntaxyExtensionsAware { + + private static final Logger log = LoggerFactory.getLogger(UniformExtendableProducer.class); + + public static final String PRODUCER_EXTENSION_ATTR_SUPPORTED_TYPES = "supportedTypes"; + + public static final String PRODUCER_EXTENSION_PATH = "producer"; + public static final String PRODUCER_EXTENSION_NAME = "config.json"; + + public static final String PRODUCER_EXTENSION_KEY = PRODUCER_EXTENSION_PATH + "/" + PRODUCER_EXTENSION_NAME; + + protected Map> extensionsToSupportedTypesMap = new HashMap<>(); + + protected Object extensionsLock = new Object(); + + protected ComponentContext componentContext; + + protected List availableFactories = new ArrayList<>(); + + protected Object factoriesLock = new Object(); + + @Activate + public void activate(ComponentContext componentContext) { + this.componentContext = componentContext; + } + + @Override + public void addExtension(EntaxyExtension entaxyExtension) { + if (!entaxyExtension.getResources().containsKey(PRODUCER_EXTENSION_KEY)) + return; + + synchronized (extensionsLock) { + try { + JsonObject config = + JSONUtils.getJsonRootObject(entaxyExtension.getResources().get(PRODUCER_EXTENSION_KEY)); + if (!config.has(PRODUCER_EXTENSION_ATTR_SUPPORTED_TYPES)) + return; + JsonArray ja = config.get(PRODUCER_EXTENSION_ATTR_SUPPORTED_TYPES).getAsJsonArray(); + if (ja.size() == 0) + return; + final List list = new ArrayList<>(); + for (int i = 0; i < ja.size(); i++) { + JsonElement je = ja.get(i); + if (!je.isJsonPrimitive()) + continue; + if (!je.getAsJsonPrimitive().isString()) + continue; + list.add(je.getAsJsonPrimitive().getAsString()); + } + if (!list.isEmpty()) + this.extensionsToSupportedTypesMap.put(entaxyExtension, list); + calculateSupportedTypes(); + rescanAvailables(); + } catch (IOException e) { + log.error( + "Error reading resource: [" + entaxyExtension.getResources().get(PRODUCER_EXTENSION_KEY) + "]", + e); + } + } + } + + @Override + public void removeExtension(EntaxyExtension entaxyExtension) { + if (extensionsToSupportedTypesMap.containsKey(entaxyExtension)) { + synchronized (extensionsLock) { + extensionsToSupportedTypesMap.remove(entaxyExtension); + calculateSupportedTypes(); + rescanExisting(); + } + } + + } + + protected void rescanAvailables() { + synchronized (factoriesLock) { + for (EntaxyFactory factory : availableFactories) + if (!factories.containsKey(factory)) + addFactory(factory); + } + } + + protected void rescanExisting() { + synchronized (factoriesLock) { + List existing = new ArrayList<>(factories.values()); + for (EntaxyFactory factory : existing) + if (!isTypeSupported(factory.getType())) + super.removeFactory(factory); + } + } + + protected void calculateSupportedTypes() { + final List typesList = new ArrayList<>(); + supportedTypes.clear(); + supportedTypesPatterns.clear(); + extensionsToSupportedTypesMap.values().stream() + .forEach(list -> typesList.addAll(list)); + setSupportedTypes(typesList); + } + + @Reference(bind = "addFactory", unbind = "removeFactory", cardinality = ReferenceCardinality.MULTIPLE, + collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + public void addFactory(EntaxyFactory factory) { + synchronized (factoriesLock) { + if (!availableFactories.contains(factory)) + availableFactories.add(factory); + } + doAddFactory(factory); + } + + // WE MUST DECLARE IT for @Reference annotation processor + @Override + public void removeFactory(EntaxyFactory factory) { + synchronized (factoriesLock) { + availableFactories.remove(factory); + } + super.removeFactory(factory); + + } + + @Override + protected AbstractFactoryWrapper doAddFactory(EntaxyFactory factory) { + AbstractFactoryWrapper wrapper = super.doAddFactory(factory, DefaultFactoryWrapper.class); + if (wrapper != null) + wrapper.setGenerationProcessor(this); + return wrapper; + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/AddConfigCommand2.java b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/AddConfigCommand2.java new file mode 100644 index 00000000..9f7d38b6 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/AddConfigCommand2.java @@ -0,0 +1,290 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-config-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.config; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated; +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.objects.EntaxyObject.FIELDS; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory.OutputInfo; +import ru.entaxy.platform.base.objects.factory.exceptions.FactoryNotFoundException; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.config.runtime.ObjectConfig; +import ru.entaxy.platform.config.runtime.ObjectConfigHelper; +import ru.entaxy.platform.config.runtime.ObjectConfig.FactoryOutputConfiguration; +import ru.entaxy.platform.core.producer.api.EntaxyProducerService; +import ru.entaxy.platform.core.producer.api.ExecutionPlan.ExecutionPlanUpdate; +import ru.entaxy.platform.core.producer.api.ProducerResult; +import ru.entaxy.platform.core.producer.api.ProducerResult.CommandResult; +import ru.entaxy.platform.core.producer.api.ProducingCommandExecutor; +import ru.entaxy.platform.core.producer.executor.AbstractCommandExecutor; +import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObject; +import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectProxy; +import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectRef; +import ru.entaxy.platform.core.producer.executor.objectmodel.ObjectModel; + +// @Component(service = ProducingCommandExecutor.class, immediate = true) +// @CommandExecutor(id = "add-config", predecessors = {"enrich"}, descendants = {"validate"}) +public class AddConfigCommand2 extends AbstractCommandExecutor implements ProducingCommandExecutor { + + private static final Logger log = LoggerFactory.getLogger(AddConfigCommand2.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyProducerService entaxyProducerServiceLocal; + + public AddConfigCommand2() { + super(null); + } + + protected AddConfigCommand2(EntaxyProducerService entaxyProducerService) { + super(entaxyProducerService); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.entaxyProducerService = this.entaxyProducerServiceLocal; + this.entaxyProducerService.registerCommand(this); + } + + @Override + protected boolean doExecute(ProducerResult currentResult, CommandResult commandResult, + Map instructions) throws Exception { + + printOutput("\n\n\t== ADD-CONFIG == \n\n"); + + ObjectModel objectModel = currentResult.findResultObject(ObjectModel.class); + objectModel.startTracking(); + + JsonObject incomingJson = objectModel.getJsonCurrent().deepCopy(); + + for (FactoredObject fo : objectModel.objects) { + + // skip proxies + if (fo instanceof FactoredObjectProxy) + continue; + + log.debug("OBJECT :: {}/{}", fo.getObjectId(), fo.getObjectType()); + + String factoryId = fo.factoryId; + + EntaxyFactory factory = entaxyProducerService.findFactoryById(factoryId); + if (factory == null) + throw new FactoryNotFoundException(factoryId); + + String output = fo.getOutputType(); + log.debug("OUTPUT :: {}", output); + + OutputInfo oi = CommonUtils.isValid(output) ? factory.getOutputByType(output) : factory.getDefaultOutput(); + Map config = oi.getConfig(); + if ((config == null) || (config.isEmpty())) + continue; + + String val = config.getOrDefault(ObjectConfig.CONFIGURABLE_ATTRIBUTE_NAME, "false").toString(); + Boolean configurable = Boolean.valueOf(val); + if (!configurable) + continue; + + JsonObject objectOrigin = fo.origin; + JsonObject objectProperties = objectOrigin.get(FIELDS.PROPERTIES).getAsJsonObject(); + + if (objectProperties.has(ObjectConfig.CONFIG_FIELD_NAME)) + continue; + + @SuppressWarnings("serial") + Generated g = this.entaxyProducerService.findFactoryById("common-config") + .generate("config-field", "private", new HashMap() { + { + put(FIELDS.FACTORY_ID, "common-config"); + put(ObjectConfig.TARGET_FACTORY_FIELD_NAME, fo.factoryId); + put(ObjectConfig.TARGET_TYPE_FIELD_NAME, fo.getObjectType()); + put(ObjectConfig.TARGET_ID_FIELD_NAME, fo.getObjectId()); + put(ObjectConfig.TARGET_OUTPUT_FIELD_NAME, fo.getOutputType()); + } + }); + + objectProperties.add(ObjectConfig.CONFIG_FIELD_NAME, JSONUtils.getJsonRootObject(g.getObject().toString())); + objectModel.setDirty(); + + } + + for (FactoredObjectRef ref : objectModel.refs) { + // process external refs and replace ref to object with ref to config if + // - ref is not marked 'directValueOnly' + // - the referenced object has config + // - the referenced field is configurable + + // if (!ref.isExternal()) + // continue; + + log.debug("REF :: " + ref.relativePath); + + if (ObjectConfigHelper.getInstance().isDirectValueOnly(ref)) + continue; + + String objectId = ref.getTargetId(); + String objectType = ref.getTargetType(); + + log.debug("TO :: " + objectId + ":" + objectType); + log.debug("DEFINED IN :: " + ref.definedIn.getObjectId()); + + String refField = ref.getOrDefault(FIELDS.REF_FIELD, FIELDS.OBJECT_ID).toString(); + if (FIELDS.OBJECT_ID.equals(refField)) + // objectId can't be configured + continue; + + // skip if it's already config + if (ObjectConfig.CONFIG_OBJECT_TYPE.equals(objectType)) + continue; + + String configurationPid = ObjectConfig.getConfigurationPid(objectId, objectType); + + String factoryId = null; + + JsonElement newTargetId = null; + + if (ref.isExternal()) { + + EntaxyObject theObject = ObjectConfigHelper.getInstance().findObject(objectId, objectType); + if (theObject == null) + // referenced object not found + continue; + + factoryId = theObject.getFactoryId(); + + EntaxyObject configObject = ObjectConfigHelper.getInstance() + .findObject(configurationPid, ObjectConfig.CONFIG_OBJECT_TYPE); + if (configObject == null) + // config for referenced object not found + continue; + + newTargetId = new JsonPrimitive(configurationPid); + + } else { + + log.debug("EXTERNAL :: false"); + + Optional theObjectOpt = objectModel.objects.stream() + .filter(obj -> objectId.equals(obj.getObjectId())).findFirst(); + if (!theObjectOpt.isPresent()) + continue; + + FactoredObject theObject = theObjectOpt.get(); + + log.debug("TARGET OBJECT :: found"); + + factoryId = theObject.factoryId; + + Optional configRefOpt = objectModel.refs.stream() + .filter(r -> r.definedIn.equals(theObject)) + .filter(r -> r.relativePath.endsWith(ObjectConfig.CONFIG_FIELD_NAME)) + .findFirst(); + + if (!configRefOpt.isPresent()) + continue; + + log.debug("REF TO CONFIG :: found; TARGET :: " + configRefOpt.get().getTargetId()); + + Optional configObjectOpt = objectModel.objects.stream() + .filter(obj -> obj.getObjectId().equals(configRefOpt.get().getTargetId())) + .findFirst(); + if (!configObjectOpt.isPresent()) + continue; + + log.debug("CONFIG OBJECT :: found"); + + newTargetId = new JsonPrimitive(configObjectOpt.get().getObjectId()); + } + + + EntaxyFactory entaxyFactory = entaxyProducerService.findFactoryById(factoryId); + if (entaxyFactory == null) + // factory for referenced object not found + continue; + + FactoryOutputConfiguration conf = FactoryOutputConfiguration.read(entaxyFactory, + EntaxyFactory.CONFIGURATION.OUTPUTS.OUTPUT_TYPE_INIT); + if (!conf.isConfigurable) + continue; + + + if (!ObjectConfig.isConfigurable(entaxyFactory, EntaxyFactory.CONFIGURATION.OUTPUTS.OUTPUT_TYPE_INIT, + refField, conf.defaultFieldsConfigurable, conf.configurations)) + // field is not configurable + continue; + + JSONUtils.replaceValue(ref.origin, FIELDS.OBJECT_TYPE, new JsonPrimitive(ObjectConfig.CONFIG_OBJECT_TYPE)); + JSONUtils.replaceValue(ref.origin, FactoredObjectRef.TARGET_TYPE_FIELD, + new JsonPrimitive(ObjectConfig.CONFIG_OBJECT_TYPE)); + JSONUtils.replaceValue(ref.origin, FactoredObjectRef.TARGET_ID_FIELD, newTargetId); + + // and we must generate ref to config to merge to main object + JSONUtils.replaceValue(ref.origin, FIELDS.IS_REF_BY_VALUE_ONLY, new JsonPrimitive(false)); + + objectModel.setDirty(); + + } + + if (objectModel.stopTracking()) { + + // remove ##embedded + for (FactoredObject fo : objectModel.objects) + fo.origin.remove(FactoredObject.EMBEDDED_FIELD); + + + commandResult.planUpdate = ExecutionPlanUpdate.create() + // .updateInstructions().target("enrich").value("skip", true).complete() + .reset().target("analyze").complete(); + } + + JsonObject outgoingJson = objectModel.getJsonCurrent(); + + printOutput("\n== INCOMING JSON ==\n"); + printOutput(incomingJson.toString()); + printOutput("\n== OUTGOING JSON ==\n"); + printOutput(outgoingJson.toString()); + + commandResult.resultObject(outgoingJson); + + return true; + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/ConfigProducer2.java b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/ConfigProducer2.java new file mode 100644 index 00000000..ff3cb10b --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/ConfigProducer2.java @@ -0,0 +1,194 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-config-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.config; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.stream.Collectors; + +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated; +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.objects.factory.EntaxyFactoryException; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.config.runtime.ObjectConfig; +import ru.entaxy.platform.core.producer.api.EntaxyProducer; +import ru.entaxy.platform.core.producer.api.EntaxyProducerService; +import ru.entaxy.platform.core.producer.api.EntaxyWrappedFactory; +import ru.entaxy.platform.core.producer.executor.generationmodel.GeneratedHeaders; +import ru.entaxy.platform.core.producer.impl.CommonObjectProducer; +import ru.entaxy.platform.core.producer.wrapper.AbstractFactoryWrapper; + +// @Component(service = EntaxyProducer.class, immediate = true) +// @EntaxyProducerInfo (supportedTypes = {ObjectConfig.CONFIG_OBJECT_TYPE}) +public class ConfigProducer2 extends CommonObjectProducer implements EntaxyProducer { + + private static final Logger log = LoggerFactory.getLogger(ConfigProducer2.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyProducerService entaxyProducerService; + + @Reference(bind = "addFactory", unbind = "removeFactory", cardinality = ReferenceCardinality.MULTIPLE, + collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + public void addFactory(EntaxyFactory factory) { + AbstractFactoryWrapper wrapper = super.doAddFactory(factory); + if (wrapper != null) + wrapper.setGenerationProcessor(this); + } + + // WE MUST DECLARE IT for @Reference annotation processor + @Override + public void removeFactory(EntaxyFactory factory) { + super.removeFactory(factory); + } + + @Override + public void preGenerate(EntaxyWrappedFactory wrappedFactory, String outputType, String scope, String objectType, + Map parameters) throws EntaxyFactoryException { + super.preGenerate(wrappedFactory, outputType, scope, objectType, parameters); + @SuppressWarnings("unchecked") + Map properties = (Map) parameters.get(EntaxyObject.FIELDS.PROPERTIES); + + // System.out.println("\n\n\tCONFIG PRODUCER :: preGenerate"); + // System.out.println("\t" + parameters.toString()); + + // properties can be null for 'config-field' output + if (properties != null) { + + /* System.out.println("\n\n\tGENERATE CONFIG: " + + "\noutput: " + outputType + + "\nscope: " + scope + + "\nproperties: " + properties.toString()); */ + + ObjectConfig.backupProperties(parameters, ObjectConfig.CONFIG_PROPERTIES_FIELD_NAME); + ObjectConfig.removeConfigData(parameters, ObjectConfig.CONFIG_PROPERTIES_FIELD_NAME); + + Map configurables = new HashMap<>(); + Map immutables = new HashMap<>(); + + String targetFactoryId = properties.get(ObjectConfig.CONFIG_FACTORY_FIELD_NAME).toString(); + String targetOutput = properties.get(ObjectConfig.CONFIG_OUTPUT_FIELD_NAME).toString(); + + EntaxyFactory f = entaxyProducerService.findFactoryById(targetFactoryId); + if (!CommonUtils.isValid(targetOutput)) + targetOutput = f.getDefaultOutput().getType(); + + fillConfigMaps(f, targetOutput, scope, objectType, parameters, configurables, immutables); + + parameters.put(ObjectConfig.CONFIGURABLES_FIELD_NAME, configurables); + parameters.put(ObjectConfig.IMMUTABLES_FIELD_NAME, immutables); + + String configuredId = parameters.get(ObjectConfig.CONFIG_ID_FIELD_NAME).toString(); + String configuredType = parameters.get(ObjectConfig.CONFIG_TYPE_FIELD_NAME).toString(); + + String configurationPid = ObjectConfig.getConfigurationPid(configuredId, configuredType); + String placeholderPrefix = ObjectConfig.getConfigurationPrefix(configuredId, configuredType); + + // set objectId to configurationPid + + parameters.put(EntaxyObject.FIELDS.OBJECT_ID, configurationPid); + + parameters.put(ObjectConfig.CONFIG_PID_FIELD_NAME, configurationPid); + parameters.put(ObjectConfig.CONFIG_PLACEHOLDER_PREFIX_FIELD_NAME, placeholderPrefix); + + } + } + + @Override + public void postGenerate(EntaxyWrappedFactory wrappedFactory, String outputType, String scope, String objectType, + Map parameters, Generated generated) throws EntaxyFactoryException { + super.postGenerate(wrappedFactory, outputType, scope, objectType, parameters, generated); + ObjectConfig.restoreBackupProperties(parameters, ObjectConfig.CONFIG_PROPERTIES_FIELD_NAME); + + @SuppressWarnings("unchecked") + Map properties = (Map) parameters.get(EntaxyObject.FIELDS.PROPERTIES); + + // properties can be null for 'config-field' output + if (properties != null) { + + // enrich paramaters with configured fields placeholders + String placeholderPrefix = parameters.get(ObjectConfig.CONFIG_PLACEHOLDER_PREFIX_FIELD_NAME).toString(); + + @SuppressWarnings("unchecked") + Map configuredFields = + (Map) parameters.getOrDefault(ObjectConfig.CONFIGURABLES_FIELD_NAME, + Collections.emptyMap()); + configuredFields.putAll( + (Map) parameters.getOrDefault(ObjectConfig.IMMUTABLES_FIELD_NAME, + Collections.emptyMap())); + + log.debug("CONFIGURED: \n" + configuredFields); + + Map placeholdersMap = configuredFields.entrySet().stream() + // .map(entry -> entry.setValue(placeholderPrefix + entry.getKey() + "}")) + .collect(Collectors.toMap(Map.Entry::getKey, entry -> placeholderPrefix + entry.getKey() + "}")); + + log.debug("\n\n\tPLACEHOLDERS: \n" + placeholdersMap); + + parameters.putAll(placeholdersMap); + + // add headers + String configuredId = parameters.get(ObjectConfig.CONFIG_ID_FIELD_NAME).toString(); + String configuredType = parameters.get(ObjectConfig.CONFIG_TYPE_FIELD_NAME).toString(); + + String configurationPid = ObjectConfig.getConfigurationPid(configuredId, configuredType); + + GeneratedHeaders headers = GeneratedHeaders.getHeaders(generated.getProperties()); + headers.set(ObjectConfig.HEADER_OBJECT_CONFIG_PID, + configuredId + ":" + configuredType + ":" + configurationPid); + } + } + + protected void fillConfigMaps(EntaxyFactory factory, String outputType, String scope, String objectType, + Map parameters, Map configurables, Map immutables) { + + @SuppressWarnings("unchecked") + Map properties = + (Map) parameters.get(ObjectConfig.CONFIG_PROPERTIES_FIELD_NAME); + for (Entry entry : properties.entrySet()) { + Map targetMap = + ObjectConfig.getTargetConfigMap(factory, outputType, entry.getKey(), configurables, immutables); + if (targetMap == null) { + continue; + } + targetMap.put(entry.getKey(), entry.getValue()); + + } + + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/support/ConfigObjectSupport.java b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/support/ConfigObjectSupport.java new file mode 100644 index 00000000..2a452edd --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/support/ConfigObjectSupport.java @@ -0,0 +1,114 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-config-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.config.support; + +import java.util.Map; + +import org.apache.felix.utils.properties.TypedProperties; +import org.apache.karaf.config.core.ConfigRepository; +import org.osgi.framework.ServiceReference; +import org.osgi.service.cm.ConfigurationAdmin; +import org.osgi.service.component.annotations.Component; + +import ru.entaxy.esb.platform.runtime.base.connecting.generator.Generated; +import ru.entaxy.platform.config.runtime.ObjectConfigHelper; +import ru.entaxy.platform.core.producer.executor.builder.BuiltObject; +import ru.entaxy.platform.core.producer.executor.builder.DefaultBuiltObject; +import ru.entaxy.platform.core.producer.executor.builder.ObjectBuilder; +import ru.entaxy.platform.core.producer.executor.deployer.DefaultDeployedObject; +import ru.entaxy.platform.core.producer.executor.deployer.DeployedObject; +import ru.entaxy.platform.core.producer.executor.deployer.ObjectDeployer; +import ru.entaxy.platform.core.producer.executor.installer.DefaultInstalledObject; +import ru.entaxy.platform.core.producer.executor.installer.InstalledObject; +import ru.entaxy.platform.core.producer.executor.installer.ObjectInstaller; + +@Component(service = {ObjectBuilder.class, ObjectDeployer.class, ObjectInstaller.class}) +public class ConfigObjectSupport implements ObjectBuilder, ObjectDeployer, ObjectInstaller { + + private static final String CONFIG_TYPE_PREFIX = "config:"; + + @Override + public boolean isBuildable(Generated generated) { + return generated.getType().startsWith(CONFIG_TYPE_PREFIX); + } + + @Override + public BuiltObject build(Generated generated, Map instructions) throws Exception { + return new DefaultBuiltObject(new DeployableConfig( + generated.getProperties().getOrDefault("configurationPid", + generated.getProperties().getOrDefault("objectId", "unknown")).toString(), + + generated.getObject().toString())); + } + + @Override + public boolean isDeployable(BuiltObject object) { + return object.getObject() instanceof DeployableConfig; + } + + @Override + public DeployedObject deploy(BuiltObject object, Map instructions) throws Exception { + return new DefaultDeployedObject(object.getObject()); + } + + @Override + public boolean isInstallable(DeployedObject object) { + return object.getObject() instanceof DeployableConfig; + } + + @Override + public InstalledObject install(DeployedObject object, Map instructions) throws Exception { + DeployableConfig deployableConfig = (DeployableConfig) object.getObject(); + Map map = deployableConfig.properties; + + ServiceReference ref = ObjectConfigHelper.getInstance().getReference(ConfigRepository.class); + ServiceReference ref2 = + ObjectConfigHelper.getInstance().getReference(ConfigurationAdmin.class); + if (ref != null) { + + ConfigurationAdmin configurationAdmin = ObjectConfigHelper.getInstance().getService(ref2); + + // we need this to not bind config to felix bundle + configurationAdmin.getConfiguration(deployableConfig.configurationPid, "?"); + + ConfigRepository configRepository = ObjectConfigHelper.getInstance().getService(ref); + TypedProperties typedProperties = configRepository.getConfig(deployableConfig.configurationPid); + + typedProperties.clear(); + + for (Map.Entry entry : map.entrySet()) + typedProperties.put(entry.getKey(), entry.getValue()); + + configRepository.update(deployableConfig.configurationPid, typedProperties); + + ObjectConfigHelper.getInstance().ungetService(ref); + ObjectConfigHelper.getInstance().ungetService(ref2); + } + + return new DefaultInstalledObject(map); + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/support/DeployableConfig.java b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/support/DeployableConfig.java new file mode 100644 index 00000000..0c5c1471 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/java/ru/entaxy/platform/core/producer/config/support/DeployableConfig.java @@ -0,0 +1,95 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-config-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.config.support; + +import java.util.Base64; +import java.util.HashMap; +import java.util.Map; + +import org.jline.utils.Log; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.config.runtime.ObjectConfig; +import ru.entaxy.platform.config.runtime.ObjectConfig.ConfigHint; + +public class DeployableConfig { + + private static final Logger LOG = LoggerFactory.getLogger(DeployableConfig.class); + + public String jsonData; + public Map properties; + + public String configurationPid; + + public DeployableConfig(String configurationPid, String jsonData) { + + this.configurationPid = configurationPid; + + this.jsonData = jsonData; + + Map origin = JSONUtils.element2map(JSONUtils.getJsonRootObject(jsonData)); + properties = new HashMap<>(); + if (origin == null) { + return; + } + + for (Map.Entry entry : origin.entrySet()) + if (!entry.getKey().startsWith("#")) + properties.put(entry.getKey(), entry.getValue()); + + try { + generateHint(); + } catch (Exception e) { + Log.error("Error generating condig hint", e); + } + + } + + protected void generateHint() throws Exception { + + properties.remove(ObjectConfig.CONFIG_HINT_FIELD_NAME); + + String factoryId = properties.getOrDefault(ObjectConfig.CONFIG_FACTORY_FIELD_NAME, "").toString(); + String outputType = properties.getOrDefault(ObjectConfig.CONFIG_OUTPUT_FIELD_NAME, "").toString(); + + ConfigHint configHint = new ConfigHint(); + configHint.generate(properties, factoryId, outputType); + + String jsonHint = configHint.getAsJsonString(); + if (CommonUtils.isValid(jsonHint)) { + properties.put(ObjectConfig.CONFIG_HINT_FIELD_NAME, + Base64.getEncoder().encodeToString(jsonHint.getBytes())); + + } + + + + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/extensions/objectproducer/merge/config/BlueprintMergeProcessor.json b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/extensions/objectproducer/merge/config/BlueprintMergeProcessor.json new file mode 100644 index 00000000..888c30d9 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/extensions/objectproducer/merge/config/BlueprintMergeProcessor.json @@ -0,0 +1,8 @@ +{ + "property-placeholder": { + "targetNodeName": "##root", + "position": "inside_first", + "unique": ["persistent-id"], + "conflict": "ignore" /*[ignore, replace]*/ + } +} \ No newline at end of file diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/factory/object-config.json b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/factory/object-config.json new file mode 100644 index 00000000..f7434642 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/factory/object-config.json @@ -0,0 +1,103 @@ +{ + "factory": { + "id": "object-config", + "type": "entaxy.runtime.config", + "description": "Entaxy object configuration factory", + "isAbstract": false + }, + "entaxy.runtime.config": {}, + "fields": { + "configurables": { + "type": "Map", + "group": "config", + "required": true, + "defaultValue": {} + }, + "immutables": { + "type": "Map", + "group": "config", + "required": true, + "defaultValue": {} + } + }, + "outputs": { + "init": { + "isDefault": true, + "scopes": ["private", "public"], + "fields": { + "__entaxy_configuredId": { + "type": "String", + "isHidden": true + }, + "__entaxy_configuredType": { + "type": "String", + "isHidden": true + }, + "__entaxy_configuredFactoryId": { + "type": "String", + "isHidden": true + }, + "__entaxy_configuredOutput": { + "type": "String", + "isHidden": true + } + } + }, + "config-defaults": { + "isDefault": false, + "scopes": ["private", "public"], + "fields": { + "##publish": { + "defaultValue": { + "name": { + "@CALCULATED": { + "expression": "${properties.configurationPid}", + "lazy": true + } + }, + "objectId": { + "@CALCULATED": { + "expression": "${properties.configurationPid}", + "lazy": true + } + }, + "relation": [ + { + "@CALCULATED": { + "expression": "${properties.__entaxy_configuredId}:${properties.__entaxy_configuredType}:config:-composition:config", + "lazy": false + } + } + ], + "target": { + "@CALCULATED": { + "expression": "${properties.__entaxy_configuredId}:${properties.__entaxy_configuredType}", + "lazy": false + } + } + } + } + }, + "config": { + "@PUBLISH_AS": { + "*": "configurationPid" + } + } + }, + "config-link-field": { + "isDefault": false, + "generator": "", + "config": {}, + "scopes": ["private", "public"] + }, + "config-defaults-field": { + "isDefault": false, + "generator": "", + "config": {}, + "scopes": ["private"] + }, + "ref":{ + "scopes": ["private", "public"] + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-defaults-field.ftl b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-defaults-field.ftl new file mode 100644 index 00000000..1c56f7d6 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-defaults-field.ftl @@ -0,0 +1,29 @@ +[#ftl attributes={"generated.type":"json"}] +{ + "factoryId": "object-config", + "objectId": "[=objectId]", + "scope": "private", + "outputType": "config-defaults", + "@FILL_CONFIGURABLES": "", + "properties": { + "configured": { + "@CALCULATED": { + "resultType": "String", + "expression": "${#OWNER#.objectId}", + "lazy": true + } + }, + "__entaxy_configuredId":"[=targetObjectId]", + "__entaxy_configuredType":"[=targetObjectType]", + "__entaxy_configuredFactoryId":"[=targetObjectFactoryId]", + "__entaxy_configuredOutput":"[=targetObjectOutput]", + "configurationPid": [=configurationPid], + "configuredProperties": { + "@CALCULATED": { + "resultType": "Map", + "expression": "${#OWNER#.properties}", + "lazy": true + } + } + } +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-defaults.ftl b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-defaults.ftl new file mode 100644 index 00000000..7a18f237 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-defaults.ftl @@ -0,0 +1,44 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + [#if configurables??] + [#list configurables as key, value] + + [/#list] + [/#if] + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-link-field.ftl b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-link-field.ftl new file mode 100644 index 00000000..5af27d75 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/config-link-field.ftl @@ -0,0 +1,23 @@ +[#ftl attributes={"generated.type":"json"}] +{ + "factoryId": "object-config", + "objectId": "[=objectId]", + "scope": "public", + "@FILL_CONFIGURABLES": "properties", + "properties": { + "__entaxy_configuredId":"[=targetObjectId]", + "__entaxy_configuredType":"[=targetObjectType]", + "__entaxy_configuredFactoryId":"[=targetObjectFactoryId]", + "__entaxy_configuredOutput":"[=targetObjectOutput]" + }, + "configuredProperties": { + "@CALCULATED": { + "resultType": "Map", + "expression": "${#OWNER#.properties}", + "lazy": true + } + }, + "refConfig": { + "isRefByValueOnly": true + } +} diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/init.ftl b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/init.ftl new file mode 100644 index 00000000..3c5b5f51 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/init.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"config:json"}] +[=configurables_json!] diff --git a/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/ref.ftl b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/ref.ftl new file mode 100644 index 00000000..ea9f75e9 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-config-support/src/main/resources/ru/entaxy/templates/object-config/ref.ftl @@ -0,0 +1,22 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/EntaxyResourceProducingProcessor.java b/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/EntaxyResourceProducingProcessor.java new file mode 100644 index 00000000..cac2b818 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/EntaxyResourceProducingProcessor.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-resources-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.resources; + +import java.util.Map; + +public interface EntaxyResourceProducingProcessor { + + String PROP_PROCESSOR = "processor"; + + String getName(); + Object process(Object value, Map properties) throws Exception; + +} diff --git a/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/EntaxyResourceProducingProcessorService.java b/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/EntaxyResourceProducingProcessorService.java new file mode 100644 index 00000000..fae2017a --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/EntaxyResourceProducingProcessorService.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-resources-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.resources; + +import java.util.Map; + +public interface EntaxyResourceProducingProcessorService { + + Object process(Object value, Map properties) throws Exception; + +} diff --git a/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/impl/EntaxyResourceProducingProcessorServiceImpl.java b/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/impl/EntaxyResourceProducingProcessorServiceImpl.java new file mode 100644 index 00000000..9588a052 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-resources-support/src/main/java/ru/entaxy/platform/core/producer/resources/impl/EntaxyResourceProducingProcessorServiceImpl.java @@ -0,0 +1,90 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-resources-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~~~~~~ + */ +package ru.entaxy.platform.core.producer.resources.impl; + +import java.util.HashMap; +import java.util.Map; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.CollectionType; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessor; +import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessorService; + +@Component (service = EntaxyResourceProducingProcessorService.class, immediate = true) +public class EntaxyResourceProducingProcessorServiceImpl implements EntaxyResourceProducingProcessorService { + + private static final Logger log = LoggerFactory.getLogger(EntaxyResourceProducingProcessorServiceImpl.class); + + protected static EntaxyResourceProducingProcessorService _INSTANCE; + + public static EntaxyResourceProducingProcessorService getInstance() { + return _INSTANCE; + } + + protected Map processorsMap = new HashMap<>(); + + @Activate + public void activate() { + _INSTANCE = this; + } + + @Reference (cardinality = ReferenceCardinality.MULTIPLE, collectionType = CollectionType.SERVICE, policy = ReferencePolicy.DYNAMIC + , policyOption = ReferencePolicyOption.GREEDY, unbind = "removeProcessor") + public void addProcessor(EntaxyResourceProducingProcessor processor) { + synchronized (processorsMap) { + this.processorsMap.put(processor.getName(), processor); + } + } + + public void removeProcessor(EntaxyResourceProducingProcessor processor) { + synchronized (processorsMap) { + this.processorsMap.remove(processor.getName()); + } + } + + + @Override + public Object process(Object value, Map properties) throws Exception{ + Object val = properties.get(EntaxyResourceProducingProcessor.PROP_PROCESSOR); + if (val == null) + return value; + String processorName = val.toString(); + if (!processorsMap.containsKey(processorName)) { + log.warn("Unknown processor [{}] in [{}]", processorName, properties); + return value; + } + return processorsMap.get(processorName).process(value, properties); + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-shell/src/main/java/ru/entaxy/platform/core/producer/shell/FactoryEssence.java b/platform/runtime/core/object-producing/object-producing-shell/src/main/java/ru/entaxy/platform/core/producer/shell/FactoryEssence.java new file mode 100644 index 00000000..8a4be22f --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-shell/src/main/java/ru/entaxy/platform/core/producer/shell/FactoryEssence.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.producer.shell; + +import java.util.Map; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.Option; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.core.producer.api.EntaxyProducerUtils; + +@Service +@Command(scope = EntaxyProducerServiceSupport.SCOPE, name = "factory-essence") +public class FactoryEssence extends FactoryAwareCommand { + + @Option(name = "-p", aliases = {"--prefix"}) + String prefix = ""; + + @Override + protected Object doExecute() throws Exception { + + Map essence = EntaxyProducerUtils.getFactoryEssence(entaxyFactory, prefix); + + ShellTableExt table = new ShellTableExt(); + table.column("Key"); + table.column("Value"); + + for (Map.Entry entry : essence.entrySet()) + table.addRow().addContent(entry.getKey(), entry.getValue() == null ? "" : entry.getValue().toString()); + + // print output + table.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/core/object-producing/object-producing-shell/src/main/java/ru/entaxy/platform/core/producer/shell/FindFactories.java b/platform/runtime/core/object-producing/object-producing-shell/src/main/java/ru/entaxy/platform/core/producer/shell/FindFactories.java new file mode 100644 index 00000000..e98fba01 --- /dev/null +++ b/platform/runtime/core/object-producing/object-producing-shell/src/main/java/ru/entaxy/platform/core/producer/shell/FindFactories.java @@ -0,0 +1,91 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.core.producer.shell; + +import java.util.Comparator; +import java.util.List; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; + +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; + +@Service +@Command(scope = "producer", name = "factory-find") +public class FindFactories extends EntaxyProducerServiceSupport implements Action { + + @Argument(index = 0, required = true) + String filter; + + @Override + public Object execute() throws Exception { + + Filter osgiFilter = null; + + try { + osgiFilter = FrameworkUtil.createFilter(filter); + } catch (InvalidSyntaxException e) { + + // print error + System.err.println("Invalid filter:"); + e.printStackTrace(System.err); + + return null; + + } + + List factories = + producerService.findFactories(osgiFilter).stream().sorted(new Comparator() { + + @Override + public int compare(EntaxyFactory o1, EntaxyFactory o2) { + return o1.getId().compareToIgnoreCase(o2.getId()); + } + }) + .collect(Collectors.toList()); + + ShellTableExt table = new ShellTableExt(); + + table.column("Id"); + table.column("Type"); + + for (EntaxyFactory f : factories) + table.addRow().addContent(f.getId(), f.getType()); + + // print output + table.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/EntaxyObjectCustomizer.java b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/EntaxyObjectCustomizer.java new file mode 100644 index 00000000..bd7de68c --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/EntaxyObjectCustomizer.java @@ -0,0 +1,38 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime; + +import ru.entaxy.platform.base.objects.EntaxyObject; + +public interface EntaxyObjectCustomizer { + + boolean isAccepted(EntaxyObject entaxyObject); + + EntaxyObject applyCustomization(EntaxyObject entaxyObject); + + EntaxyObject unapplyCustomization(EntaxyObject entaxyObject); + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/EntaxyRuntimeObjectExtendedDataProvider.java b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/EntaxyRuntimeObjectExtendedDataProvider.java new file mode 100644 index 00000000..46005017 --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/EntaxyRuntimeObjectExtendedDataProvider.java @@ -0,0 +1,36 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime; + +import java.util.Map; + +public interface EntaxyRuntimeObjectExtendedDataProvider { + + String getProviderId(); + + Map getExtendedData(EntaxyRuntimeObject runtimeObject); + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/impl/ClusterExtendedDataProvider.java b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/impl/ClusterExtendedDataProvider.java new file mode 100644 index 00000000..6b8e79c1 --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/impl/ClusterExtendedDataProvider.java @@ -0,0 +1,99 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime.impl; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.objects.EntaxyObject.BundleInfo; +import ru.entaxy.platform.core.support.runtime.cluster.ClusterBundleDataProvider; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectExtendedDataProvider; + +@Component(service = EntaxyRuntimeObjectExtendedDataProvider.class, immediate = true) +public class ClusterExtendedDataProvider implements EntaxyRuntimeObjectExtendedDataProvider { + + private static final Logger LOG = LoggerFactory.getLogger(ClusterExtendedDataProvider.class); + + private static final String CLUSTER_PROVIDER_ID = "cluster"; + + @Reference(cardinality = ReferenceCardinality.OPTIONAL, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile protected ClusterBundleDataProvider clusterBundleDataProvider = null; + + protected BundleContext bundleContext; + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + } + + @Override + public String getProviderId() { + return CLUSTER_PROVIDER_ID; + } + + @Override + public Map getExtendedData(EntaxyRuntimeObject runtimeObject) { + if (clusterBundleDataProvider == null) + return null; + Map result = new HashMap<>(); + + List groups = getClusterGroups(runtimeObject); + if (groups != null) { + result.put("groups", groups); + result.put("objectClusterState", !groups.isEmpty() ? + groups.stream().allMatch(group -> group.startsWith("?")) ? "non-clustered" : "clustered" : "local"); + } + + return result; + } + + protected List getClusterGroups(EntaxyRuntimeObject runtimeObject) { + try { + BundleInfo bi = runtimeObject.getBundleInfo(); + Bundle bundle = bundleContext.getBundle(bi.getBundleId()); + return clusterBundleDataProvider.getGroups(bundle); + } catch (Exception e) { + LOG.error(String.format("Error getting cluster groups for [%s]", runtimeObject.getObjectFullId()), e); + return null; + } + } + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/impl/RuntimeObjectSearchProvider.java b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/impl/RuntimeObjectSearchProvider.java new file mode 100644 index 00000000..2088f779 --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/impl/RuntimeObjectSearchProvider.java @@ -0,0 +1,171 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime.impl; + +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.Filter; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.service.component.annotations.ReferencePolicy; +import org.osgi.service.component.annotations.ReferencePolicyOption; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectContainer; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectService; +import ru.entaxy.platform.search.AbstractSearchProvider; +import ru.entaxy.platform.search.SearchProvider; +import ru.entaxy.platform.search.SearchProviderInfo; +import ru.entaxy.platform.search.SearchService; + +@Component(service = SearchProvider.class, immediate = true) +@SearchProviderInfo(id = "runtime", + targetTypes = {RuntimeObjectSearchProvider.TYPE_OBJECT, RuntimeObjectSearchProvider.TYPE_CONTAINER}) +public class RuntimeObjectSearchProvider extends AbstractSearchProvider { + + public static final String TYPE_OBJECT = "object"; + public static final String TYPE_CONTAINER = "container"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile SearchService searchService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC, + policyOption = ReferencePolicyOption.GREEDY) + volatile EntaxyRuntimeObjectService objectService; + + @Override + public Map getStandardAttributes(String targetType) throws IllegalArgumentException { + + if (TYPE_CONTAINER.equalsIgnoreCase(targetType)) + return EntaxyRuntimeObjectContainer.SEARCH.STANDARD_ATTRIBUTES; + + if (TYPE_OBJECT.equalsIgnoreCase(targetType)) { + Map result = new LinkedHashMap<>(); + result.putAll(EntaxyRuntimeObject.SEARCH.STANDARD_ATTRIBUTES); + + result.putAll(CommonUtils.prefixMap(EntaxyRuntimeObjectContainer.SEARCH.STANDARD_ATTRIBUTES, "container.")); + + // factory fields we'll get via search service + // for 'runtime-only' nodes the information can be unavailable + + try { + result.putAll(CommonUtils.prefixMap(searchService.getStandardAttributes("factory"), "factory.")); + } catch (Exception ignore) { + // NOOP + } + + return result; + } + + throw new IllegalArgumentException( + String.format("Provider [%s]: type [%s] nor supported", getProviderId(), targetType)); + } + + @Override + public List> search(String targetType, Filter filter) throws IllegalArgumentException { + if (TYPE_CONTAINER.equalsIgnoreCase(targetType)) + return searchContainers(filter); + + if (TYPE_OBJECT.equalsIgnoreCase(targetType)) + return searchObjects(filter); + + throw new IllegalArgumentException( + String.format("Provider [%s]: type [%s] nor supported", getProviderId(), targetType)); + } + + protected List> searchObjects(Filter filter) { + return objectService.getObjects().stream() + .map(obj -> getObjectEssence(obj)) + .filter(ess -> filter.matches(ess)) + .collect(Collectors.toList()); + } + + protected Map getObjectEssence(EntaxyRuntimeObject object) { + + Map result = new LinkedHashMap<>(); + + // object attributes + result.put(EntaxyRuntimeObject.SEARCH.ATTR_ID, object.getId()); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_TYPE, object.getType()); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_LABEL, object.getAllAttributes().getOrDefault("label", "")); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_DISPLAY_NAME, object.getDisplayName()); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_FACTORY, object.getFactoryId()); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_SCOPE, object.getScope()); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_RESOURCES, object.getResources().stream() + .map(res -> String.format("%s;%s", res.getResourceUrl(), res.getScope().name())) + .collect(Collectors.toList())); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_RELATIONS_IN, + object.getIncomingRelations().stream().map(rel -> String.format("%s;%S;%s:%s", + rel.getSource().getObjectFullId(), rel.getType().name(), rel.getName(), rel.getGroup())) + .collect(Collectors.toList())); + result.put(EntaxyRuntimeObject.SEARCH.ATTR_RELATIONS_OUT, + object.getRelations().stream().map(rel -> String.format("%s;%S;%s:%s", + rel.getTarget().getObjectFullId(), rel.getType().name(), rel.getName(), rel.getGroup())) + .collect(Collectors.toList())); + + // container attributes + result.putAll(CommonUtils.prefixMap(getContainerEssence(object.getContainer()), "container.")); + + // factory attributes we'll get via search service + // for 'runtime-only' nodes the information can be unavailable + + try { + List> factories = searchService.search("factory", + String.format("(&(id=%s)(type=%s))", object.getFactoryId(), object.getType())); + if (factories != null && !factories.isEmpty()) + result.putAll(CommonUtils.prefixMap(factories.get(0), "factory.")); + } catch (Exception ignore) { + // NOOP + } + + return result; + } + + protected List> searchContainers(Filter filter) { + return objectService.getContainers().stream() + .map(obj -> getContainerEssence(obj)) + .filter(ess -> filter.matches(ess)) + .collect(Collectors.toList()); + } + + protected Map getContainerEssence(EntaxyRuntimeObjectContainer container) { + Map result = new LinkedHashMap<>(); + + result.put(EntaxyRuntimeObjectContainer.SEARCH.ATTR_ID, container.getId()); + result.put(EntaxyRuntimeObjectContainer.SEARCH.ATTR_TYPE, container.getType()); + result.put(EntaxyRuntimeObjectContainer.SEARCH.ATTR_NAME, container.getName()); + result.put(EntaxyRuntimeObjectContainer.SEARCH.ATTR_STATE, container.getState()); + + return result; + } + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/internal/ObjectResourcesProvider.java b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/internal/ObjectResourcesProvider.java new file mode 100644 index 00000000..11c1197b --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-core/src/main/java/ru/entaxy/platform/objects/runtime/internal/ObjectResourcesProvider.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-core + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime.internal; + +import org.osgi.service.component.annotations.Activate; + +import ru.entaxy.esb.resources.impl.AbstractResourceProviderProxy; + +// @Component(service = EntaxyResourceProviderProxy.class, immediate = true) +/** + * @Deprecated already defined in core-support-runtime + */ +@Deprecated(forRemoval = true) +public class ObjectResourcesProvider extends AbstractResourceProviderProxy { + + @Activate + public void activate() { + + setProtocol("object-resources"); + setTargetProtocol("entaxy-file-internal"); + setTargetPath(".object-resources"); + + } + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-shell/src/main/java/ru/entaxy/platform/objects/runtime/shell/ObjectFind.java b/platform/runtime/core/object-runtime/object-runtime-shell/src/main/java/ru/entaxy/platform/objects/runtime/shell/ObjectFind.java new file mode 100644 index 00000000..c93f539e --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-shell/src/main/java/ru/entaxy/platform/objects/runtime/shell/ObjectFind.java @@ -0,0 +1,63 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime.shell; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.Argument; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@Service +@Command(name = "find-objects", scope = EntaxyRuntimeObjectServiceSupport.OBJECTS_SCOPE) +public class ObjectFind extends EntaxyRuntimeObjectServiceSupport implements Action { + + @Argument(index = 0) + String filter; + + @Override + public Object execute() throws Exception { + + Filter odgiFilter = FrameworkUtil.createFilter(filter); + + ShellTableExt shellTable = new ShellTableExt(); + shellTable.column("Id"); + shellTable.column("Type"); + + for (EntaxyRuntimeObject obj : objectService.findObjects(odgiFilter)) + shellTable.addRow().addContent( + obj.getId(), obj.getType()); + + shellTable.print(System.out); + + return null; + } + +} diff --git a/platform/runtime/core/object-runtime/object-runtime-shell/src/main/java/ru/entaxy/platform/objects/runtime/shell/ObjectVersions.java b/platform/runtime/core/object-runtime/object-runtime-shell/src/main/java/ru/entaxy/platform/objects/runtime/shell/ObjectVersions.java new file mode 100644 index 00000000..15e61291 --- /dev/null +++ b/platform/runtime/core/object-runtime/object-runtime-shell/src/main/java/ru/entaxy/platform/objects/runtime/shell/ObjectVersions.java @@ -0,0 +1,76 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-runtime-shell + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.objects.runtime.shell; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Reference; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.core.artifact.Artifact; +import ru.entaxy.platform.core.artifact.Artifacts; +import ru.entaxy.platform.core.artifact.repository.ArtifactRepository; +import ru.entaxy.platform.core.artifact.service.ArtifactService; +import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject; + +@Service +@Command(name = "object-versions", scope = EntaxyRuntimeObjectServiceSupport.OBJECTS_SCOPE, + description = "List available object versions") +public class ObjectVersions extends RuntimeObjectAwareCommand { + + @Reference + ArtifactService artifactService; + + @Override + public Object doExecute(EntaxyRuntimeObject entaxyObject) throws Exception { + Set availaleVersions = new HashSet<>(); + + Artifact artifact = Artifacts.create(Artifact.ARTIFACT_CATEGORY_BUNDLE); + artifact.getCoordinates().groupId(entaxyObject.getType()).artifactId(entaxyObject.getId()); + + String[] repos = new String[] {ArtifactRepository.REPO_NAME_LOCAL, ArtifactRepository.REPO_NAME_SHARED}; + for (String repoName : repos) { + List versions = artifactService.getRepository(repoName).getAvailableVersions(artifact); + if (versions != null) + availaleVersions.addAll(versions); + } + + List list = new ArrayList<>(availaleVersions); + Collections.sort(list); + + System.out.println("Available versions:\n"); + System.out.println(list.stream().collect(Collectors.joining("\n"))); + + return null; + } + +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/LICENSE.txt b/platform/runtime/core/objects-implementations/config-implementation/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/LICENSE.txt b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/pom.xml b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/pom.xml new file mode 100644 index 00000000..f3c57b3b --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/pom.xml @@ -0,0 +1,49 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + config-implementation + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations.config-implementation + config-runtime + bundle + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: CONFIG :: RUNTIME + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: CONFIG :: RUNTIME + + + + ru.entaxy.platform.config.runtime + + + + + org.apache.karaf.config + org.apache.karaf.config.core + ${karaf.version} + + + org.apache.felix + org.apache.felix.configadmin + ${felix.configadmin.version} + + + + ru.entaxy.esb.platform.runtime.core.object-producing + + object-producer-core + ${project.version} + + + ru.entaxy.esb.platform.runtime.core + object-runtime-core + ${project.version} + + + commons-io + commons-io + ${commons-io.version} + + + + diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ConfigEntaxyObject.java b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ConfigEntaxyObject.java new file mode 100644 index 00000000..4921496c --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ConfigEntaxyObject.java @@ -0,0 +1,163 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.runtime; + +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.osgi.service.cm.Configuration; +import org.osgi.service.cm.ConfigurationAdmin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.support.JSONUtils; + +public class ConfigEntaxyObject implements EntaxyObject, ConfigEntaxyObjectWrapped { + + private static final Logger LOG = LoggerFactory.getLogger(ConfigEntaxyObject.class); + + protected EntaxyObject origin; + + protected Map configurationMap = new HashMap<>(); + + public ConfigEntaxyObject(EntaxyObject entaxyObject) { + super(); + this.origin = entaxyObject; + configurationMap.put(EntaxyObject.FIELDS.OBJECT_ID, origin.getId()); + configurationMap.put(EntaxyObject.FIELDS.OBJECT_TYPE, origin.getType()); + configurationMap.put(EntaxyObject.FIELDS.FACTORY_ID, origin.getFactoryId()); + } + + @Override + public EntaxyObject getOrigin() { + return this.origin; + } + + @Override + public String getId() { + return origin.getId(); + } + + @Override + public String getType() { + return origin.getType(); + } + + @Override + public String getDisplayName() { + return origin.getDisplayName(); + } + + @Override + public String getScope() { + return origin.getScope(); + } + + @Override + public String getOwner() { + return origin.getOwner(); + } + + @Override + public String getFactoryId() { + return origin.getFactoryId(); + } + + @Override + public BundleInfo getBundleInfo() { + return origin.getBundleInfo(); + } + + @Override + public String getConfiguration() { + ServiceReference ref = + ObjectConfigHelper.getInstance().getReference(ConfigurationAdmin.class); + if (ref != null) { + ConfigurationAdmin configurationAdmin = ObjectConfigHelper.getInstance().getService(ref); + + Map properties = new HashMap<>(); + + try { + Configuration config = configurationAdmin.getConfiguration(getId(), "?"); + + Enumeration keys = config.getProperties().keys(); + + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + properties.put(key, config.getProperties().get(key)); + } + + properties.remove("felix.fileinstall.filename"); + properties.remove(Constants.SERVICE_PID); + properties.remove(ConfigurationAdmin.SERVICE_FACTORYPID); + + configurationMap.put(EntaxyObject.FIELDS.PROPERTIES, properties); + + + return JSONUtils.GSON.toJsonTree(configurationMap).toString(); + + } catch (IOException e) { + LOG.error("Error reading configuration [" + getId() + "]", e); + } finally { + ObjectConfigHelper.getInstance().ungetService(ref); + } + + } + return origin.getConfiguration(); + } + + @Override + public boolean isProvided() { + return origin.isProvided(); + } + + @Override + public boolean isComplete() { + return origin.isComplete(); + } + + @Override + public boolean isGhost() { + return origin.isGhost(); + } + + @Override + public List getRelations() { + return origin.getRelations(); + } + + @Override + public List getIncomingRelations() { + return origin.getIncomingRelations(); + } + +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ConfigEntaxyObjectWrapped.java b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ConfigEntaxyObjectWrapped.java new file mode 100644 index 00000000..068c9681 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ConfigEntaxyObjectWrapped.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.runtime; + +import ru.entaxy.platform.base.objects.EntaxyObject; + +public interface ConfigEntaxyObjectWrapped { + EntaxyObject getOrigin(); +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfig.java b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfig.java new file mode 100644 index 00000000..2d6ed3e4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfig.java @@ -0,0 +1,588 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-config-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~~~~~~ + */ +package ru.entaxy.platform.config.runtime; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.regex.Pattern; + +import org.apache.felix.utils.properties.TypedProperties; +import org.osgi.framework.ServiceReference; +import org.osgi.service.cm.Configuration; +import org.osgi.service.cm.ConfigurationAdmin; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonElement; + +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory.FieldInfo; +import ru.entaxy.platform.base.objects.factory.EntaxyFactory.OutputInfo; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.core.producer.api.EntaxyProducerService; +import ru.entaxy.platform.core.producer.api.EntaxyProducerUtils; + +public class ObjectConfig { + + private static final Logger log = LoggerFactory.getLogger(ObjectConfig.class); + + public static final String CONFIG_OBJECT_TYPE = "entaxy.runtime.config"; + + public static final String TARGET_FACTORY_FIELD_NAME = "targetObjectFactoryId"; + public static final String TARGET_TYPE_FIELD_NAME = "targetObjectType"; + public static final String TARGET_ID_FIELD_NAME = "targetObjectId"; + public static final String TARGET_OUTPUT_FIELD_NAME = "targetObjectOutput"; + + public static final String CONFIG_PROPERTIES_FIELD_NAME = "configuredProperties"; + public static final String CONFIG_FACTORY_FIELD_NAME = "__entaxy_configuredFactoryId"; + public static final String CONFIG_TYPE_FIELD_NAME = "__entaxy_configuredType"; + public static final String CONFIG_ID_FIELD_NAME = "__entaxy_configuredId"; + public static final String CONFIG_OUTPUT_FIELD_NAME = "__entaxy_configuredOutput"; + public static final String CONFIG_HINT_FIELD_NAME = "__entaxy_config_hint"; + + public static final List CONFIG_INTERNAL_FIELDS = Arrays.asList(new String[] {CONFIG_FACTORY_FIELD_NAME, + CONFIG_TYPE_FIELD_NAME, CONFIG_ID_FIELD_NAME, CONFIG_OUTPUT_FIELD_NAME, CONFIG_HINT_FIELD_NAME}); + + public static final String CONFIG_PID_FIELD_NAME = "configurationPid"; + public static final String CONFIG_PLACEHOLDER_PREFIX_FIELD_NAME = "placeholderPrefix"; + + @Deprecated + public static final String CONFIG_FIELD_NAME = "##config"; + public static final String CONFIG_DEFAULTS_FIELD_NAME = "##config"; + public static final String CONFIG_LINK_FIELD_NAME = "##config-link"; + public static final String CONFIGURABLE_ATTRIBUTE_NAME = "configurable"; + public static final String DEFAULT_FIELDS_CONFIGURABLE_ATTRIBUTE_NAME = "fieldsConfigurableByDefault"; + public static final String CONFIGURABLE_FIELDS_ATTRIBUTE_NAME = "configurableFields"; + public static final String PROPERTIES_BACKUP_FIELD = EntaxyObject.FIELDS.PROPERTIES + "_backup"; + + public static final String DIRECT_VALUE_ONLY_ATTR_NAME = "directValueOnly"; + + public static final String CONFIGURABLES_FIELD_NAME = "configurables"; + public static final String IMMUTABLES_FIELD_NAME = "immutables"; + + public static final String HEADER_OBJECT_CONFIG_PID = "Entaxy-Generated-Object-Config-Pid"; + + protected static Gson GSON = new GsonBuilder().create(); + + public static String getConfigurationPid(String objectId, String type) { + return reduceType(type) + "." + objectId.replace("-", "_"); + } + + public static String reduceType(String type) { + return type + // .replace(EntaxyObject.OBJECT_TYPES.ENTAXY_RUNTIME_TYPE_PREFIX, "e_r_") + .replace("-", "_"); + } + + public static String getConfigurationPrefix(String objectId, String type) { + return "$" + getConfigurationPid(objectId, type) + "{"; + } + + public static boolean isConfigurable(EntaxyFactory factory, String outputType, String fieldName, + boolean defaultFieldsConfigurable, List configurations) { + Optional fi = factory.getOutputByType(outputType).getFields().stream() + .filter(f -> f.getName().equals(fieldName)).findFirst(); + if (!fi.isPresent()) + return false; + + boolean fieldIsConfigurable = defaultFieldsConfigurable; + + try { + fieldIsConfigurable = fi.get().getJsonOrigin().get(CONFIGURABLE_ATTRIBUTE_NAME).getAsBoolean(); + } catch (Exception e) { + // usinf default value + } + + if (!fieldIsConfigurable) + return false; + + for (ConfigurableFieldsConfiguration cfc : configurations) + if (cfc.isConfigurable(factory, outputType, fieldName)) + return true; + + return false; + } + + public static void backupProperties(Map parameters) { + backupProperties(parameters, EntaxyObject.FIELDS.PROPERTIES); + } + + @SuppressWarnings("unchecked") + public static void backupProperties(Map parameters, String fieldName) { + if (!parameters.containsKey(fieldName)) + return; + Map backup = new HashMap<>(); + backup.putAll((Map) parameters.get(fieldName)); + parameters.put(ObjectConfig.PROPERTIES_BACKUP_FIELD, backup); + } + + public static void restoreBackupProperties(Map parameters) { + restoreBackupProperties(parameters, EntaxyObject.FIELDS.PROPERTIES); + } + + public static void restoreBackupProperties(Map parameters, String fieldName) { + if (!parameters.containsKey(ObjectConfig.PROPERTIES_BACKUP_FIELD)) + return; + parameters.put(fieldName, parameters.get(ObjectConfig.PROPERTIES_BACKUP_FIELD)); + } + + public static void removeConfigData(Map parameters) { + removeConfigData(parameters, EntaxyObject.FIELDS.PROPERTIES); + } + + @SuppressWarnings("unchecked") + public static void removeConfigData(Map parameters, String fieldName) { + if (!parameters.containsKey(fieldName)) + return; + ((Map) parameters.get(fieldName)).remove(CONFIG_FIELD_NAME); + } + + public static Map getTargetConfigMap(EntaxyFactory factory, String outputType, String fieldName, + Map configurables, Map immutables) { +/* + Optional fi = factory.getOutputByType(outputType).getFields().stream().filter(f -> f.getName().equals(fieldName)).findFirst(); + + if (!fi.isPresent()) { + log.debug("FIELD NOT FOUND: " + fieldName); + return null; + } + FieldInfo field = fi.get(); + boolean isConfigurable = true; + log.debug("\n FIELDNAME:: " + fieldName + " -> " + field.getJsonOrigin()); + if (field.getJsonOrigin().has(CONFIGURABLE_ATTRIBUTE_NAME)) + try { + isConfigurable = field.getJsonOrigin().get(CONFIGURABLE_ATTRIBUTE_NAME).getAsBoolean(); + } catch (Exception e) { + isConfigurable = true; + } + if (!isConfigurable) { + log.debug("FIELD NOT CONFIGURABLE: " + fieldName); + return null; + } +*/ + Optional fi = factory.getOutputByType(outputType).getFields().stream() + .filter(f -> f.getName().equals(fieldName)).findFirst(); + + if (!fi.isPresent()) { + log.debug("FIELD NOT FOUND: " + fieldName); + return null; + } + + FactoryOutputConfiguration conf = FactoryOutputConfiguration.read(factory, outputType); + + if (!isConfigurable(factory, outputType, fieldName, conf.defaultFieldsConfigurable, conf.configurations)) + return null; + + FieldInfo field = fi.get(); + + if (field.isImmutable()) + return immutables; + return configurables; + } + + public static String getConfiguredObjectId(String pid) { + ServiceReference ref = null; + try { + ref = + ObjectConfigHelper.getInstance().getReference(ConfigurationAdmin.class); + ConfigurationAdmin configurationAdmin = ObjectConfigHelper.getInstance().getService(ref); + + Configuration configuration = configurationAdmin.getConfiguration(pid, "?"); + if (configuration == null) + return null; + + String configuredId = configuration.getProperties().get(CONFIG_ID_FIELD_NAME).toString(); + String configuredType = configuration.getProperties().get(CONFIG_TYPE_FIELD_NAME).toString(); + + if (!CommonUtils.isValid(configuredId) || !CommonUtils.isValid(configuredType)) + return null; + + return configuredId + ":" + configuredType; + + } catch (Exception e) { + return null; + } finally { + ObjectConfigHelper.getInstance().ungetService(ref); + } + } + + public static class FactoryOutputConfiguration { + + public static FactoryOutputConfiguration read(EntaxyFactory factory, String outputType) { + + FactoryOutputConfiguration result = new FactoryOutputConfiguration(); + + OutputInfo oi = factory.getOutputByType(outputType); + if (oi == null) + oi = factory.getDefaultOutput(); + + Map outputConfig = oi.getConfig(); + + result.isConfigurable = false; + try { + result.isConfigurable = (Boolean) outputConfig.get(ObjectConfig.CONFIGURABLE_ATTRIBUTE_NAME); + } catch (Exception e) { + log.trace("Parameter [{}] not found in [{}]:[{}]", ObjectConfig.CONFIGURABLE_ATTRIBUTE_NAME, + factory.getId(), outputType); + } + if (!result.isConfigurable) + return result; + + result.defaultFieldsConfigurable = false; + try { + result.defaultFieldsConfigurable = + (Boolean) outputConfig.get(ObjectConfig.DEFAULT_FIELDS_CONFIGURABLE_ATTRIBUTE_NAME); + } catch (Exception e) { + log.trace("Parameter [{}] not found in [{}]:[{}]", + ObjectConfig.DEFAULT_FIELDS_CONFIGURABLE_ATTRIBUTE_NAME, factory.getId(), outputType); + } + + result.configurations = new ArrayList<>(); + + Object configuration = outputConfig.get(ObjectConfig.CONFIGURABLE_FIELDS_ATTRIBUTE_NAME); + if (configuration != null) { + if (configuration instanceof List) { + List configList = (List) configuration; + for (Object configItem : configList) { + if (configItem instanceof Map) { + ObjectConfig.ConfigurableFieldsConfiguration cnf = + ObjectConfig.ConfigurableFieldsConfiguration.read((Map) configItem); + result.configurations.add(cnf); + } + } + } else if (configuration instanceof Map) { + ObjectConfig.ConfigurableFieldsConfiguration cnf = + ObjectConfig.ConfigurableFieldsConfiguration.read((Map) configuration); + result.configurations.add(cnf); + } + } else { + result.configurations.add(new ObjectConfig.ConfigurableFieldsConfiguration()); + } + + return result; + } + + public boolean isConfigurable; + public boolean defaultFieldsConfigurable; + public List configurations; + + } + + public static class ConfigurableFieldsConfiguration { + + public static ConfigurableFieldsConfiguration read(Map parameters) { + JsonElement obj = GSON.toJsonTree(parameters); + if (obj.isJsonObject()) { + ConfigurableFieldsConfiguration result = GSON.fromJson(obj, ConfigurableFieldsConfiguration.class); + return result; + } + return null; + } + + + List includeNames = new ArrayList<>(); + List includePatterns = new ArrayList<>(); + List excludeNames = new ArrayList<>(); + List excludePatterns = new ArrayList<>(); + + List includeTypes = new ArrayList<>(); + List excludeTypes = new ArrayList<>(); + + public ConfigurableFieldsConfiguration() { + includeTypes.add("string"); + includeTypes.add("boolean"); + includeTypes.add("number"); + includePatterns.add("*"); + } + + + public boolean isConfigurable(EntaxyFactory factory, String outputType, String fieldName) { + Optional fi = factory.getOutputByType(outputType).getFields().stream() + .filter(f -> f.getName().equals(fieldName)).findFirst(); + if (!fi.isPresent()) + return false; + + String fieldType = fi.get().getType().toLowerCase(); + + + boolean fieldIsExcluded = false; + for (String name : excludeNames) + if (fieldName.equals(name)) { + fieldIsExcluded = true; + break; + } + + if (!fieldIsExcluded) { + for (String pattern : excludePatterns) { + if (Pattern.matches(EntaxyProducerUtils.toRegexPattern(pattern), fieldName)) { + fieldIsExcluded = true; + break; + } + } + } + + + if (!fieldIsExcluded) { + for (String type : excludeTypes) + if (type.equals(fieldType)) { + fieldIsExcluded = true; + break; + } + } + + if (fieldIsExcluded) + return false; + + boolean fieldIsIncluded = false; + + // first we check types + if (!fieldIsIncluded) { + for (String type : includeTypes) + if (type.equals(fieldType)) { + fieldIsIncluded = true; + break; + } + } + if (!fieldIsIncluded) + return false; + + if (!includeNames.isEmpty() || !includePatterns.isEmpty()) + fieldIsIncluded = false; + + for (String name : includeNames) + if (fieldName.equals(name)) { + fieldIsIncluded = true; + break; + } + + if (!fieldIsIncluded) { + for (String pattern : includePatterns) { + if (Pattern.matches(EntaxyProducerUtils.toRegexPattern(pattern), fieldName)) { + fieldIsIncluded = true; + break; + } + } + } + + return fieldIsIncluded; + } + } + + public static class ConfigHint { + + public static final String CONFIG_HINT_SECTION_FIELDS = "fields"; + + protected Map configHint = new HashMap<>(); + + public Map getAsMap() { + return configHint; + } + + public JsonElement getAsJson() { + return JSONUtils.GSON.toJsonTree(configHint); + } + + public String getAsJsonString() { + return getAsJson().toString(); + } + + public void generate(Map configProperties, String factoryId, String outputType) { + + Map fieldsHint = generateFieldsHint(configProperties, factoryId, outputType); + if (fieldsHint != null) + configHint.put(CONFIG_HINT_SECTION_FIELDS, fieldsHint); + + } + + public void readFrom(TypedProperties typedProperties) { + if (typedProperties.containsKey(CONFIG_HINT_FIELD_NAME)) { + String encoded = typedProperties.get(CONFIG_HINT_FIELD_NAME).toString(); + String hintString = new String(Base64.getDecoder().decode(encoded)); + read(hintString); + } + } + + public void read(String hintString) { + this.configHint = JSONUtils.element2map(JSONUtils.getJsonRootObject(hintString)); + } + + protected Map generateFieldsHint(Map configProperties, String factoryId, + String outputType) { + + Map result = new HashMap<>(); + + try { + + ServiceReference ref = + ObjectConfigHelper.getInstance().getReference(EntaxyProducerService.class); + if (ref != null) { + EntaxyProducerService entaxyProducerService = ObjectConfigHelper.getInstance().getService(ref); + + EntaxyFactory factory = entaxyProducerService.findFactoryById(factoryId); + if (factory == null) { + log.error("Factory not found: [{}]", factoryId); + return null; + } + + OutputInfo outputInfo = null; + + if (CommonUtils.isValid(outputType)) { + outputInfo = factory.getOutputByType(outputType); + } else { + outputInfo = factory.getDefaultOutput(); + } + if (outputInfo == null) { + log.error("Output [{}] not found in factory [{}]", outputType, factoryId); + return null; + } + + for (FieldInfo fi : outputInfo.getFields()) { + if (configProperties.containsKey(fi.getName())) { + ConfigFieldHint fieldHint = ConfigFieldHint.create(fi); + result.put(fieldHint.getName(), (Map) fieldHint); + } + } + + ObjectConfigHelper.getInstance().ungetService(ref); + + for (String name : ObjectConfig.CONFIG_INTERNAL_FIELDS) { + ConfigFieldHint fieldHint = new ConfigFieldHint(name); + fieldHint.setInternal(true); + result.put(name, (Map) fieldHint); + } + + } + + return result; + + } catch (Exception e) { + return null; + } + } + + public Map getFieldsHint() { + if (configHint.containsKey(CONFIG_HINT_SECTION_FIELDS)) { + Object obj = configHint.get(CONFIG_HINT_SECTION_FIELDS); + if (obj instanceof Map) { + Map fieldHints = (Map) obj; + Map result = new HashMap<>(); + + for (String name : fieldHints.keySet()) { + ConfigFieldHint fieldHint = new ConfigFieldHint(name); + fieldHint.load((Map) fieldHints.get(name)); + result.put(name, fieldHint); + } + + return result; + } + } + return new HashMap<>(); + } + + } + + public static class ConfigFieldHint extends HashMap { + + private static final long serialVersionUID = 1L; + + public static final String CONFIG_FIELD_IS_INTERNAL = "isInternal"; + + public static ConfigFieldHint create(FieldInfo fieldInfo) { + ConfigFieldHint result = new ConfigFieldHint(fieldInfo.getName()); + + result.setType(fieldInfo.getType()); + result.setDisplayName(fieldInfo.getDisplayName()); + result.setDescription(fieldInfo.getDescription()); + result.setInternal(false); + + return result; + + } + + public ConfigFieldHint(String name) { + super(); + setName(name); + } + + String name; + + public void load(Map data) { + this.putAll(data); + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getDisplayName() { + Object displayName = getOrDefault(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.FIELD_DISPLAY_NAME, ""); + return displayName != null ? displayName.toString() : ""; + } + + public void setDisplayName(String displayName) { + put(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.FIELD_DISPLAY_NAME, displayName); + } + + public String getType() { + return getOrDefault(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.FIELD_TYPE, "String").toString(); + } + + public void setType(String type) { + put(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.FIELD_TYPE, type); + } + + public String getDescription() { + return getOrDefault(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.FIELD_DESCRIPTION, "").toString(); + } + + public void setDescription(String description) { + put(EntaxyFactory.CONFIGURATION.FIELDS.ATTRIBUTES.FIELD_DESCRIPTION, description); + } + + public boolean isInternal() { + return (Boolean) getOrDefault(CONFIG_FIELD_IS_INTERNAL, false); + } + + public void setInternal(boolean isInternal) { + put(CONFIG_FIELD_IS_INTERNAL, isInternal); + } + + } + +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigCustomizer.java b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigCustomizer.java new file mode 100644 index 00000000..5cd47f56 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigCustomizer.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.runtime; + +import org.osgi.service.component.annotations.Component; + +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.objects.runtime.EntaxyObjectCustomizer; + +@Component(service = EntaxyObjectCustomizer.class, immediate = true) +public class ObjectConfigCustomizer implements EntaxyObjectCustomizer { + + @Override + public boolean isAccepted(EntaxyObject entaxyObject) { + return entaxyObject.getType().equals(ObjectConfig.CONFIG_OBJECT_TYPE); + } + + @Override + public EntaxyObject applyCustomization(EntaxyObject entaxyObject) { + if (entaxyObject instanceof ConfigEntaxyObjectWrapped) + return entaxyObject; + return new ConfigEntaxyObject(entaxyObject); + } + + @Override + public EntaxyObject unapplyCustomization(EntaxyObject entaxyObject) { + if (entaxyObject instanceof ConfigEntaxyObjectWrapped) + return ((ConfigEntaxyObjectWrapped) entaxyObject).getOrigin(); + return entaxyObject; + } + +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigEditor.java b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigEditor.java new file mode 100644 index 00000000..cddee5cf --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigEditor.java @@ -0,0 +1,209 @@ +/*- + * ~~~~~~licensing~~~~~~ + * config-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.config.runtime; + +import java.io.File; +import java.io.IOException; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.apache.felix.utils.properties.TypedProperties; +import org.osgi.framework.Constants; +import org.osgi.framework.ServiceReference; +import org.osgi.service.cm.Configuration; +import org.osgi.service.cm.ConfigurationAdmin; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.config.runtime.ObjectConfig.ConfigFieldHint; + +public class ObjectConfigEditor { + + public static ObjectConfigEditor create(File configFile) throws IOException { + return new ObjectConfigEditor(configFile); + } + + protected String pid; + + protected File configFile; + + protected TypedProperties loadedProperties; + + protected ObjectConfig.ConfigHint configHint = new ObjectConfig.ConfigHint(); + + protected TypedProperties modifiedProperties = new TypedProperties(); + + protected Map currentProperties = new HashMap<>(); + + protected Map fieldHints = new HashMap<>(); + + protected ObjectConfigEditor(File configFile) throws IOException { + super(); + this.configFile = configFile; + loadedProperties = new TypedProperties(); + loadedProperties.load(configFile); + configHint.readFrom(loadedProperties); + fieldHints = configHint.getFieldsHint(); + } + + public void loadCurrent(String pid) throws Exception { + ServiceReference ref = null; + try { + ref = ObjectConfigHelper.getInstance().getReference(ConfigurationAdmin.class); + ConfigurationAdmin configurationAdmin = ObjectConfigHelper.getInstance().getService(ref); + + int pos = pid.indexOf('~'); + if (pos >= 0) { + pid = pid.substring(0, pos); + } + Configuration configuration = configurationAdmin.getConfiguration(pid, "?"); + + currentProperties.clear(); + if (configuration.getProperties() == null) { + return; + } + Enumeration keys = configuration.getProperties().keys(); + while (keys.hasMoreElements()) { + String key = keys.nextElement(); + currentProperties.put(key, configuration.getProperties().get(key)); + } + + } finally { + if (ref != null) + ObjectConfigHelper.getInstance().ungetService(ref); + } + + } + + public boolean isDirty() { + return !modifiedProperties.isEmpty(); + } + + public Set getPropertiesNames() { + Set result = new HashSet<>(); + result.addAll(loadedProperties.keySet()); + result.addAll(currentProperties.keySet()); + + // remove hint field itself + result.remove(ObjectConfig.CONFIG_HINT_FIELD_NAME); + // remove felix property + result.remove("felix.fileinstall.filename"); + // remove osgi properties + result.remove(Constants.SERVICE_PID); + + + return result; + } + + public ConfigProperty getAsConfigProperty(String name) { + if (!getPropertiesNames().contains(name)) + return null; + ConfigProperty result = new ConfigProperty(name); + if (loadedProperties.containsKey(name)) + result.configValue = loadedProperties.get(name); + if (currentProperties.containsKey(name)) + result.currentValue = currentProperties.get(name); + if (modifiedProperties.containsKey(name)) + result.modifiedValue = modifiedProperties.get(name); + if (fieldHints.containsKey(name)) + result.hint = fieldHints.get(name); + return result; + } + + public void setValue(String propertyName, String propertyValue) throws Exception { + if (!loadedProperties.containsKey(propertyName) && !currentProperties.containsKey(propertyName)) + throw new IllegalArgumentException("Unknown property: [" + propertyName + "]"); + ConfigProperty property = getAsConfigProperty(propertyName); + String dataType = CommonUtils.getValid(property.hint.getType(), "string").toLowerCase(); + + Object valueToSet = propertyValue; + + if ("boolean".equals(dataType)) { + try { + valueToSet = Boolean.parseBoolean(propertyValue); + } catch (Exception e) { + valueToSet = Boolean.FALSE; + } + } else if ("number".equals(valueToSet)) { + try { + valueToSet = NumberUtils.createNumber(propertyValue); + } catch (Exception e) { + valueToSet = 0; + } + + } + + modifiedProperties.put(propertyName, valueToSet); + + } + + public File getConfigFile() { + return configFile; + } + + public void save() throws IOException { + if (!isDirty()) + return; + loadedProperties.putAll(modifiedProperties); + loadedProperties.save(configFile); + } + + public void clear() { + FileUtils.deleteQuietly(configFile); + } + + public String getPid() { + return pid; + } + + public void setPid(String pid) { + this.pid = pid; + } + + public static class ConfigProperty { + public ConfigFieldHint hint; + public Object configValue = null; + public Object currentValue = null; + public Object modifiedValue = null; + + public String name; + + public ConfigProperty(String name) { + this.name = name; + this.hint = new ConfigFieldHint(name); + } + + public boolean isDirty() { + return modifiedValue != null; + } + + } + +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigHelper.java b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigHelper.java new file mode 100644 index 00000000..79cbf0d2 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/config-runtime/src/main/java/ru/entaxy/platform/config/runtime/ObjectConfigHelper.java @@ -0,0 +1,100 @@ +/*- + * ~~~~~~licensing~~~~~~ + * object-producing-config-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~~~~~~ + */ +package ru.entaxy.platform.config.runtime; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.ServiceReference; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; + +import ru.entaxy.platform.base.objects.EntaxyObject; +import ru.entaxy.platform.base.objects.EntaxyObjectService; +import ru.entaxy.platform.core.producer.executor.objectmodel.FactoredObjectRef; + +@Component(service = ObjectConfigHelper.class, immediate = true) +public class ObjectConfigHelper { + + private static ObjectConfigHelper _INSTANCE = null; + + public static ObjectConfigHelper getInstance() { + return _INSTANCE; + } + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyObjectService entaxyObjectService; + + public BundleContext bundleContext; + + public ObjectConfigHelper() { + super(); + _INSTANCE = this; + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + } + + @Deactivate + public void deactivate() { + + } + + public EntaxyObject findObject(String objectId, String objectType) { + return entaxyObjectService.findObject(objectId, objectType); + } + + public boolean isDirectValueOnly(FactoredObjectRef ref) { + if (!ref.origin.has(ObjectConfig.DIRECT_VALUE_ONLY_ATTR_NAME)) + return false; + try { + return ref.origin.get(ObjectConfig.DIRECT_VALUE_ONLY_ATTR_NAME).getAsBoolean(); + } catch (Exception e) { + return false; + } + } + + public ServiceReference getReference(Class clazz) { + if (bundleContext == null) + return null; + return bundleContext.getServiceReference(clazz); + } + + public T getService(ServiceReference ref) { + return (T) bundleContext.getService(ref); + } + + public void ungetService(ServiceReference ref) { + if (bundleContext == null) + return; + bundleContext.ungetService(ref); + } + +} diff --git a/platform/runtime/core/objects-implementations/config-implementation/pom.xml b/platform/runtime/core/objects-implementations/config-implementation/pom.xml new file mode 100644 index 00000000..3367e023 --- /dev/null +++ b/platform/runtime/core/objects-implementations/config-implementation/pom.xml @@ -0,0 +1,16 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + objects-implementations + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + config-implementation + pom + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: CONFIG + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: CONFIG + + config-runtime + + diff --git a/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/java/ru/entaxy/platform/runtime/connections/ftps/FtpsConnectionComponent.java b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/java/ru/entaxy/platform/runtime/connections/ftps/FtpsConnectionComponent.java new file mode 100644 index 00000000..15071bfe --- /dev/null +++ b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/java/ru/entaxy/platform/runtime/connections/ftps/FtpsConnectionComponent.java @@ -0,0 +1,130 @@ +/*- + * ~~~~~~licensing~~~~~~ + * file-adapter + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.runtime.connections.ftps; + +import org.apache.camel.ExtendedCamelContext; +import org.apache.camel.component.file.GenericFileEndpoint; +import org.apache.camel.component.file.remote.FtpsComponent; +import org.apache.camel.spi.PropertyConfigurer; +import org.apache.commons.net.ftp.FTPFile; +import ru.entaxy.platform.base.support.CommonUtils; + +import java.util.Map; + +public class FtpsConnectionComponent extends FtpsComponent { + + private static final String COMPONENT_CONFIGURER = "ftps-component-configurer"; + private static final String ENDPOINT_CONFIGURER = "ftps-endpoint-configurer"; + private static final String PATH_PLACEHOLDER = "PATH_PLACEHOLDER"; + + protected String username = ""; + protected String password = ""; + protected String host = ""; + protected String port = ""; + protected String directoryName = ""; + + private volatile PropertyConfigurer componentPropertyConfigurerLocal; + private volatile PropertyConfigurer endpointPropertyConfigurerLocal; + + @Override + protected void doBuild() { + + componentPropertyConfigurerLocal = getCamelContext().adapt(ExtendedCamelContext.class).getConfigurerResolver() + .resolvePropertyConfigurer(COMPONENT_CONFIGURER, getCamelContext()); + log.debug("componentPropertyConfigurerLocal: {}", componentPropertyConfigurerLocal); + + endpointPropertyConfigurerLocal = getCamelContext().adapt(ExtendedCamelContext.class).getConfigurerResolver() + .resolvePropertyConfigurer(ENDPOINT_CONFIGURER, getCamelContext()); + log.debug("endpointPropertyConfigurerLocal: {}", endpointPropertyConfigurerLocal); + } + + protected GenericFileEndpoint createEndpoint(String uri, String remaining, Map parameters) + throws Exception { + + // doBuild method called to force configurer initialization (doBuild not invoked in some scenario) + doBuild(); + uri = uri.replace(PATH_PLACEHOLDER, buildPath()); + log.debug("CREATING ENDPOINT FOR [{}]", uri); + if (CommonUtils.isValid(username)) { + parameters.put("username", username); + } + if (CommonUtils.isValid(password)) { + parameters.put("password", password); + } + + return super.createEndpoint(uri, remaining, parameters); + } + + private String buildPath() { + + StringBuilder path = new StringBuilder(); + + if (CommonUtils.isValid(host)) { + path.append(host.trim()); + } + if (CommonUtils.isValid(port)) { + path.append(":"); + path.append(port.trim()); + } + if (CommonUtils.isValid(directoryName)) { + if (!directoryName.startsWith("/")) { + path.append("/"); + } + path.append(directoryName.trim()); + } + return path.toString(); + } + + public void setUsername(String username) { + this.username = username; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setHost(String host) { + this.host = host; + } + + public void setPort(String port) { + this.port = port; + } + + public void setDirectoryName(String directoryName) { + this.directoryName = directoryName; + } + + @Override + public PropertyConfigurer getComponentPropertyConfigurer() { + return componentPropertyConfigurerLocal; + } + + @Override + public PropertyConfigurer getEndpointPropertyConfigurer() { + return endpointPropertyConfigurerLocal; + } +} diff --git a/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/factory/ftps-connection.json b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/factory/ftps-connection.json new file mode 100644 index 00000000..9cdb97a7 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/factory/ftps-connection.json @@ -0,0 +1,2442 @@ +{ + "factory": { + "id": "ftps-connection", + "type": "entaxy.runtime.connection", + "parent": "remote-file-abstract-connection", + "isAbstract": false, + "camelOriginComponent": "ftps", + "label": "ftps", + "description": "This component provides access to remote file systems over the FTP and SFTP protocols. For more details see Camel docs", + "displayName": "FTPS", + "camelOrigin": "camel-ftp", + "camelOriginJavaType": "org.apache.camel.component.file.remote.FtpsComponent" + }, + "entaxy.runtime.connection": {}, + "fields": { + "useGlobalSslContextParameters": { + "displayName": "Use Global Ssl Context Parameters", + "description": "Enable usage of global SSL context parameters. For more details see Camel docs", + "label": "security", + "type": "boolean", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "transferLoggingIntervalSeconds": { + "displayName": "Transfer Logging Interval Seconds", + "description": "Configures the interval in seconds to use when logging the progress of upload and download operations that are in-flight. This is used for logging progress when operations takes longer time. For more details see Camel docs", + "label": "common", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": 5, + "group": "common", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "transferLoggingLevel": { + "displayName": "Transfer Logging Level", + "description": "Configure the logging level to use when logging the progress of upload and download operations. For more details see Camel docs", + "label": "common", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "DEBUG", + "group": "common", + "@TYPEINFO": { + "type": "enum", + "values": [ + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "OFF" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.LoggingLevel", + "deprecated": false + } + }, + "transferLoggingVerbose": { + "displayName": "Transfer Logging Verbose", + "description": "Configures whether the perform verbose (fine grained) logging of the progress of upload and download operations. For more details see Camel docs", + "label": "common", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "common", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "resumeDownload": { + "displayName": "Resume Download", + "description": "Configures whether resume download is enabled. This must be supported by the FTP server (almost all FTP servers support it). In addition the options localWorkDirectory must be configured so downloaded files are stored in a local directory, and the option binary must be enabled, which is required to support resuming of downloads. For more details see Camel docs", + "label": "consumer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "handleDirectoryParserAbsoluteResult": { + "displayName": "Handle Directory Parser Absolute Result", + "description": "Allows you to set how the consumer will handle subfolders and files in the path if the directory parser results in with absolute paths The reason for this is that some FTP servers may return file names with absolute paths, and if so then the FTP component needs to handle this by converting the returned path into a relative path. For more details see Camel docs", + "label": "consumer,advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "activePortRange": { + "displayName": "Active Port Range", + "description": "Set the client side port range in active mode. The syntax is: minPort-maxPort Both port numbers are inclusive, eg 10000-19999 to include all 1xxxx ports. For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "bufferSize": { + "displayName": "Buffer Size", + "description": "Buffer size in bytes used for writing files (or in case of FTP for downloading and uploading files). For more details see Camel docs", + "label": "advanced", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": 131072, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "ftpClient": { + "displayName": "Ftp Client", + "description": "To use a custom instance of FTPClient. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.commons.net.ftp.FTPClient", + "deprecated": false + } + }, + "ftpClientConfig": { + "displayName": "Ftp Client Config", + "description": "To use a custom instance of FTPClientConfig to configure the FTP client the endpoint should use. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.commons.net.ftp.FTPClientConfig", + "deprecated": false + } + }, + "ftpClientConfigParameters": { + "displayName": "Ftp Client Config Parameters", + "description": "Used by FtpComponent to provide additional parameters for the FTPClientConfig. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClientConfig.", + "multiValue": true, + "deprecated": false + } + }, + "ftpClientParameters": { + "displayName": "Ftp Client Parameters", + "description": "Used by FtpComponent to provide additional parameters for the FTPClient. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClient.", + "multiValue": true, + "deprecated": false + } + }, + "siteCommand": { + "displayName": "Site Command", + "description": "Sets optional site command(s) to be executed after successful login. Multiple site commands can be separated using a new line character. For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "account": { + "displayName": "Account", + "description": "Account to use for login. For more details see Camel docs", + "label": "security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": true, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "disableSecureDataChannelDefaults": { + "displayName": "Disable Secure Data Channel Defaults", + "description": "Use this option to disable default options when using secure data channel. This allows you to be in full control what the execPbsz and execProt setting should be used. Default is false. For more details see Camel docs", + "label": "security", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "execPbsz": { + "displayName": "Exec Pbsz", + "description": "When using secure data channel you can set the exec protection buffer size. For more details see Camel docs", + "label": "security", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Long", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "execProt": { + "displayName": "Exec Prot", + "description": "The exec protection level PROT command. C - Clear S - Safe(SSL protocol only) E - Confidential(SSL protocol only) P - Private. For more details see Camel docs", + "label": "security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "ftpClientKeyStoreParameters": { + "displayName": "Ftp Client Key Store Parameters", + "description": "Set the key store parameters. For more details see Camel docs", + "label": "security", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClient.keyStore.", + "multiValue": true, + "deprecated": false + } + }, + "ftpClientTrustStoreParameters": { + "displayName": "Ftp Client Trust Store Parameters", + "description": "Set the trust store parameters. For more details see Camel docs", + "label": "security", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClient.trustStore.", + "multiValue": true, + "deprecated": false + } + }, + "implicit": { + "displayName": "Implicit", + "description": "Set the security mode (Implicit/Explicit). true - Implicit Mode / False - Explicit Mode. For more details see Camel docs", + "label": "security", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "securityProtocol": { + "displayName": "Security Protocol", + "description": "Set the underlying security protocol. For more details see Camel docs", + "label": "security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "TLSv1.2", + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration" + } + }, + "sslContextParameters": { + "displayName": "Ssl Context Parameters", + "description": "Gets the JSSE configuration that overrides any settings in FtpsEndpoint#ftpClientKeyStoreParameters, ftpClientTrustStoreParameters, and FtpsConfiguration#getSecurityProtocol(). For more details see Camel docs", + "label": "security", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.support.jsse.SSLContextParameters", + "deprecated": false + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "hidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "component": { + "kind": "component", + "name": "ftps", + "title": "FTPS", + "description": "Upload and download files to/from FTP servers supporting the FTPS protocol.", + "deprecated": false, + "deprecationNote": "", + "firstVersion": "2.2.0", + "label": "file", + "javaType": "org.apache.camel.component.file.remote.FtpsComponent", + "supportLevel": "Stable", + "groupId": "org.apache.camel", + "artifactId": "camel-ftp", + "version": "3.4.5", + "scheme": "ftps", + "extendsScheme": "file", + "syntax": "ftps:host:port/directoryName", + "alternativeSyntax": "ftps:username:password@host:port/directoryName", + "async": false, + "consumerOnly": false, + "producerOnly": false, + "lenientProperties": false + }, + "componentProperties": { + "bridgeErrorHandler": { + "kind": "property", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "lazyStartProducer": { + "kind": "property", + "displayName": "Lazy Start Producer", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel\u0027s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing." + }, + "basicPropertyBinding": { + "kind": "property", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "useGlobalSslContextParameters": { + "kind": "property", + "displayName": "Use Global Ssl Context Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Enable usage of global SSL context parameters." + } + }, + "properties": { + "host": { + "kind": "path", + "displayName": "Host", + "group": "common", + "label": "", + "required": true, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "", + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Hostname of the FTP server" + }, + "port": { + "kind": "path", + "displayName": "Port", + "group": "common", + "label": "", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Port of the FTP server" + }, + "directoryName": { + "kind": "path", + "displayName": "Directory Name", + "group": "common", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "The starting directory" + }, + "binary": { + "kind": "parameter", + "displayName": "Binary", + "group": "common", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Specifies the file transfer mode, BINARY or ASCII. Default is ASCII (false)." + }, + "charset": { + "kind": "parameter", + "displayName": "Charset", + "group": "common", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "This option is used to specify the encoding of the file. You can use this on the consumer, to specify the encodings of the files, which allow Camel to know the charset it should load the file content in case the file content is being accessed. Likewise when writing a file, you can use this option to specify which charset to write the file as well. Do mind that when writing the file Camel may have to read the message content into memory to be able to convert the data into the configured charset, so do not use this if you have big messages." + }, + "disconnect": { + "kind": "parameter", + "displayName": "Disconnect", + "group": "common", + "label": "common", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether or not to disconnect from remote FTP server right after use. Disconnect will only disconnect the current connection to the FTP server. If you have a consumer which you want to stop, then you need to stop the consumer/route instead." + }, + "doneFileName": { + "kind": "parameter", + "displayName": "Done File Name", + "group": "common", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Producer: If provided, then Camel will write a 2nd done file when the original file has been written. The done file will be empty. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders. The done file will always be written in the same folder as the original file. Consumer: If provided, Camel will only consume files if a done file exists. This option configures what file name to use. Either you can specify a fixed name. Or you can use dynamic placeholders.The done file is always expected in the same folder as the original file. Only ${file.name} and ${file.name.next} is supported as dynamic placeholders." + }, + "fileName": { + "kind": "parameter", + "displayName": "File Name", + "group": "common", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Use Expression such as File Language to dynamically set the filename. For consumers, it\u0027s used as a filename filter. For producers, it\u0027s used to evaluate the filename to write. If an expression is set, it take precedence over the CamelFileName header. (Note: The header itself can also be an Expression). The expression options support both String and Expression types. If the expression is a String type, it is always evaluated using the File Language. If the expression is an Expression type, the specified Expression type is used - this allows you, for instance, to use OGNL expressions. For the consumer, you can use it to filter filenames, so you can for instance consume today\u0027s file using the File Language syntax: mydata-${date:now:yyyyMMdd}.txt. The producers support the CamelOverruleFileName header which takes precedence over any existing CamelFileName header; the CamelOverruleFileName is a header that is used only once, and makes it easier as this avoids to temporary store CamelFileName and have to restore it afterwards." + }, + "passiveMode": { + "kind": "parameter", + "displayName": "Passive Mode", + "group": "common", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets passive mode connections. Default is active mode connections." + }, + "separator": { + "kind": "parameter", + "displayName": "Separator", + "group": "common", + "label": "", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.file.remote.RemoteFileConfiguration.PathSeparator", + "enum": [ + "UNIX", + "Windows", + "Auto" + ], + "deprecated": false, + "secret": false, + "defaultValue": "UNIX", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets the path separator to be used. UNIX \u003d Uses unix style path separator Windows \u003d Uses windows style path separator Auto \u003d (is default) Use existing path separator in file name" + }, + "transferLoggingIntervalSeconds": { + "kind": "parameter", + "displayName": "Transfer Logging Interval Seconds", + "group": "common", + "label": "common", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "5", + "description": "Configures the interval in seconds to use when logging the progress of upload and download operations that are in-flight. This is used for logging progress when operations takes longer time." + }, + "transferLoggingLevel": { + "kind": "parameter", + "displayName": "Transfer Logging Level", + "group": "common", + "label": "common", + "required": false, + "type": "object", + "javaType": "org.apache.camel.LoggingLevel", + "enum": [ + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "OFF" + ], + "deprecated": false, + "secret": false, + "defaultValue": "DEBUG", + "description": "Configure the logging level to use when logging the progress of upload and download operations." + }, + "transferLoggingVerbose": { + "kind": "parameter", + "displayName": "Transfer Logging Verbose", + "group": "common", + "label": "common", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Configures whether the perform verbose (fine grained) logging of the progress of upload and download operations." + }, + "fastExistsCheck": { + "kind": "parameter", + "displayName": "Fast Exists Check", + "group": "common (advanced)", + "label": "common,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If set this option to be true, camel-ftp will use the list file directly to check if the file exists. Since some FTP server may not support to list the file directly, if the option is false, camel-ftp will use the old way to list the directory and check if the file exists. This option also influences readLock\u003dchanged to control whether it performs a fast check to update file information or not. This can be used to speed up the process if the FTP server has a lot of files." + }, + "bridgeErrorHandler": { + "kind": "parameter", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "delete": { + "kind": "parameter", + "displayName": "Delete", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If true, the file will be deleted after it is processed successfully." + }, + "moveFailed": { + "kind": "parameter", + "displayName": "Move Failed", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the move failure expression based on Simple language. For example, to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again." + }, + "noop": { + "kind": "parameter", + "displayName": "Noop", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If true, the file is not moved or deleted in any way. This option is good for readonly data, or for ETL type requirements. If noop\u003dtrue, Camel will set idempotent\u003dtrue as well, to avoid consuming the same files over and over again." + }, + "preMove": { + "kind": "parameter", + "displayName": "Pre Move", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order." + }, + "preSort": { + "kind": "parameter", + "displayName": "Pre Sort", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "When pre-sort is enabled then the consumer will sort the file and directory names during polling, that was retrieved from the file system. You may want to do this in case you need to operate on the files in a sorted order. The pre-sort is executed before the consumer starts to filter, and accept files to process by Camel. This option is default\u003dfalse meaning disabled." + }, + "recursive": { + "kind": "parameter", + "displayName": "Recursive", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If a directory, will look for files in all the sub-directories as well." + }, + "resumeDownload": { + "kind": "parameter", + "displayName": "Resume Download", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Configures whether resume download is enabled. This must be supported by the FTP server (almost all FTP servers support it). In addition the options localWorkDirectory must be configured so downloaded files are stored in a local directory, and the option binary must be enabled, which is required to support resuming of downloads." + }, + "sendEmptyMessageWhenIdle": { + "kind": "parameter", + "displayName": "Send Empty Message When Idle", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead." + }, + "streamDownload": { + "kind": "parameter", + "displayName": "Stream Download", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets the download method to use when not using a local working directory. If set to true, the remote files are streamed to the route as they are read. When set to false, the remote files are loaded into memory before being sent into the route. If enabling this option then you must set stepwise\u003dfalse as both cannot be enabled at the same time." + }, + "download": { + "kind": "parameter", + "displayName": "Download", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the FTP consumer should download the file. If this option is set to false, then the message body will be null, but the consumer will still trigger a Camel Exchange that has details about the file such as file name, file size, etc. It\u0027s just that the file will not be downloaded." + }, + "exceptionHandler": { + "kind": "parameter", + "displayName": "Exception Handler", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false, + "secret": false, + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "exchangePattern": { + "kind": "parameter", + "displayName": "Exchange Pattern", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.ExchangePattern", + "enum": [ + "InOnly", + "InOut", + "InOptionalOut" + ], + "deprecated": false, + "secret": false, + "description": "Sets the exchange pattern when the consumer creates an exchange." + }, + "handleDirectoryParserAbsoluteResult": { + "kind": "parameter", + "displayName": "Handle Directory Parser Absolute Result", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Allows you to set how the consumer will handle subfolders and files in the path if the directory parser results in with absolute paths The reason for this is that some FTP servers may return file names with absolute paths, and if so then the FTP component needs to handle this by converting the returned path into a relative path." + }, + "ignoreFileNotFoundOrPermissionError": { + "kind": "parameter", + "displayName": "Ignore File Not Found Or Permission Error", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Whether to ignore when (trying to list files in directories or when downloading a file), which does not exist or due to permission error. By default when a directory or file does not exists or insufficient permission, then an exception is thrown. Setting this option to true allows to ignore that instead." + }, + "inProgressRepository": { + "kind": "parameter", + "displayName": "In Progress Repository", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.IdempotentRepository", + "deprecated": false, + "secret": false, + "description": "A pluggable in-progress repository org.apache.camel.spi.IdempotentRepository. The in-progress repository is used to account the current in progress files being consumed. By default a memory based repository is used." + }, + "localWorkDirectory": { + "kind": "parameter", + "displayName": "Local Work Directory", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "When consuming, a local work directory can be used to store the remote file content directly in local files, to avoid loading the content into memory. This is beneficial, if you consume a very big remote file and thus can conserve memory." + }, + "onCompletionExceptionHandler": { + "kind": "parameter", + "displayName": "On Completion Exception Handler", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.ExceptionHandler", + "deprecated": false, + "secret": false, + "description": "To use a custom org.apache.camel.spi.ExceptionHandler to handle any thrown exceptions that happens during the file on completion process where the consumer does either a commit or rollback. The default implementation will log any exception at WARN level and ignore." + }, + "pollStrategy": { + "kind": "parameter", + "displayName": "Poll Strategy", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.PollingConsumerPollStrategy", + "deprecated": false, + "secret": false, + "description": "A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel." + }, + "processStrategy": { + "kind": "parameter", + "displayName": "Process Strategy", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.file.GenericFileProcessStrategy\u003corg.apache.commons.net.ftp.FTPFile\u003e", + "deprecated": false, + "secret": false, + "description": "A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed, such as a special ready file exists. If this option is set then the readLock option does not apply." + }, + "useList": { + "kind": "parameter", + "displayName": "Use List", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Whether to allow using LIST command when downloading a file. Default is true. In some use cases you may want to download a specific file and are not allowed to use the LIST command, and therefore you can set this option to false. Notice when using this option, then the specific file to download does not include meta-data information such as file size, timestamp, permissions etc, because those information is only possible to retrieve when LIST command is in use." + }, + "fileExist": { + "kind": "parameter", + "displayName": "File Exist", + "group": "producer", + "label": "producer", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.file.GenericFileExist", + "enum": [ + "Override", + "Append", + "Fail", + "Ignore", + "Move", + "TryRename" + ], + "deprecated": false, + "secret": false, + "defaultValue": "Override", + "description": "What to do if a file already exists with the same name. Override, which is the default, replaces the existing file. - Append - adds content to the existing file. - Fail - throws a GenericFileOperationException, indicating that there is already an existing file. - Ignore - silently ignores the problem and does not override the existing file, but assumes everything is okay. - Move - option requires to use the moveExisting option to be configured as well. The option eagerDeleteTargetFile can be used to control what to do if an moving the file, and there exists already an existing file, otherwise causing the move operation to fail. The Move option will move any existing files, before writing the target file. - TryRename is only applicable if tempFileName option is in use. This allows to try renaming the file from the temporary name to the actual name, without doing any exists check. This check may be faster on some file systems and especially FTP servers." + }, + "flatten": { + "kind": "parameter", + "displayName": "Flatten", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Flatten is used to flatten the file name path to strip any leading paths, so it\u0027s just the file name. This allows you to consume recursively into sub-directories, but when you eg write the files to another directory they will be written in a single directory. Setting this to true on the producer enforces that any file name in CamelFileName header will be stripped for any leading paths." + }, + "jailStartingDirectory": { + "kind": "parameter", + "displayName": "Jail Starting Directory", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Used for jailing (restricting) writing files to the starting directory (and sub) only. This is enabled by default to not allow Camel to write files to outside directories (to be more secured out of the box). You can turn this off to allow writing files to directories outside the starting directory, such as parent or root folders." + }, + "lazyStartProducer": { + "kind": "parameter", + "displayName": "Lazy Start Producer", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel\u0027s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing." + }, + "moveExisting": { + "kind": "parameter", + "displayName": "Move Existing", + "group": "producer", + "label": "producer", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Expression (such as File Language) used to compute file name to use when fileExist\u003dMove is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name, file:name.ext, file:name.noext, file:onlyname, file:onlyname.noext, file:ext, and file:parent. Notice the file:parent is not supported by the FTP component, as the FTP component can only move any existing files to a relative directory based on current dir as base." + }, + "tempFileName": { + "kind": "parameter", + "displayName": "Temp File Name", + "group": "producer", + "label": "producer", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. The location for tempFilename is relative to the final file location in the option \u0027fileName\u0027, not the target directory in the base uri. For example if option fileName includes a directory prefix: dir/finalFilename then tempFileName is relative to that subdirectory dir." + }, + "tempPrefix": { + "kind": "parameter", + "displayName": "Temp Prefix", + "group": "producer", + "label": "producer", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "This option is used to write the file using a temporary name and then, after the write is complete, rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files." + }, + "allowNullBody": { + "kind": "parameter", + "displayName": "Allow Null Body", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Used to specify if a null body is allowed during file writing. If set to true then an empty file will be created, when set to false, and attempting to send a null body to the file component, a GenericFileWriteException of \u0027Cannot write null body to file.\u0027 will be thrown. If the fileExist option is set to \u0027Override\u0027, then the file will be truncated, and if set to append the file will remain unchanged." + }, + "chmod": { + "kind": "parameter", + "displayName": "Chmod", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Allows you to set chmod on the stored file. For example chmod\u003d640." + }, + "disconnectOnBatchComplete": { + "kind": "parameter", + "displayName": "Disconnect On Batch Complete", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether or not to disconnect from remote FTP server right after a Batch upload is complete. disconnectOnBatchComplete will only disconnect the current connection to the FTP server." + }, + "eagerDeleteTargetFile": { + "kind": "parameter", + "displayName": "Eager Delete Target File", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether or not to eagerly delete any existing target file. This option only applies when you use fileExists\u003dOverride and the tempFileName option as well. You can use this to disable (set it to false) deleting the target file before the temp file is written. For example you may write big files and want the target file to exists during the temp file is being written. This ensure the target file is only deleted until the very last moment, just before the temp file is being renamed to the target filename. This option is also used to control whether to delete any existing files when fileExist\u003dMove is enabled, and an existing file exists. If this option copyAndDeleteOnRenameFails false, then an exception will be thrown if an existing file existed, if its true, then the existing file is deleted before the move operation." + }, + "keepLastModified": { + "kind": "parameter", + "displayName": "Keep Last Modified", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Will keep the last modified timestamp from the source file (if any). Will use the Exchange.FILE_LAST_MODIFIED header to located the timestamp. This header can contain either a java.util.Date or long with the timestamp. If the timestamp exists and the option is enabled it will set this timestamp on the written file. Note: This option only applies to the file producer. You cannot use this option with any of the ftp producers." + }, + "moveExistingFileStrategy": { + "kind": "parameter", + "displayName": "Move Existing File Strategy", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.file.strategy.FileMoveExistingStrategy", + "deprecated": false, + "secret": false, + "description": "Strategy (Custom Strategy) used to move file with special naming token to use when fileExist\u003dMove is configured. By default, there is an implementation used if no custom strategy is provided" + }, + "sendNoop": { + "kind": "parameter", + "displayName": "Send Noop", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Whether to send a noop command as a pre-write check before uploading files to the FTP server. This is enabled by default as a validation of the connection is still valid, which allows to silently re-connect to be able to upload the file. However if this causes problems, you can turn this option off." + }, + "activePortRange": { + "kind": "parameter", + "displayName": "Active Port Range", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Set the client side port range in active mode. The syntax is: minPort-maxPort Both port numbers are inclusive, eg 10000-19999 to include all 1xxxx ports." + }, + "autoCreate": { + "kind": "parameter", + "displayName": "Auto Create", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Automatically create missing directories in the file\u0027s pathname. For the file consumer, that means creating the starting directory. For the file producer, it means the directory the files should be written to." + }, + "basicPropertyBinding": { + "kind": "parameter", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "bufferSize": { + "kind": "parameter", + "displayName": "Buffer Size", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "131072", + "description": "Buffer size in bytes used for writing files (or in case of FTP for downloading and uploading files)." + }, + "connectTimeout": { + "kind": "parameter", + "displayName": "Connect Timeout", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "duration", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "10000", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets the connect timeout for waiting for a connection to be established Used by both FTPClient and JSCH" + }, + "ftpClient": { + "kind": "parameter", + "displayName": "Ftp Client", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.commons.net.ftp.FTPClient", + "deprecated": false, + "secret": false, + "description": "To use a custom instance of FTPClient" + }, + "ftpClientConfig": { + "kind": "parameter", + "displayName": "Ftp Client Config", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.commons.net.ftp.FTPClientConfig", + "deprecated": false, + "secret": false, + "description": "To use a custom instance of FTPClientConfig to configure the FTP client the endpoint should use." + }, + "ftpClientConfigParameters": { + "kind": "parameter", + "displayName": "Ftp Client Config Parameters", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClientConfig.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "Used by FtpComponent to provide additional parameters for the FTPClientConfig" + }, + "ftpClientParameters": { + "kind": "parameter", + "displayName": "Ftp Client Parameters", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClient.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "Used by FtpComponent to provide additional parameters for the FTPClient" + }, + "maximumReconnectAttempts": { + "kind": "parameter", + "displayName": "Maximum Reconnect Attempts", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "Specifies the maximum reconnect attempts Camel performs when it tries to connect to the remote FTP server. Use 0 to disable this behavior." + }, + "reconnectDelay": { + "kind": "parameter", + "displayName": "Reconnect Delay", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "duration", + "javaType": "long", + "deprecated": false, + "secret": false, + "description": "Delay in millis Camel will wait before performing a reconnect attempt." + }, + "siteCommand": { + "kind": "parameter", + "displayName": "Site Command", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets optional site command(s) to be executed after successful login. Multiple site commands can be separated using a new line character." + }, + "soTimeout": { + "kind": "parameter", + "displayName": "So Timeout", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "duration", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "5m", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets the so timeout FTP and FTPS Only for Camel 2.4. SFTP for Camel 2.14.3/2.15.3/2.16 onwards. Is the SocketOptions.SO_TIMEOUT value in millis. Recommended option is to set this to 300000 so as not have a hanged connection. On SFTP this option is set as timeout on the JSCH Session instance." + }, + "stepwise": { + "kind": "parameter", + "displayName": "Stepwise", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets whether we should stepwise change directories while traversing file structures when downloading files, or as well when uploading a file to a directory. You can disable this if you for example are in a situation where you cannot change directory on the FTP server due security reasons. Stepwise cannot be used together with streamDownload." + }, + "synchronous": { + "kind": "parameter", + "displayName": "Synchronous", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported)." + }, + "throwExceptionOnConnectFailed": { + "kind": "parameter", + "displayName": "Throw Exception On Connect Failed", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Should an exception be thrown if connection failed (exhausted) By default exception is not thrown and a WARN is logged. You can use this to enable exception being thrown and handle the thrown exception from the org.apache.camel.spi.PollingConsumerPollStrategy rollback method." + }, + "timeout": { + "kind": "parameter", + "displayName": "Timeout", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "duration", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "30s", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Sets the data timeout for waiting for reply Used only by FTPClient" + }, + "antExclude": { + "kind": "parameter", + "displayName": "Ant Exclude", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Ant style filter exclusion. If both antInclude and antExclude are used, antExclude takes precedence over antInclude. Multiple exclusions may be specified in comma-delimited format." + }, + "antFilterCaseSensitive": { + "kind": "parameter", + "displayName": "Ant Filter Case Sensitive", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Sets case sensitive flag on ant filter." + }, + "antInclude": { + "kind": "parameter", + "displayName": "Ant Include", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Ant style filter inclusion. Multiple inclusions may be specified in comma-delimited format." + }, + "eagerMaxMessagesPerPoll": { + "kind": "parameter", + "displayName": "Eager Max Messages Per Poll", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files. Where as false would scan all files, and then perform sorting. Setting this option to false allows for sorting all files first, and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting." + }, + "exclude": { + "kind": "parameter", + "displayName": "Exclude", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Is used to exclude files, if filename matches the regex pattern (matching is case in-senstive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris" + }, + "filter": { + "kind": "parameter", + "displayName": "Filter", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.file.GenericFileFilter\u003corg.apache.commons.net.ftp.FTPFile\u003e", + "deprecated": false, + "secret": false, + "description": "Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method." + }, + "filterDirectory": { + "kind": "parameter", + "displayName": "Filter Directory", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Filters the directory based on Simple language. For example to filter on current date, you can use a simple date pattern such as ${date:now:yyyMMdd}" + }, + "filterFile": { + "kind": "parameter", + "displayName": "Filter File", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Filters the file based on Simple language. For example to filter on file size, you can use ${file:size} 5000" + }, + "idempotent": { + "kind": "parameter", + "displayName": "Idempotent", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop\u003dtrue then idempotent will be enabled as well to avoid consuming the same files over and over again." + }, + "idempotentKey": { + "kind": "parameter", + "displayName": "Idempotent Key", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language, for example to use the file name and file size, you can do: idempotentKey\u003d${file:name}-${file:size}" + }, + "idempotentRepository": { + "kind": "parameter", + "displayName": "Idempotent Repository", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.IdempotentRepository", + "deprecated": false, + "secret": false, + "description": "A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryMessageIdRepository if none is specified and idempotent is true." + }, + "include": { + "kind": "parameter", + "displayName": "Include", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Is used to include files, if filename matches the regex pattern (matching is case in-sensitive). Notice if you use symbols such as plus sign and others you would need to configure this using the RAW() syntax if configuring this as an endpoint uri. See more details at configuring endpoint uris" + }, + "maxDepth": { + "kind": "parameter", + "displayName": "Max Depth", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "2147483647", + "description": "The maximum depth to traverse when recursively processing a directory." + }, + "maxMessagesPerPoll": { + "kind": "parameter", + "displayName": "Max Messages Per Poll", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "To define a maximum messages to gather per poll. By default no maximum is set. Can be used to set a limit of e.g. 1000 to avoid when starting up the server that there are thousands of files. Set a value of 0 or negative to disabled it. Notice: If this option is in use then the File and FTP components will limit before any sorting. For example if you have 100000 files and use maxMessagesPerPoll\u003d500, then only the first 500 files will be picked up, and then sorted. You can use the eagerMaxMessagesPerPoll option and set this to false to allow to scan all files first and then sort afterwards." + }, + "minDepth": { + "kind": "parameter", + "displayName": "Min Depth", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "The minimum depth to start processing when recursively processing a directory. Using minDepth\u003d1 means the base directory. Using minDepth\u003d2 means the first sub directory." + }, + "move": { + "kind": "parameter", + "displayName": "Move", + "group": "filter", + "label": "consumer,filter", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done." + }, + "exclusiveReadLockStrategy": { + "kind": "parameter", + "displayName": "Exclusive Read Lock Strategy", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy\u003corg.apache.commons.net.ftp.FTPFile\u003e", + "deprecated": false, + "secret": false, + "description": "Pluggable read-lock as a org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy implementation." + }, + "readLock": { + "kind": "parameter", + "displayName": "Read Lock", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "enum": [ + "none", + "markerFile", + "fileLock", + "rename", + "changed", + "idempotent", + "idempotent-changed", + "idempotent-rename" + ], + "deprecated": false, + "secret": false, + "defaultValue": "none", + "description": "Used by consumer, to only poll the files if it has exclusive read-lock on the file (i.e. the file is not in-progress or being written). Camel will wait until the file lock is granted. This option provides the build in strategies: - none - No read lock is in use - markerFile - Camel creates a marker file (fileName.camelLock) and then holds a lock on it. This option is not available for the FTP component - changed - Changed is using file length/modification timestamp to detect whether the file is currently being copied or not. Will at least use 1 sec to determine this, so this option cannot consume files as fast as the others, but can be more reliable as the JDK IO API cannot always determine whether a file is currently being used by another process. The option readLockCheckInterval can be used to set the check frequency. - fileLock - is for using java.nio.channels.FileLock. This option is not avail for Windows OS and the FTP component. This approach should be avoided when accessing a remote file system via a mount/share unless that file system supports distributed file locks. - rename - rename is for using a try to rename the file as a test if we can get exclusive read-lock. - idempotent - (only for file component) idempotent is for using a idempotentRepository as the read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. - idempotent-changed - (only for file component) idempotent-changed is for using a idempotentRepository and changed as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that. - idempotent-rename - (only for file component) idempotent-rename is for using a idempotentRepository and rename as the combined read-lock. This allows to use read locks that supports clustering if the idempotent repository implementation supports that.Notice: The various read locks is not all suited to work in clustered mode, where concurrent consumers on different nodes is competing for the same files on a shared file system. The markerFile using a close to atomic operation to create the empty marker file, but its not guaranteed to work in a cluster. The fileLock may work better but then the file system need to support distributed file locks, and so on. Using the idempotent read lock can support clustering if the idempotent repository supports clustering, such as Hazelcast Component or Infinispan." + }, + "readLockCheckInterval": { + "kind": "parameter", + "displayName": "Read Lock Check Interval", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1000", + "description": "Interval in millis for the read-lock, if supported by the read lock. This interval is used for sleeping between attempts to acquire the read lock. For example when using the changed read lock, you can set a higher interval period to cater for slow writes. The default of 1 sec. may be too fast if the producer is very slow writing the file. Notice: For FTP the default readLockCheckInterval is 5000. The readLockTimeout value must be higher than readLockCheckInterval, but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit." + }, + "readLockDeleteOrphanLockFiles": { + "kind": "parameter", + "displayName": "Read Lock Delete Orphan Lock Files", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether or not read lock with marker files should upon startup delete any orphan read lock files, which may have been left on the file system, if Camel was not properly shutdown (such as a JVM crash). If turning this option to false then any orphaned lock file will cause Camel to not attempt to pickup that file, this could also be due another node is concurrently reading files from the same shared directory." + }, + "readLockLoggingLevel": { + "kind": "parameter", + "displayName": "Read Lock Logging Level", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "object", + "javaType": "org.apache.camel.LoggingLevel", + "enum": [ + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "OFF" + ], + "deprecated": false, + "secret": false, + "defaultValue": "DEBUG", + "description": "Logging level used when a read lock could not be acquired. By default a DEBUG is logged. You can change this level, for example to OFF to not have any logging. This option is only applicable for readLock of types: changed, fileLock, idempotent, idempotent-changed, idempotent-rename, rename." + }, + "readLockMarkerFile": { + "kind": "parameter", + "displayName": "Read Lock Marker File", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether to use marker file with the changed, rename, or exclusive read lock types. By default a marker file is used as well to guard against other processes picking up the same files. This behavior can be turned off by setting this option to false. For example if you do not want to write marker files to the file systems by the Camel application." + }, + "readLockMinAge": { + "kind": "parameter", + "displayName": "Read Lock Min Age", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "0", + "description": "This option is applied only for readLock\u003dchanged. It allows to specify a minimum age the file must be before attempting to acquire the read lock. For example use readLockMinAge\u003d300s to require the file is at last 5 minutes old. This can speedup the changed read lock as it will only attempt to acquire files which are at least that given age." + }, + "readLockMinLength": { + "kind": "parameter", + "displayName": "Read Lock Min Length", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1", + "description": "This option is applied only for readLock\u003dchanged. It allows you to configure a minimum file length. By default Camel expects the file to contain data, and thus the default value is 1. You can set this option to zero, to allow consuming zero-length files." + }, + "readLockRemoveOnCommit": { + "kind": "parameter", + "displayName": "Read Lock Remove On Commit", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "This option is applied only for readLock\u003didempotent. It allows to specify whether to remove the file name entry from the idempotent repository when processing the file is succeeded and a commit happens. By default the file is not removed which ensures that any race-condition do not occur so another active node may attempt to grab the file. Instead the idempotent repository may support eviction strategies that you can configure to evict the file name entry after X minutes - this ensures no problems with race conditions. See more details at the readLockIdempotentReleaseDelay option." + }, + "readLockRemoveOnRollback": { + "kind": "parameter", + "displayName": "Read Lock Remove On Rollback", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "This option is applied only for readLock\u003didempotent. It allows to specify whether to remove the file name entry from the idempotent repository when processing the file failed and a rollback happens. If this option is false, then the file name entry is confirmed (as if the file did a commit)." + }, + "readLockTimeout": { + "kind": "parameter", + "displayName": "Read Lock Timeout", + "group": "lock", + "label": "consumer,lock", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "10000", + "description": "Optional timeout in millis for the read-lock, if supported by the read-lock. If the read-lock could not be granted and the timeout triggered, then Camel will skip the file. At next poll Camel, will try the file again, and this time maybe the read-lock could be granted. Use a value of 0 or lower to indicate forever. Currently fileLock, changed and rename support the timeout. Notice: For FTP the default readLockTimeout value is 20000 instead of 10000. The readLockTimeout value must be higher than readLockCheckInterval, but a rule of thumb is to have a timeout that is at least 2 or more times higher than the readLockCheckInterval. This is needed to ensure that amble time is allowed for the read lock process to try to grab the lock before the timeout was hit." + }, + "backoffErrorThreshold": { + "kind": "parameter", + "displayName": "Backoff Error Threshold", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in." + }, + "backoffIdleThreshold": { + "kind": "parameter", + "displayName": "Backoff Idle Threshold", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "The number of subsequent idle polls that should happen before the backoffMultipler should kick-in." + }, + "backoffMultiplier": { + "kind": "parameter", + "displayName": "Backoff Multiplier", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured." + }, + "delay": { + "kind": "parameter", + "displayName": "Delay", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "500", + "description": "Milliseconds before the next poll." + }, + "greedy": { + "kind": "parameter", + "displayName": "Greedy", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages." + }, + "initialDelay": { + "kind": "parameter", + "displayName": "Initial Delay", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1000", + "description": "Milliseconds before the first poll starts." + }, + "repeatCount": { + "kind": "parameter", + "displayName": "Repeat Count", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "0", + "description": "Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever." + }, + "runLoggingLevel": { + "kind": "parameter", + "displayName": "Run Logging Level", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "object", + "javaType": "org.apache.camel.LoggingLevel", + "enum": [ + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "OFF" + ], + "deprecated": false, + "secret": false, + "defaultValue": "TRACE", + "description": "The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that." + }, + "scheduledExecutorService": { + "kind": "parameter", + "displayName": "Scheduled Executor Service", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "object", + "javaType": "java.util.concurrent.ScheduledExecutorService", + "deprecated": false, + "secret": false, + "description": "Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool." + }, + "scheduler": { + "kind": "parameter", + "displayName": "Scheduler", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "enum": [ + "none", + "spring", + "quartz" + ], + "deprecated": false, + "secret": false, + "defaultValue": "none", + "description": "To use a cron scheduler from either camel-spring or camel-quartz component" + }, + "schedulerProperties": { + "kind": "parameter", + "displayName": "Scheduler Properties", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "scheduler.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler." + }, + "startScheduler": { + "kind": "parameter", + "displayName": "Start Scheduler", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether the scheduler should be auto started." + }, + "timeUnit": { + "kind": "parameter", + "displayName": "Time Unit", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "object", + "javaType": "java.util.concurrent.TimeUnit", + "enum": [ + "NANOSECONDS", + "MICROSECONDS", + "MILLISECONDS", + "SECONDS", + "MINUTES", + "HOURS", + "DAYS" + ], + "deprecated": false, + "secret": false, + "defaultValue": "MILLISECONDS", + "description": "Time unit for initialDelay and delay options." + }, + "useFixedDelay": { + "kind": "parameter", + "displayName": "Use Fixed Delay", + "group": "scheduler", + "label": "consumer,scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details." + }, + "account": { + "kind": "parameter", + "displayName": "Account", + "group": "security", + "label": "security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Account to use for login" + }, + "disableSecureDataChannelDefaults": { + "kind": "parameter", + "displayName": "Disable Secure Data Channel Defaults", + "group": "security", + "label": "security", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Use this option to disable default options when using secure data channel. This allows you to be in full control what the execPbsz and execProt setting should be used. Default is false" + }, + "execPbsz": { + "kind": "parameter", + "displayName": "Exec Pbsz", + "group": "security", + "label": "security", + "required": false, + "type": "integer", + "javaType": "java.lang.Long", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "When using secure data channel you can set the exec protection buffer size" + }, + "execProt": { + "kind": "parameter", + "displayName": "Exec Prot", + "group": "security", + "label": "security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "The exec protection level PROT command. C - Clear S - Safe(SSL protocol only) E - Confidential(SSL protocol only) P - Private" + }, + "ftpClientKeyStoreParameters": { + "kind": "parameter", + "displayName": "Ftp Client Key Store Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClient.keyStore.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "Set the key store parameters" + }, + "ftpClientTrustStoreParameters": { + "kind": "parameter", + "displayName": "Ftp Client Trust Store Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "ftpClient.trustStore.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "Set the trust store parameters" + }, + "implicit": { + "kind": "parameter", + "displayName": "Implicit", + "group": "security", + "label": "security", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Set the security mode (Implicit/Explicit). true - Implicit Mode / False - Explicit Mode" + }, + "password": { + "kind": "parameter", + "displayName": "Password", + "group": "security", + "label": "security", + "required": false, + "type": "password", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Password to use for login" + }, + "securityProtocol": { + "kind": "parameter", + "displayName": "Security Protocol", + "group": "security", + "label": "security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "defaultValue": "TLSv1.2", + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Set the underlying security protocol." + }, + "sslContextParameters": { + "kind": "parameter", + "displayName": "Ssl Context Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "org.apache.camel.support.jsse.SSLContextParameters", + "deprecated": false, + "secret": false, + "description": "Gets the JSSE configuration that overrides any settings in FtpsEndpoint#ftpClientKeyStoreParameters, ftpClientTrustStoreParameters, and FtpsConfiguration#getSecurityProtocol()." + }, + "username": { + "kind": "parameter", + "displayName": "Username", + "group": "security", + "label": "security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "configurationClass": "org.apache.camel.component.file.remote.FtpsConfiguration", + "configurationField": "configuration", + "description": "Username to use for login" + }, + "shuffle": { + "kind": "parameter", + "displayName": "Shuffle", + "group": "sort", + "label": "consumer,sort", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "To shuffle the list of files (sort in random order)" + }, + "sortBy": { + "kind": "parameter", + "displayName": "Sort By", + "group": "sort", + "label": "consumer,sort", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Built-in sort by using the File Language. Supports nested sorts, so you can have a sort by file name and as a 2nd group sort by modified date." + }, + "sorter": { + "kind": "parameter", + "displayName": "Sorter", + "group": "sort", + "label": "consumer,sort", + "required": false, + "type": "object", + "javaType": "java.util.Comparator\u003corg.apache.camel.component.file.GenericFile\u003corg.apache.commons.net.ftp.FTPFile\u003e\u003e", + "deprecated": false, + "secret": false, + "description": "Pluggable sorter as a java.util.Comparator class." + } + } + } + }, + "outputs": { + "init": { + "fields": { + "username": {}, + "password": {}, + "host": {}, + "port": {}, + "directoryName": {}, + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + }, + "config": { + "configurable": true, + "fieldsConfigurableByDefault": true, + "configurableFields": { + "includeTypes":["string","password","number"], + "includeNames":["username","password","host","port","directoryName"], + "includePatterns":[] + } + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.body.ftl b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.body.ftl new file mode 100644 index 00000000..97172647 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.body.ftl @@ -0,0 +1,9 @@ +[#ftl] + + [=utils.createBeanProperties(properties, "camel_", true)] + [#if properties.username??][/#if] + [#if properties.password??][/#if] + + [#if properties.port??][/#if] + [#if properties.directoryName??][/#if] + diff --git a/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.ftl b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.ftl new file mode 100644 index 00000000..b8670743 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.ftl @@ -0,0 +1,19 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + +[#import "templates:object-commons/common-utils.ftl" as utils] +[#include "templates:ftps-connection/init.body.ftl"] + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.private.ftl b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.private.ftl new file mode 100644 index 00000000..477174a1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connection-implementation/standard-connections-pack/src/main/resources/ru/entaxy/templates/ftps-connection/init.private.ftl @@ -0,0 +1,3 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#import "templates:object-commons/common-utils.ftl" as utils] +[#include "templates:ftps-connection/init.body.ftl"] diff --git a/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector-in/pre-route.bak.xml b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector-in/pre-route.bak.xml new file mode 100644 index 00000000..6bd6af21 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector-in/pre-route.bak.xml @@ -0,0 +1,7 @@ + + + + + true + + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector-out/pre-output.bak.xml b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector-out/pre-output.bak.xml new file mode 100644 index 00000000..b2000645 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector-out/pre-output.bak.xml @@ -0,0 +1,7 @@ + + + + + true + + diff --git a/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector/response-route.bak.xml b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector/response-route.bak.xml new file mode 100644 index 00000000..e4de4fbd --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-connector/response-route.bak.xml @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/templates/abstract-connector/__errorHandler.ftl b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/templates/abstract-connector/__errorHandler.ftl new file mode 100644 index 00000000..f1750fb4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/templates/abstract-connector/__errorHandler.ftl @@ -0,0 +1,31 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[=properties.errorHandlerType] + + + + diff --git a/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/templates/abstract-connector/globalOptions.ftl b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/templates/abstract-connector/globalOptions.ftl new file mode 100644 index 00000000..6f0cd9f1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/connector-producing/src/main/resources/ru/entaxy/templates/abstract-connector/globalOptions.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/ftps-connector-in.json b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/ftps-connector-in.json new file mode 100644 index 00000000..ba8ea82a --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/ftps-connector-in.json @@ -0,0 +1,83 @@ +/* */ +{ + "factory": { + "id": "ftps-connector-in", + "type": "entaxy.runtime.connector", + "displayName": "FTPS :: IN", + "parent": "connection-based-connector-in", + "description": "This component provides access to remote file systems over the FTP and SFTP protocols. For more details see Camel docs", + "isAbstract": false, + "requires": [ + "ftps-connection" + ] + }, + "entaxy.runtime.connector": { + "type": "ftps", + "protocol": "ftps" + }, + "fields": { + "entaxyOriginConnection": { + "type": "entaxy.runtime.connection", + "filter": "(&(type=entaxy.runtime.connection)(label=*ftps*))" + }, + "connectorSubdirectory": { + "displayName": "Subdirectory", + "description": "Connector specific part of endpoint directory path. For example you can set value 'documents' in connection's field `Directory Name` and set value '2023september' in connectors's field `Subdirectory`, as a result endpoint will be configured to `/documents2023september` directory. Or you can add slash symbol (/) to one of these fields and make subdirectory for connector - `/documents/2023september`. For more details see Camel docs", + "type": "String", + "group": "general" + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "entaxyOriginConnection": {}, + "connectorSubdirectory": {}, + "runExclusive": { + "type": "Boolean", + "defaultValue": true + }, + "@IMPORT": [ + { + "sourceFactoryId": "ftps-connection", + "location": "outputs.consumer.fields", + "prefix": "", + "filter": { + "contained": [ + { + "attribute": "##origin", + "values": [ + "camel" + ] + }, + { + "attribute": "$key", + "inverse": true, + "values": [ + "camel_username", + "camel_password" + ] + } + ] + } + }, + { + "sourceFactoryId": "ftp-client-config", + "location": "fields", + "prefix": "" + } + ] + }, + "config": { + "configurable": true, + "fieldsConfigurableByDefault": true, + "configurableFields": { + "includeNames": [ + "connectorSubdirectory" + ], + "includePatterns": [] + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/ftps-connector-out.json b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/ftps-connector-out.json new file mode 100644 index 00000000..60e79086 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/ftps-connector-out.json @@ -0,0 +1,71 @@ +/* */ +{ + "factory": { + "id": "ftps-connector-out", + "type": "entaxy.runtime.connector", + "displayName": "FTPS :: OUT", + "parent": "connection-based-connector-out", + "description": "This component provides access to remote file systems over the FTP and SFTP protocols. For more details see Camel docs", + "isAbstract": false, + "requires": ["ftps-connection"] + }, + "entaxy.runtime.connector": { + "type": "ftps", + "protocol": "ftps" + }, + "fields": { + "entaxyOriginConnection": { + "type": "entaxy.runtime.connection", + "filter": "(&(type=entaxy.runtime.connection)(label=*ftps*))" + }, + "connectorSubdirectory": { + "displayName": "Subdirectory", + "description": "Connector specific part of endpoint directory path. For example you can set value 'documents' in connection's field `Directory Name` and set value '2023september' in connectors's field `Subdirectory`, as a result endpoint will be configured to `/documents2023september` directory. Or you can add slash symbol (/) to one of these fields and make subdirectory for connector - `/documents/2023september`. For more details see Camel docs", + "type": "String", + "group": "general" + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "entaxyOriginConnection": {}, + "connectorSubdirectory": {}, + "@IMPORT": [{ + "sourceFactoryId": "ftps-connection", + "location": "outputs.producer.fields", + "prefix": "", + "filter": { + "contained": [{ + "attribute": "##origin", + "values": ["camel"] + }, + { + "attribute": "$key", + "inverse": true, + "values": [ + "camel_username", + "camel_password" + ] + } + ] + } + }, + { + "sourceFactoryId": "ftp-client-config", + "location": "fields", + "prefix": "" + } + ] + }, + "config": { + "configurable": true, + "fieldsConfigurableByDefault": true, + "configurableFields": { + "includeNames":["connectorSubdirectory"], + "includePatterns":[] + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/http-connector-out.json b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/http-connector-out.json new file mode 100644 index 00000000..1e875c75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/factory/http-connector-out.json @@ -0,0 +1,2718 @@ +{ + "factory": { + "id": "http-connector-out", + "type": "entaxy.runtime.connector", + "displayName": "HTTP :: OUT", + "parent": "abstract-connector-out", + "isAbstract": false, + "camelOriginComponent": "http", + "label": "http", + "description": "Send requests to external HTTP servers using Apache HTTP Client 4.x. For more details see Camel docs", + "camelOrigin": "camel-http", + "camelOriginJavaType": "org.apache.camel.component.http.HttpComponent" + }, + "entaxy.runtime.connector": { + "type": "http", + "protocol": "http" + }, + "fields": { + "removeServiceHeadersBeforeSending": { + "displayName": "Remove service headers before sending", + "description": "Enable to removing service headers before sending.())", + "type": "Boolean", + "required": false, + "group": "filter", + "defaultValue": true, + "@UI": { + "transmitAlways": true + } + }, + "cookieStore": { + "displayName": "Cookie Store", + "description": "To use a custom org.apache.http.client.CookieStore. By default the org.apache.http.impl.client.BasicCookieStore is used which is an in-memory only cookie store. Notice if bridgeEndpoint\u003dtrue then the cookie store is forced to be a noop cookie store as cookie shouldn\u0027t be stored as we are just bridging (eg acting as a proxy). For more details see Camel docs", + "label": "producer", + "type": "object", + "required": false, + "hidden": false, + "group": "producer", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.http.client.CookieStore", + "deprecated": false + }, + "new": { + "javaType": "org.apache.http.client.CookieStore", + "deprecated": false + } + } + }, + "lazyStartProducer": { + "displayName": "Lazy Start Producer", + "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel\u0027s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. For more details see Camel docs", + "label": "producer", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "allowJavaSerializedObject": { + "displayName": "Allow Java Serialized Object", + "description": "Whether to allow java serialization when a request uses context-type\u003dapplication/x-java-serialized-object. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk. For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "basicPropertyBinding": { + "displayName": "Basic Property Binding", + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "clientConnectionManager": { + "displayName": "Client Connection Manager", + "description": "To use a custom and shared HttpClientConnectionManager to manage connections. If this has been configured then this is always used for all endpoints created by this component. For more details see Camel docs", + "label": "advanced", + "type": "object", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.http.conn.HttpClientConnectionManager", + "deprecated": false + }, + "new": { + "javaType": "org.apache.http.conn.HttpClientConnectionManager", + "deprecated": false + } + } + }, + "connectionsPerRoute": { + "displayName": "Connections Per Route", + "description": "The maximum number of connections per route. For more details see Camel docs", + "label": "advanced", + "type": "number", + "required": false, + "hidden": false, + "defaultValue": 20, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "int", + "deprecated": false + }, + "new": { + "javaType": "int", + "deprecated": false + } + } + }, + "connectionTimeToLive": { + "displayName": "Connection Time To Live", + "description": "The time for connection to live, the time unit is millisecond, the default value is always keep alive. For more details see Camel docs", + "label": "advanced", + "type": "number", + "kind": "property", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "httpBinding": { + "displayName": "Http Binding", + "description": "To use a custom HttpBinding to control the mapping between Camel message and HttpClient. For more details see Camel docs", + "label": "advanced", + "type": "object", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.camel.http.common.HttpBinding", + "deprecated": false + }, + "new": { + "javaType": "org.apache.camel.http.common.HttpBinding", + "deprecated": false + } + } + }, + "httpClientConfigurer": { + "displayName": "Http Client Configurer", + "description": "To use the custom HttpClientConfigurer to perform configuration of the HttpClient that will be used. For more details see Camel docs", + "label": "advanced", + "type": "object", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.camel.component.http.HttpClientConfigurer", + "deprecated": false + }, + "new": { + "javaType": "org.apache.camel.component.http.HttpClientConfigurer", + "deprecated": false + } + } + }, + "httpConfiguration": { + "displayName": "Http Configuration", + "description": "To use the shared HttpConfiguration as base configuration. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "property", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.http.common.HttpConfiguration", + "deprecated": false + } + }, + "httpContext": { + "displayName": "Http Context", + "description": "To use a custom org.apache.http.protocol.HttpContext when executing requests. For more details see Camel docs", + "label": "advanced", + "type": "object", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.http.protocol.HttpContext", + "deprecated": false + }, + "new": { + "javaType": "org.apache.http.protocol.HttpContext", + "deprecated": false + } + } + }, + "maxTotalConnections": { + "displayName": "Max Total Connections", + "description": "The maximum number of connections. For more details see Camel docs", + "label": "advanced", + "type": "number", + "required": false, + "hidden": false, + "defaultValue": 200, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "int", + "deprecated": false + }, + "new": { + "javaType": "int", + "deprecated": false + } + } + }, + "headerFilterStrategy": { + "displayName": "Header Filter Strategy", + "description": "To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message. For more details see Camel docs", + "label": "filter", + "type": "object", + "required": false, + "hidden": false, + "group": "filter", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.camel.spi.HeaderFilterStrategy", + "deprecated": false + }, + "new": { + "javaType": "org.apache.camel.spi.HeaderFilterStrategy", + "deprecated": false + } + } + }, + "sslContextParameters": { + "displayName": "Ssl Context Parameters", + "description": "To configure security using SSLContextParameters. Important: Only one instance of org.apache.camel.support.jsse.SSLContextParameters is supported per HttpComponent. If you need to use 2 or more different instances, you need to define a new HttpComponent per instance you need. For more details see Camel docs", + "label": "security", + "type": "object", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "org.apache.camel.support.jsse.SSLContextParameters", + "deprecated": false + }, + "new": { + "javaType": "org.apache.camel.support.jsse.SSLContextParameters", + "deprecated": false + } + } + }, + "useGlobalSslContextParameters": { + "displayName": "Use Global Ssl Context Parameters", + "description": "Enable usage of global SSL context parameters. For more details see Camel docs", + "label": "security", + "type": "boolean", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "x509HostnameVerifier": { + "displayName": "X509 Hostname Verifier", + "description": "To use a custom X509HostnameVerifier such as DefaultHostnameVerifier or NoopHostnameVerifier. For more details see Camel docs", + "label": "security", + "type": "object", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "javax.net.ssl.HostnameVerifier", + "deprecated": false + }, + "new": { + "javaType": "javax.net.ssl.HostnameVerifier", + "deprecated": false + } + } + }, + "connectionRequestTimeout": { + "displayName": "Connection Request Timeout", + "description": "The timeout in milliseconds used when requesting a connection from the connection manager. A timeout value of zero is interpreted as an infinite timeout. A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default). For more details see Camel docs", + "label": "timeout", + "type": "number", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": { + "value": "-1" + }, + "group": "timeout", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "connectTimeout": { + "displayName": "Connect Timeout", + "description": "Determines the timeout in milliseconds until a connection is established. A timeout value of zero is interpreted as an infinite timeout. A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default). For more details see Camel docs", + "label": "timeout", + "type": "number", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": { + "value": "-1" + }, + "group": "timeout", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "socketTimeout": { + "displayName": "Socket Timeout", + "description": "Defines the socket timeout in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets). A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default). For more details see Camel docs", + "label": "timeout", + "type": "number", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": { + "value": "-1" + }, + "group": "timeout", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "httpUri": { + "displayName": "Http Uri", + "description": "The url of the HTTP endpoint to call. For more details see Camel docs", + "label": "common", + "type": "string", + "kind": "path", + "required": true, + "hidden": false, + "group": "common", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.net.URI", + "deprecated": false, + "deprecationNote": "" + } + }, + "disableStreamCache": { + "displayName": "Disable Stream Cache", + "description": "Determines whether or not the raw input stream from Servlet is cached or not (Camel will read the stream into a in memory/overflow to file, Stream caching) cache. By default Camel will cache the Servlet input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. DefaultHttpBinding will copy the request input stream into a stream cache and put it into message body if this option is false to support reading the stream multiple times. If you use Servlet to bridge/proxy an endpoint then consider enabling this option to improve performance, in case you do not need to read the message payload multiple times. The http producer will by default cache the response body stream. If setting this option to true, then the producers will not cache the response body stream but use the response stream as-is as the message body. For more details see Camel docs", + "label": "common", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "common", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "bridgeEndpoint": { + "displayName": "Bridge Endpoint", + "description": "If the option is true, HttpProducer will ignore the Exchange.HTTP_URI header, and use the endpoint\u0027s URI for request. You may also set the option throwExceptionOnFailure to be false to let the HttpProducer send all the fault response back. For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "chunked": { + "displayName": "Chunked", + "description": "If this option is false the Servlet will disable the HTTP streaming and set the content-length header on the response For more details see Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "clearExpiredCookies": { + "displayName": "Clear Expired Cookies", + "description": "Whether to clear expired cookies before sending the HTTP request. This ensures the cookies store does not keep growing by adding new cookies which is newer removed when they are expired. For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "connectionClose": { + "displayName": "Connection Close", + "description": "Specifies whether a Connection Close header must be added to HTTP Request. By default connectionClose is false. For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "copyHeaders": { + "displayName": "Copy Headers", + "description": "If this option is true then IN exchange headers will be copied to OUT exchange headers according to copy strategy. Setting this to false, allows to only include the headers from the HTTP response (not propagating IN headers). For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "customHostHeader": { + "displayName": "Custom Host Header", + "description": "To use custom host header for producer. When not set in query will be ignored. When set will override host header derived from url. For more details see Camel docs", + "label": "producer", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "httpMethod": { + "displayName": "Http Method", + "description": "Configure the HTTP method to use. The HttpMethod header cannot override this option if set. For more details see Camel docs", + "label": "producer", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "producer", + "@TYPEINFO": { + "type": "enum", + "values": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD", + "OPTIONS", + "TRACE", + "PATCH" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.http.common.HttpMethods", + "deprecated": false + } + }, + "ignoreResponseBody": { + "displayName": "Ignore Response Body", + "description": "If this option is true, The http producer won\u0027t read response body and cache the input stream For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "preserveHostHeader": { + "displayName": "Preserve Host Header", + "description": "If the option is true, HttpProducer will set the Host header to the value contained in the current exchange Host header, useful in reverse proxy applications where you want the Host header received by the downstream server to reflect the URL called by the upstream client, this allows applications which use the Host header to generate accurate URL\u0027s for a proxied service For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "throwExceptionOnFailure": { + "displayName": "Throw Exception On Failure", + "description": "Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code. For more details see Camel docs", + "label": "producer", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "transferException": { + "displayName": "Transfer Exception", + "description": "If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk. For more details see Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "cookieHandler": { + "displayName": "Cookie Handler", + "description": "Configure a cookie handler to maintain a HTTP session For more details see Camel docs", + "label": "producer,advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "producer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.http.base.cookie.CookieHandler", + "deprecated": false + } + }, + "deleteWithBody": { + "displayName": "Delete With Body", + "description": "Whether the HTTP DELETE should include the message body or not. By default HTTP DELETE do not include any HTTP body. However in some rare cases users may need to be able to include the message body. For more details see Camel docs", + "label": "producer,advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "getWithBody": { + "displayName": "Get With Body", + "description": "Whether the HTTP GET should include the message body or not. By default HTTP GET do not include any HTTP body. However in some rare cases users may need to be able to include the message body. For more details see Camel docs", + "label": "producer,advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "producer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "okStatusCodeRange": { + "displayName": "Ok Status Code Range", + "description": "The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included. For more details see Camel docs", + "label": "producer,advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "200-299", + "group": "producer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "clientBuilder": { + "displayName": "Client Builder", + "description": "Provide access to the http client request parameters used on new RequestConfig instances used by producers or consumers of this endpoint. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.http.impl.client.HttpClientBuilder", + "deprecated": false + } + }, + "httpClient": { + "displayName": "Http Client", + "description": "Sets a custom HttpClient to be used by the producer For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.http.client.HttpClient", + "deprecated": false + } + }, + "httpClientOptions": { + "displayName": "Http Client Options", + "description": "To configure the HttpClient using the key/values from the Map. For more details see Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "httpClient.", + "multiValue": true, + "deprecated": false + } + }, + "mapHttpMessageBody": { + "displayName": "Map Http Message Body", + "description": "If this option is true then IN exchange Body of the exchange will be mapped to HTTP body. Setting this to false will avoid the HTTP mapping. For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "mapHttpMessageFormUrlEncodedBody": { + "displayName": "Map Http Message Form Url Encoded Body", + "description": "If this option is true then IN exchange Form Encoded body of the exchange will be mapped to HTTP. Setting this to false will avoid the HTTP Form Encoded body mapping. For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "mapHttpMessageHeaders": { + "displayName": "Map Http Message Headers", + "description": "If this option is true then IN exchange Headers of the exchange will be mapped to HTTP headers. Setting this to false will avoid the HTTP Headers mapping. For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "synchronous": { + "displayName": "Synchronous", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "useSystemProperties": { + "displayName": "Use System Properties", + "description": "To use System Properties as fallback for configuration For more details see Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "proxyAuthDomain": { + "displayName": "Proxy Auth Domain", + "description": "Proxy authentication domain to use with NTML For more details see Camel docs", + "label": "producer,proxy", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyAuthHost": { + "displayName": "Proxy Auth Host", + "description": "Proxy authentication host For more details see Camel docs", + "label": "producer,proxy", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyAuthMethod": { + "displayName": "Proxy Auth Method", + "description": "Proxy authentication method to use For more details see Camel docs", + "label": "producer,proxy", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "@TYPEINFO": { + "type": "enum", + "values": [ + "Basic", + "Digest", + "NTLM" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyAuthPassword": { + "displayName": "Proxy Auth Password", + "description": "Proxy authentication password For more details see Camel docs", + "label": "producer,proxy", + "type": "password", + "kind": "parameter", + "required": false, + "hidden": true, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyAuthPort": { + "displayName": "Proxy Auth Port", + "description": "Proxy authentication port For more details see Camel docs", + "label": "producer,proxy", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "proxyAuthScheme": { + "displayName": "Proxy Auth Scheme", + "description": "Proxy authentication scheme to use For more details see Camel docs", + "label": "producer,proxy", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "@TYPEINFO": { + "type": "enum", + "values": [ + "http", + "https" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyAuthUsername": { + "displayName": "Proxy Auth Username", + "description": "Proxy authentication username For more details see Camel docs", + "label": "producer,proxy", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": true, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyHost": { + "displayName": "Proxy Host", + "description": "Proxy hostname to use For more details see Camel docs", + "label": "producer,proxy", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "proxyPort": { + "displayName": "Proxy Port", + "description": "Proxy port to use For more details see Camel docs", + "label": "producer,proxy", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "proxy", + "##origin": "camel", + "##camelDiff": { + "javaType": "int", + "deprecated": false + } + }, + "authDomain": { + "displayName": "Auth Domain", + "description": "Authentication domain to use with NTML For more details see Camel docs", + "label": "producer,security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "authenticationPreemptive": { + "displayName": "Authentication Preemptive", + "description": "If this option is true, camel-http sends preemptive basic authentication to the server. For more details see Camel docs", + "label": "producer,security", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "authHost": { + "displayName": "Auth Host", + "description": "Authentication host to use with NTML For more details see Camel docs", + "label": "producer,security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "authMethod": { + "displayName": "Auth Method", + "description": "Authentication methods allowed to use as a comma separated list of values Basic, Digest or NTLM. For more details see Camel docs", + "label": "producer,security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "authMethodPriority": { + "displayName": "Auth Method Priority", + "description": "Which authentication method to prioritize to use, either as Basic, Digest or NTLM. For more details see Camel docs", + "label": "producer,security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "security", + "@TYPEINFO": { + "type": "enum", + "values": [ + "Basic", + "Digest", + "NTLM" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "authPassword": { + "displayName": "Auth Password", + "description": "Authentication password For more details see Camel docs", + "label": "producer,security", + "type": "password", + "kind": "parameter", + "required": false, + "hidden": true, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "authUsername": { + "displayName": "Auth Username", + "description": "Authentication username For more details see Camel docs", + "label": "producer,security", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": true, + "group": "security", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + } + }, + "custom": { + "__customObjects": { + "type": "entaxy.runtime.connector", + "isRef": true, + "required": true, + "isHidden": true, + "isRefByValueOnly": true, + "@INTERNAL": true, + "defaultValue": { + "type": "entaxy.runtime.connector", + "factoryId": "#OWNER#", + "outputType": "customObjects", + "scope": "private", + "properties": { + "headerFilterStrategy": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.camel_headerFilterStrategy}", + "fallbackObject": null, + "lazy": false + } + }, + "x509HostnameVerifier": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.camel_x509HostnameVerifier}", + "fallbackObject": null, + "lazy": false + } + }, + "cookieStore": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.camel_cookieStore}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParameters": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.camel_sslContextParameters}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersPass": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersPass}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersKeyStoreResource": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersKeyStoreResource}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersKeyStoreType": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersKeyStoreType}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersKeyStorePass": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersKeyStorePass}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersTrustManagersKeyStoreResource": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersTrustManagersKeyStoreResource}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersTrustManagersKeyStoreType": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersTrustManagersKeyStoreType}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersTrustManagersKeyStorePass": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersTrustManagersKeyStorePass}", + "fallbackObject": null, + "lazy": false + } + } + } + } + }, + "headerFilterStrategyReference": { + "displayName": "Reference", + "description": "Reference to custom org.apache.camel.spi.HeaderFilterStrategy without leading # For more details see Camel docs", + "label": "filter", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "filter", + "defaultValue": "headerFilterStrategy", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "cookieStoreReference": { + "displayName": "Reference", + "description": "Reference to custom org.apache.http.client.CookieStore without leading # For more details see Camel docs", + "label": "producer", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "cookie", + "defaultValue": "cookieStore", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "clientConnectionManagerReference": { + "displayName": "Reference", + "description": "Reference to custom and shared HttpClientConnectionManager without leading # For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "client connection manager", + "defaultValue": "clientConnectionManager", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "httpBindingReference": { + "displayName": "Reference", + "description": "Reference to custom HttpBinding without leading # For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "http binding", + "defaultValue": "httpBinding", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "httpClientConfigurerReference": { + "displayName": "Reference", + "description": "Reference to custom HttpClientConfigurer without leading # For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "http client configurer", + "defaultValue": "httpClientConfigurer", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "httpContextReference": { + "displayName": "Reference", + "description": "Reference to custom org.apache.http.protocol.HttpContext without leading # For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "http context", + "defaultValue": "httpContext", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "x509HostnameVerifierReference": { + "displayName": "Reference", + "description": "Reference to custom X509HostnameVerifier without leading # For more details see Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "hostname verifier", + "defaultValue": "x509HostnameVerifier", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + } + + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "removeServiceHeadersBeforeSending": {}, + "httpUri": { + "group": "general" + }, + "camel_httpMethod": { + "@UI": { + "transmitAlways":true + }, + "@TYPEINFO": { + "emptyOptionName": "CAMEL_AUTO" + }, + "defaultValue": "GET" + }, + "camel_headerFilterStrategy": { + "type": "string", + "group": "header filter", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "org.apache.camel.http.common.HttpHeaderFilterStrategy", + "org.apache.camel.http.common.HttpProtocolHeaderFilterStrategy", + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "camel_cookieStore": { + "group": "cookie", + "type": "string", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "org.apache.camel.component.http.NoopCookieStore", + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "camel_clientConnectionManager": { + "group": "client connection manager", + "type": "string", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "camel_httpBinding": { + "group": "http binding", + "type": "string", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "camel_httpClientConfigurer": { + "group": "http client configurer", + "type": "string", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "camel_httpContext": { + "group": "http context", + "type": "string", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "camel_x509HostnameVerifier": { + "group": "hostname verifier", + "type": "string", + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "org.apache.http.conn.ssl.NoopHostnameVerifier", + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + }, + { + "sourceFactoryId": "#", + "location": "custom", + "prefix": "" + }, + { + "sourceFactoryId": "ssl-context-parameters", + "location": "fields", + "prefix": "" + } + ] + + }, + "config": { + "configurable": true, + "fieldsConfigurableByDefault": true, + "configurableFields": { + "includeNames":["httpUri", "camel_authUsername", "camel_authPassword"], + "includePatterns":[] + } + } + }, + "ssl-context-parameters": { + "fields": { + "__sslContextParametersTemplate":{} + }, + "scopes": ["private"], + "config": { + "@SKIP_PUBLISH": {}, + "configurable": false + } + }, + "customObjects": { + "fields": { + "headerFilterStrategy": {}, + "x509HostnameVerifier": {}, + "cookieStore": {} + }, + "scopes": ["private"], + "config": { + "@SKIP_PUBLISH": {}, + "configurable": false + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "hidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "component": { + "kind": "component", + "name": "http", + "title": "HTTP", + "description": "Send requests to external HTTP servers using Apache HTTP Client 4.x.", + "deprecated": false, + "firstVersion": "2.3.0", + "label": "http", + "javaType": "org.apache.camel.component.http.HttpComponent", + "supportLevel": "Stable", + "groupId": "org.apache.camel", + "artifactId": "camel-http", + "version": "3.4.5", + "scheme": "http", + "extendsScheme": "", + "alternativeSchemes": "http,https", + "syntax": "http:httpUri", + "async": false, + "consumerOnly": false, + "producerOnly": true, + "lenientProperties": true, + "verifiers": "parameters,connectivity" + }, + "componentProperties": { + "cookieStore": { + "kind": "property", + "displayName": "Cookie Store", + "group": "producer", + "label": "producer", + "required": false, + "type": "object", + "javaType": "org.apache.http.client.CookieStore", + "deprecated": false, + "secret": false, + "description": "To use a custom org.apache.http.client.CookieStore. By default the org.apache.http.impl.client.BasicCookieStore is used which is an in-memory only cookie store. Notice if bridgeEndpoint\u003dtrue then the cookie store is forced to be a noop cookie store as cookie shouldn\u0027t be stored as we are just bridging (eg acting as a proxy)." + }, + "lazyStartProducer": { + "kind": "property", + "displayName": "Lazy Start Producer", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel\u0027s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing." + }, + "allowJavaSerializedObject": { + "kind": "property", + "displayName": "Allow Java Serialized Object", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether to allow java serialization when a request uses context-type\u003dapplication/x-java-serialized-object. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk." + }, + "basicPropertyBinding": { + "kind": "property", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "clientConnectionManager": { + "kind": "property", + "displayName": "Client Connection Manager", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.conn.HttpClientConnectionManager", + "deprecated": false, + "secret": false, + "description": "To use a custom and shared HttpClientConnectionManager to manage connections. If this has been configured then this is always used for all endpoints created by this component." + }, + "connectionsPerRoute": { + "kind": "property", + "displayName": "Connections Per Route", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": 20, + "description": "The maximum number of connections per route." + }, + "connectionTimeToLive": { + "kind": "property", + "displayName": "Connection Time To Live", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "description": "The time for connection to live, the time unit is millisecond, the default value is always keep alive." + }, + "httpBinding": { + "kind": "property", + "displayName": "Http Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.http.common.HttpBinding", + "deprecated": false, + "secret": false, + "description": "To use a custom HttpBinding to control the mapping between Camel message and HttpClient." + }, + "httpClientConfigurer": { + "kind": "property", + "displayName": "Http Client Configurer", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.http.HttpClientConfigurer", + "deprecated": false, + "secret": false, + "description": "To use the custom HttpClientConfigurer to perform configuration of the HttpClient that will be used." + }, + "httpConfiguration": { + "kind": "property", + "displayName": "Http Configuration", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.http.common.HttpConfiguration", + "deprecated": false, + "secret": false, + "description": "To use the shared HttpConfiguration as base configuration." + }, + "httpContext": { + "kind": "property", + "displayName": "Http Context", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.protocol.HttpContext", + "deprecated": false, + "secret": false, + "description": "To use a custom org.apache.http.protocol.HttpContext when executing requests." + }, + "maxTotalConnections": { + "kind": "property", + "displayName": "Max Total Connections", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": 200, + "description": "The maximum number of connections." + }, + "headerFilterStrategy": { + "kind": "property", + "displayName": "Header Filter Strategy", + "group": "filter", + "label": "filter", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.HeaderFilterStrategy", + "deprecated": false, + "secret": false, + "description": "To use a custom org.apache.camel.spi.HeaderFilterStrategy to filter header to and from Camel message." + }, + "sslContextParameters": { + "kind": "property", + "displayName": "Ssl Context Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "org.apache.camel.support.jsse.SSLContextParameters", + "deprecated": false, + "secret": false, + "description": "To configure security using SSLContextParameters. Important: Only one instance of org.apache.camel.support.jsse.SSLContextParameters is supported per HttpComponent. If you need to use 2 or more different instances, you need to define a new HttpComponent per instance you need." + }, + "useGlobalSslContextParameters": { + "kind": "property", + "displayName": "Use Global Ssl Context Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Enable usage of global SSL context parameters." + }, + "x509HostnameVerifier": { + "kind": "property", + "displayName": "X509 Hostname Verifier", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "javax.net.ssl.HostnameVerifier", + "deprecated": false, + "secret": false, + "description": "To use a custom X509HostnameVerifier such as DefaultHostnameVerifier or NoopHostnameVerifier." + }, + "connectionRequestTimeout": { + "kind": "property", + "displayName": "Connection Request Timeout", + "group": "timeout", + "label": "timeout", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "-1", + "description": "The timeout in milliseconds used when requesting a connection from the connection manager. A timeout value of zero is interpreted as an infinite timeout. A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default)." + }, + "connectTimeout": { + "kind": "property", + "displayName": "Connect Timeout", + "group": "timeout", + "label": "timeout", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "-1", + "description": "Determines the timeout in milliseconds until a connection is established. A timeout value of zero is interpreted as an infinite timeout. A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default)." + }, + "socketTimeout": { + "kind": "property", + "displayName": "Socket Timeout", + "group": "timeout", + "label": "timeout", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": "-1", + "description": "Defines the socket timeout in milliseconds, which is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets). A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default)." + } + }, + "properties": { + "httpUri": { + "kind": "path", + "displayName": "Http Uri", + "group": "common", + "label": "common", + "required": true, + "type": "string", + "javaType": "java.net.URI", + "deprecated": false, + "deprecationNote": "", + "secret": false, + "description": "The url of the HTTP endpoint to call." + }, + "disableStreamCache": { + "kind": "parameter", + "displayName": "Disable Stream Cache", + "group": "common", + "label": "common", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Determines whether or not the raw input stream from Servlet is cached or not (Camel will read the stream into a in memory/overflow to file, Stream caching) cache. By default Camel will cache the Servlet input stream to support reading it multiple times to ensure it Camel can retrieve all data from the stream. However you can set this option to true when you for example need to access the raw stream, such as streaming it directly to a file or other persistent store. DefaultHttpBinding will copy the request input stream into a stream cache and put it into message body if this option is false to support reading the stream multiple times. If you use Servlet to bridge/proxy an endpoint then consider enabling this option to improve performance, in case you do not need to read the message payload multiple times. The http producer will by default cache the response body stream. If setting this option to true, then the producers will not cache the response body stream but use the response stream as-is as the message body." + }, + "headerFilterStrategy": { + "kind": "parameter", + "displayName": "Header Filter Strategy", + "group": "common", + "label": "common", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.HeaderFilterStrategy", + "deprecated": false, + "secret": false, + "description": "To use a custom HeaderFilterStrategy to filter header to and from Camel message." + }, + "httpBinding": { + "kind": "parameter", + "displayName": "Http Binding", + "group": "common (advanced)", + "label": "common,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.http.common.HttpBinding", + "deprecated": false, + "secret": false, + "description": "To use a custom HttpBinding to control the mapping between Camel message and HttpClient." + }, + "bridgeEndpoint": { + "kind": "parameter", + "displayName": "Bridge Endpoint", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If the option is true, HttpProducer will ignore the Exchange.HTTP_URI header, and use the endpoint\u0027s URI for request. You may also set the option throwExceptionOnFailure to be false to let the HttpProducer send all the fault response back." + }, + "chunked": { + "kind": "parameter", + "displayName": "Chunked", + "group": "producer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "If this option is false the Servlet will disable the HTTP streaming and set the content-length header on the response" + }, + "clearExpiredCookies": { + "kind": "parameter", + "displayName": "Clear Expired Cookies", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether to clear expired cookies before sending the HTTP request. This ensures the cookies store does not keep growing by adding new cookies which is newer removed when they are expired." + }, + "connectionClose": { + "kind": "parameter", + "displayName": "Connection Close", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Specifies whether a Connection Close header must be added to HTTP Request. By default connectionClose is false." + }, + "copyHeaders": { + "kind": "parameter", + "displayName": "Copy Headers", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "If this option is true then IN exchange headers will be copied to OUT exchange headers according to copy strategy. Setting this to false, allows to only include the headers from the HTTP response (not propagating IN headers)." + }, + "customHostHeader": { + "kind": "parameter", + "displayName": "Custom Host Header", + "group": "producer", + "label": "producer", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "To use custom host header for producer. When not set in query will be ignored. When set will override host header derived from url." + }, + "httpMethod": { + "kind": "parameter", + "displayName": "Http Method", + "group": "producer", + "label": "producer", + "required": false, + "type": "object", + "javaType": "org.apache.camel.http.common.HttpMethods", + "enum": [ + "GET", + "POST", + "PUT", + "DELETE", + "HEAD", + "OPTIONS", + "TRACE", + "PATCH" + ], + "deprecated": false, + "secret": false, + "description": "Configure the HTTP method to use. The HttpMethod header cannot override this option if set." + }, + "ignoreResponseBody": { + "kind": "parameter", + "displayName": "Ignore Response Body", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If this option is true, The http producer won\u0027t read response body and cache the input stream" + }, + "lazyStartProducer": { + "kind": "parameter", + "displayName": "Lazy Start Producer", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel\u0027s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing." + }, + "preserveHostHeader": { + "kind": "parameter", + "displayName": "Preserve Host Header", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If the option is true, HttpProducer will set the Host header to the value contained in the current exchange Host header, useful in reverse proxy applications where you want the Host header received by the downstream server to reflect the URL called by the upstream client, this allows applications which use the Host header to generate accurate URL\u0027s for a proxied service" + }, + "throwExceptionOnFailure": { + "kind": "parameter", + "displayName": "Throw Exception On Failure", + "group": "producer", + "label": "producer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Option to disable throwing the HttpOperationFailedException in case of failed responses from the remote server. This allows you to get all responses regardless of the HTTP status code." + }, + "transferException": { + "kind": "parameter", + "displayName": "Transfer Exception", + "group": "producer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If enabled and an Exchange failed processing on the consumer side, and if the caused Exception was send back serialized in the response as a application/x-java-serialized-object content type. On the producer side the exception will be deserialized and thrown as is, instead of the HttpOperationFailedException. The caused exception is required to be serialized. This is by default turned off. If you enable this then be aware that Java will deserialize the incoming data from the request to Java and that can be a potential security risk." + }, + "cookieHandler": { + "kind": "parameter", + "displayName": "Cookie Handler", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.http.base.cookie.CookieHandler", + "deprecated": false, + "secret": false, + "description": "Configure a cookie handler to maintain a HTTP session" + }, + "cookieStore": { + "kind": "parameter", + "displayName": "Cookie Store", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.client.CookieStore", + "deprecated": false, + "secret": false, + "description": "To use a custom CookieStore. By default the BasicCookieStore is used which is an in-memory only cookie store. Notice if bridgeEndpoint\u003dtrue then the cookie store is forced to be a noop cookie store as cookie shouldn\u0027t be stored as we are just bridging (eg acting as a proxy). If a cookieHandler is set then the cookie store is also forced to be a noop cookie store as cookie handling is then performed by the cookieHandler." + }, + "deleteWithBody": { + "kind": "parameter", + "displayName": "Delete With Body", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the HTTP DELETE should include the message body or not. By default HTTP DELETE do not include any HTTP body. However in some rare cases users may need to be able to include the message body." + }, + "getWithBody": { + "kind": "parameter", + "displayName": "Get With Body", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the HTTP GET should include the message body or not. By default HTTP GET do not include any HTTP body. However in some rare cases users may need to be able to include the message body." + }, + "okStatusCodeRange": { + "kind": "parameter", + "displayName": "Ok Status Code Range", + "group": "producer (advanced)", + "label": "producer,advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "defaultValue": "200-299", + "description": "The status codes which are considered a success response. The values are inclusive. Multiple ranges can be defined, separated by comma, e.g. 200-204,209,301-304. Each range must be a single number or from-to with the dash included." + }, + "basicPropertyBinding": { + "kind": "parameter", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "clientBuilder": { + "kind": "parameter", + "displayName": "Client Builder", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.impl.client.HttpClientBuilder", + "deprecated": false, + "secret": false, + "description": "Provide access to the http client request parameters used on new RequestConfig instances used by producers or consumers of this endpoint." + }, + "clientConnectionManager": { + "kind": "parameter", + "displayName": "Client Connection Manager", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.conn.HttpClientConnectionManager", + "deprecated": false, + "secret": false, + "description": "To use a custom HttpClientConnectionManager to manage connections" + }, + "connectionsPerRoute": { + "kind": "parameter", + "displayName": "Connections Per Route", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": 20, + "description": "The maximum number of connections per route." + }, + "httpClient": { + "kind": "parameter", + "displayName": "Http Client", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.client.HttpClient", + "deprecated": false, + "secret": false, + "description": "Sets a custom HttpClient to be used by the producer" + }, + "httpClientConfigurer": { + "kind": "parameter", + "displayName": "Http Client Configurer", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.component.http.HttpClientConfigurer", + "deprecated": false, + "secret": false, + "description": "Register a custom configuration strategy for new HttpClient instances created by producers or consumers such as to configure authentication mechanisms etc." + }, + "httpClientOptions": { + "kind": "parameter", + "displayName": "Http Client Options", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "httpClient.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "To configure the HttpClient using the key/values from the Map." + }, + "httpContext": { + "kind": "parameter", + "displayName": "Http Context", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.apache.http.protocol.HttpContext", + "deprecated": false, + "secret": false, + "description": "To use a custom HttpContext instance" + }, + "mapHttpMessageBody": { + "kind": "parameter", + "displayName": "Map Http Message Body", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "If this option is true then IN exchange Body of the exchange will be mapped to HTTP body. Setting this to false will avoid the HTTP mapping." + }, + "mapHttpMessageFormUrlEncodedBody": { + "kind": "parameter", + "displayName": "Map Http Message Form Url Encoded Body", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "If this option is true then IN exchange Form Encoded body of the exchange will be mapped to HTTP. Setting this to false will avoid the HTTP Form Encoded body mapping." + }, + "mapHttpMessageHeaders": { + "kind": "parameter", + "displayName": "Map Http Message Headers", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "If this option is true then IN exchange Headers of the exchange will be mapped to HTTP headers. Setting this to false will avoid the HTTP Headers mapping." + }, + "maxTotalConnections": { + "kind": "parameter", + "displayName": "Max Total Connections", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "defaultValue": 200, + "description": "The maximum number of connections." + }, + "synchronous": { + "kind": "parameter", + "displayName": "Synchronous", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported)." + }, + "useSystemProperties": { + "kind": "parameter", + "displayName": "Use System Properties", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "To use System Properties as fallback for configuration" + }, + "proxyAuthDomain": { + "kind": "parameter", + "displayName": "Proxy Auth Domain", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Proxy authentication domain to use with NTML" + }, + "proxyAuthHost": { + "kind": "parameter", + "displayName": "Proxy Auth Host", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Proxy authentication host" + }, + "proxyAuthMethod": { + "kind": "parameter", + "displayName": "Proxy Auth Method", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "enum": [ + "Basic", + "Digest", + "NTLM" + ], + "deprecated": false, + "secret": false, + "description": "Proxy authentication method to use" + }, + "proxyAuthPassword": { + "kind": "parameter", + "displayName": "Proxy Auth Password", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "description": "Proxy authentication password" + }, + "proxyAuthPort": { + "kind": "parameter", + "displayName": "Proxy Auth Port", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "Proxy authentication port" + }, + "proxyAuthScheme": { + "kind": "parameter", + "displayName": "Proxy Auth Scheme", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "enum": [ + "http", + "https" + ], + "deprecated": false, + "secret": false, + "description": "Proxy authentication scheme to use" + }, + "proxyAuthUsername": { + "kind": "parameter", + "displayName": "Proxy Auth Username", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "description": "Proxy authentication username" + }, + "proxyHost": { + "kind": "parameter", + "displayName": "Proxy Host", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Proxy hostname to use" + }, + "proxyPort": { + "kind": "parameter", + "displayName": "Proxy Port", + "group": "proxy", + "label": "producer,proxy", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "Proxy port to use" + }, + "authDomain": { + "kind": "parameter", + "displayName": "Auth Domain", + "group": "security", + "label": "producer,security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Authentication domain to use with NTML" + }, + "authenticationPreemptive": { + "kind": "parameter", + "displayName": "Authentication Preemptive", + "group": "security", + "label": "producer,security", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If this option is true, camel-http sends preemptive basic authentication to the server." + }, + "authHost": { + "kind": "parameter", + "displayName": "Auth Host", + "group": "security", + "label": "producer,security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Authentication host to use with NTML" + }, + "authMethod": { + "kind": "parameter", + "displayName": "Auth Method", + "group": "security", + "label": "producer,security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Authentication methods allowed to use as a comma separated list of values Basic, Digest or NTLM." + }, + "authMethodPriority": { + "kind": "parameter", + "displayName": "Auth Method Priority", + "group": "security", + "label": "producer,security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "enum": [ + "Basic", + "Digest", + "NTLM" + ], + "deprecated": false, + "secret": false, + "description": "Which authentication method to prioritize to use, either as Basic, Digest or NTLM." + }, + "authPassword": { + "kind": "parameter", + "displayName": "Auth Password", + "group": "security", + "label": "producer,security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "description": "Authentication password" + }, + "authUsername": { + "kind": "parameter", + "displayName": "Auth Username", + "group": "security", + "label": "producer,security", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": true, + "description": "Authentication username" + }, + "sslContextParameters": { + "kind": "parameter", + "displayName": "Ssl Context Parameters", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "org.apache.camel.support.jsse.SSLContextParameters", + "deprecated": false, + "secret": false, + "description": "To configure security using SSLContextParameters. Important: Only one instance of org.apache.camel.util.jsse.SSLContextParameters is supported per HttpComponent. If you need to use 2 or more different instances, you need to define a new HttpComponent per instance you need." + }, + "x509HostnameVerifier": { + "kind": "parameter", + "displayName": "X509 Hostname Verifier", + "group": "security", + "label": "security", + "required": false, + "type": "object", + "javaType": "javax.net.ssl.HostnameVerifier", + "deprecated": false, + "secret": false, + "description": "To use a custom X509HostnameVerifier such as DefaultHostnameVerifier or NoopHostnameVerifier" + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/custom-connector-in/input-route.bak.xml b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/custom-connector-in/input-route.bak.xml new file mode 100644 index 00000000..7c0edc94 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/custom-connector-in/input-route.bak.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/ftps-connector-in/init.ftl b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/ftps-connector-in/init.ftl new file mode 100644 index 00000000..2f7f2ab7 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/ftps-connector-in/init.ftl @@ -0,0 +1,17 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + +[#import "templates:object-commons/common-utils.ftl" as utils] + + + + + [#include "templates:abstract-connector/generate-logging-key.ftl"] + + + + + diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/ftps-connector-out/init.ftl b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/ftps-connector-out/init.ftl new file mode 100644 index 00000000..c5c58f20 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/ftps-connector-out/init.ftl @@ -0,0 +1,16 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + +[#import "templates:object-commons/common-utils.ftl" as utils] + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/customObjectReferences.ftl b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/customObjectReferences.ftl new file mode 100644 index 00000000..259d828d --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/customObjectReferences.ftl @@ -0,0 +1,53 @@ +[#if properties.camel_headerFilterStrategy??] + [#if properties.camel_headerFilterStrategy == "custom"] + [#assign headerFilterStrategyReference = properties.headerFilterStrategyReference] + [#else] + [#assign headerFilterStrategyReference = "headerFilterStrategy"] + [/#if] + [#global properties = properties + {"camel_headerFilterStrategy": "#[=headerFilterStrategyReference]"} ] +[/#if] +[#if properties.camel_cookieStore??] + [#if properties.camel_cookieStore == "custom"] + [#assign cookieStoreReference = properties.cookieStoreReference] + [#else] + [#assign cookieStoreReference = "cookieStore"] + [/#if] + [#global properties = properties + {"camel_cookieStore": "#[=cookieStoreReference]"} ] +[/#if] +[#if properties.camel_clientConnectionManager?? && properties.camel_clientConnectionManager == "custom"] + [#global properties = properties + {"camel_clientConnectionManager": "#[=properties.clientConnectionManagerReference]"} ] +[/#if] +[#if properties.camel_x509HostnameVerifier??] + [#if properties.camel_x509HostnameVerifier == "custom"] + [#assign x509HostnameVerifierReference = properties.x509HostnameVerifierReference] + [#else] + [#assign x509HostnameVerifierReference = "x509HostnameVerifier"] + [/#if] + [#global properties = properties + {"camel_x509HostnameVerifier": "#[=x509HostnameVerifierReference]"} ] +[/#if] +[#if properties.camel_sslContextParameters??] + [#if properties.camel_sslContextParameters == "custom"] + [#assign sslContextParametersReference = properties.sslContextParametersReference] + [#else] + [#assign sslContextParametersReference = "sslContextParameters"] + [/#if] + [#global properties = properties + {"camel_sslContextParameters": "#[=sslContextParametersReference]"} ] +[/#if] +[#if properties.camel_cookieStore?? && properties.camel_cookieStore == "custom"] + [#global properties = properties + {"camel_cookieStore": "#[=properties.cookieStoreReference]"} ] +[/#if] +[#if properties.camel_clientConnectionManager?? && properties.camel_clientConnectionManager == "custom"] + [#global properties = properties + {"camel_clientConnectionManager": "#[=properties.clientConnectionManagerReference]"} ] +[/#if] +[#if properties.camel_httpBinding?? && properties.camel_httpBinding == "custom"] + [#global properties = properties + {"camel_httpBinding": "#[=properties.httpBindingReference]"} ] +[/#if] +[#if properties.camel_httpClientConfigurer?? && properties.camel_httpClientConfigurer == "custom"] + [#global properties = properties + {"camel_httpClientConfigurer": "#[=properties.httpClientConfigurerReference]"} ] +[/#if] +[#if properties.camel_httpConfiguration?? && properties.camel_httpConfiguration == "custom"] + [#global properties = properties + {"camel_httpConfiguration": "#[=properties.httpConfigurationReference]"} ] +[/#if] +[#if properties.camel_httpContext?? && properties.camel_httpContext == "custom"] + [#global properties = properties + {"camel_httpContext": "#[=properties.httpContextReference]"} ] +[/#if] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/customObjects.ftl b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/customObjects.ftl new file mode 100644 index 00000000..e497db81 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/customObjects.ftl @@ -0,0 +1,10 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#if properties.headerFilterStrategy?? && properties.headerFilterStrategy != "custom"] + +[/#if] +[#if properties.x509HostnameVerifier?? && properties.x509HostnameVerifier != "custom"] + +[/#if] +[#if properties.cookieStore?? && properties.cookieStore != "custom"] + +[/#if] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/init.ftl b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/init.ftl new file mode 100644 index 00000000..8bb57551 --- /dev/null +++ b/platform/runtime/core/objects-implementations/connector-implementation/standard-connectors-pack/src/main/resources/ru/entaxy/templates/http-connector-out/init.ftl @@ -0,0 +1,21 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + +[#import "templates:object-commons/common-utils.ftl" as utils] +[#include "customObjectReferences.ftl" ] + + + + + [#if properties.removeServiceHeadersBeforeSending] + + [/#if] + + + + + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/in-flow-pre-route.bak.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/in-flow-pre-route.bak.xml new file mode 100644 index 00000000..b9e36574 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/in-flow-pre-route.bak.xml @@ -0,0 +1,7 @@ + + + + + true + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/in-flow-response.bak.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/in-flow-response.bak.xml new file mode 100644 index 00000000..94c41dbc --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/in-flow-response.bak.xml @@ -0,0 +1,7 @@ + + + + + true + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-connector-selector.bak.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-connector-selector.bak.xml new file mode 100644 index 00000000..68f67c0a --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-connector-selector.bak.xml @@ -0,0 +1,23 @@ + + + + + + connector.type + connector.protocol + connector.classifier + + + *:*:= + + + + false + + false + false + false + + + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-pre-route.bak.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-pre-route.bak.xml new file mode 100644 index 00000000..564ed730 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-pre-route.bak.xml @@ -0,0 +1,7 @@ + + + + + true + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-response.bak.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-response.bak.xml new file mode 100644 index 00000000..68d4d054 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/common-system-profile/out-flow-response.bak.xml @@ -0,0 +1,7 @@ + + + + + true + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/default-route-2/default-route.bak.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/default-route-2/default-route.bak.xml new file mode 100644 index 00000000..ee5831f3 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/default-route-2/default-route.bak.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/LICENSE.txt b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/pom.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/pom.xml new file mode 100644 index 00000000..5f51e3da --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/pom.xml @@ -0,0 +1,41 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + profile-implementation + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations.profile-implementation + profile-runtime-camel-components + bundle + + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: PROFILE :: RUNTIME CAMEL + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: PROFILE :: RUNTIME CAMEL + + + + ru.entaxy.esb.system.component, + ru.entaxy.esb.system.component.util, + ru.entaxy.esb.system.groups.component, + ru.entaxy.esb.system.groups.component.util + + + + + + ru.entaxy.esb.platform.runtime.core + core-support-runtime-legacy + ${project.version} + + + ru.entaxy.esb.platform.runtime.core.objects-implementations.profile-implementation + profile-runtime-legacy-support + ${project.version} + + + org.apache.camel + camel-core + + + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemComponent.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemComponent.java new file mode 100644 index 00000000..8f6a9912 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemComponent.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.component; + +import org.apache.camel.Endpoint; +import org.apache.camel.support.DefaultComponent; + +import java.util.Map; + +public class SystemComponent extends DefaultComponent { + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + SystemEndpoint endpoint = new SystemEndpoint(uri, this); + + endpoint.setSystemName(remaining); + setProperties(endpoint, parameters); + return endpoint; + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemConsumer.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemConsumer.java new file mode 100644 index 00000000..df19f810 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemConsumer.java @@ -0,0 +1,71 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.component; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.support.ScheduledPollConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SystemConsumer extends ScheduledPollConsumer { + + private static final Logger LOG = LoggerFactory.getLogger(SystemConsumer.class); + + private final SystemEndpoint endpoint; + + public SystemConsumer(SystemEndpoint endpoint, Processor processor) { + super(endpoint, processor); + this.endpoint = endpoint; + } + + @Override + protected int poll() throws Exception { + Exchange exchange = endpoint.createExchange(); + + // create a message body + exchange.getIn().setBody(readOptions()); + LOG.info("In SystemConsumer " + exchange.getIn().getBody()); + + try { + // send message to next processor in the route + getProcessor().process(exchange); + return 1; // number of messages polled + } finally { + // log exception if an exception occurred and was not handled + if (exchange.getException() != null) { + getExceptionHandler().handleException( + "Error processing exchange", exchange, + exchange.getException()); + } + } + } + + private String readOptions() { + return "Operation name " + endpoint.getSystemName(); + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemEndpoint.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemEndpoint.java new file mode 100644 index 00000000..f6366b06 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemEndpoint.java @@ -0,0 +1,115 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.component; + +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; + +@UriEndpoint( + scheme = "system", + title = "System", + syntax = "system:systemName", + label = "custom", + producerOnly = true) +public class SystemEndpoint extends DefaultEndpoint { + + @UriPath + @Metadata(required = true) + private String systemName; + @UriParam(label = "producer") + private String connectorProtocol = null; + @UriParam(label = "producer") + private String connectorClassifier = null; + @UriParam(label = "producer") + private String connectorType = null; + @UriParam(label = "producer") + private Boolean connectorMandatory = null; + + public SystemEndpoint() { + } + + public SystemEndpoint(String uri, SystemComponent component) { + super(uri, component); + } + + public Producer createProducer() throws Exception { + return new SystemProducer(this); + } + + public Consumer createConsumer(Processor processor) throws Exception { + return null; + } + + public boolean isSingleton() { + return true; + } + + public String getSystemName() { + return systemName; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + public String getConnectorProtocol() { + return connectorProtocol; + } + + public void setConnectorProtocol(String connectorProtocol) { + this.connectorProtocol = connectorProtocol; + } + + public String getConnectorClassifier() { + return connectorClassifier; + } + + public void setConnectorClassifier(String connectorClassifier) { + this.connectorClassifier = connectorClassifier; + } + + public String getConnectorType() { + return connectorType; + } + + public void setConnectorType(String connectorType) { + this.connectorType = connectorType; + } + + public Boolean isConnectorMandatory() { + return connectorMandatory; + } + + public void setConnectorMandatory(Boolean connectorMandatory) { + this.connectorMandatory = connectorMandatory; + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemProducer.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemProducer.java new file mode 100644 index 00000000..69d01d5f --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/SystemProducer.java @@ -0,0 +1,130 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.component; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.support.DefaultProducer; +import org.apache.commons.lang3.StringUtils; +import org.osgi.framework.FrameworkUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.system.common.exception.ProfileNotFound; +import ru.entaxy.esb.system.registry.systems.profile.SystemCollectorListener; +import ru.entaxy.esb.system.registry.systems.profile.SystemProfile; +import ru.entaxy.platform.base.support.osgi.OSGIUtils; + + +public class SystemProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(SystemProducer.class); + private final SystemEndpoint endpoint; + + private SystemCollectorListener systemCollectorListener; + + public SystemProducer(SystemEndpoint endpoint) { + super(endpoint); + this.endpoint = endpoint; + } + + public void process(Exchange exchange) throws Exception { + LOG.debug("In SystemProducer " + exchange.getIn().getBody()); + + // get System Profile from systemRegistry endpoint.getSystemName() + SystemProfile systemProfile = null; + + systemProfile = getSystemProfile(endpoint.getSystemName()); + + setPreferredConnector(exchange); + setConnectorMandatory(exchange); + + LOG.debug("Called system profile " + (systemProfile != null ? systemProfile.getSystemName() : "NULL")); + + systemProfile.send(exchange); + + } + + public SystemProfile getSystemProfile(String nameSystem) throws ProfileNotFound { + systemCollectorListener = getSystemProfileNamedListener(); + LOG.debug("Registry SystemProfile {}; systems count {}", nameSystem, + systemCollectorListener.getReferenceNames().size()); + SystemProfile systemProfile = null; + if (systemCollectorListener.isRegistered(nameSystem)) { + systemProfile = (SystemProfile) systemCollectorListener.getReference(nameSystem); + } else { + throw new ProfileNotFound("Profile for system " + nameSystem + " not found"); + } + return systemProfile; + } + + public SystemCollectorListener getSystemProfileNamedListener() { + if (systemCollectorListener == null) { + systemCollectorListener = (SystemCollectorListener) OSGIUtils.getService( + FrameworkUtil.getBundle(SystemProducer.class).getBundleContext(), + SystemCollectorListener.class); + } + return systemCollectorListener; + } + + public void setPreferredConnector(Exchange exchange) { + if (!StringUtils.isEmpty(endpoint.getConnectorProtocol()) + || !StringUtils.isEmpty(endpoint.getConnectorClassifier()) || + !StringUtils.isEmpty(endpoint.getConnectorType())) { + List preferredConnectorList = new ArrayList<>(); + if (!StringUtils.isEmpty(endpoint.getConnectorProtocol())) { + preferredConnectorList.add("\"protocol\":\"" + endpoint.getConnectorProtocol() + "\""); + } + if (!StringUtils.isEmpty(endpoint.getConnectorClassifier())) { + preferredConnectorList.add("\"classifier\":\"" + endpoint.getConnectorClassifier() + "\""); + } + if (!StringUtils.isEmpty(endpoint.getConnectorType())) { + preferredConnectorList.add("\"type\":\"" + endpoint.getConnectorType() + "\""); + } + String jsonPreferredConnector = "{" + joinByComma(preferredConnectorList) + "}"; + exchange.getMessage().getHeaders().put("NTX_preferred_connector", jsonPreferredConnector); + } + } + + public void setConnectorMandatory(Exchange exchange) { + if (endpoint.isConnectorMandatory() != null) + exchange.getMessage().getHeaders().put("NTX_connector_preferred_as_mandatory", + endpoint.isConnectorMandatory()); + } + + private String joinByComma(List preferredConnectorList) { + StringBuilder summary = new StringBuilder(); + for (int i = 0; i < preferredConnectorList.size(); i++) { + summary.append(preferredConnectorList.get(i)); + if (i < preferredConnectorList.size() - 1) { + summary.append(","); + } + } + return summary.toString(); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/util/SystemConstants.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/util/SystemConstants.java new file mode 100644 index 00000000..6c270e69 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/component/util/SystemConstants.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.component.util; + +public class SystemConstants { + + public static final String PARAMETER_PREFERRED_CONNECTOR = "preferredConnector"; + + private SystemConstants() { + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupComponent.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupComponent.java new file mode 100644 index 00000000..180d7b08 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupComponent.java @@ -0,0 +1,44 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.component; + +import org.apache.camel.Endpoint; +import org.apache.camel.support.DefaultComponent; + +import java.util.Map; + +public class SystemGroupComponent extends DefaultComponent { + + @Override + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + SystemGroupEndpoint endpoint = new SystemGroupEndpoint(uri, this); + + endpoint.setSystemName(remaining); + setProperties(endpoint, parameters); + return endpoint; + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupConsumer.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupConsumer.java new file mode 100644 index 00000000..fd1cae2a --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupConsumer.java @@ -0,0 +1,71 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.component; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; +import org.apache.camel.support.ScheduledPollConsumer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class SystemGroupConsumer extends ScheduledPollConsumer { + + private static final Logger LOG = LoggerFactory.getLogger(SystemGroupConsumer.class); + + private final SystemGroupEndpoint endpoint; + + public SystemGroupConsumer(SystemGroupEndpoint endpoint, Processor processor) { + super(endpoint, processor); + this.endpoint = endpoint; + } + + @Override + protected int poll() throws Exception { + Exchange exchange = endpoint.createExchange(); + + // create a message body + exchange.getIn().setBody(readOptions()); + LOG.info("In SystemGroupConsumer ++++ " + exchange.getIn().getBody()); + + try { + // send message to next processor in the route + getProcessor().process(exchange); + return 1; // number of messages polled + } finally { + // log exception if an exception occurred and was not handled + if (exchange.getException() != null) { + getExceptionHandler().handleException( + "Error processing exchange", exchange, + exchange.getException()); + } + } + } + + private String readOptions() { + return "Operation name " + endpoint.getSystemName(); + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupEndpoint.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupEndpoint.java new file mode 100644 index 00000000..cc486c1b --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupEndpoint.java @@ -0,0 +1,86 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.component; + +import org.apache.camel.Consumer; +import org.apache.camel.Processor; +import org.apache.camel.Producer; +import org.apache.camel.spi.Metadata; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.spi.UriPath; +import org.apache.camel.support.DefaultEndpoint; + +@UriEndpoint( + scheme = "system-group", + title = "System", + syntax = "system-group:systemName", + label = "custom", + producerOnly = true) +public class SystemGroupEndpoint extends DefaultEndpoint { + + @UriPath + @Metadata(required = true) + private String systemName; + @UriParam + private String preferredConnector = null; + + public SystemGroupEndpoint() { + } + + public SystemGroupEndpoint(String uri, SystemGroupComponent component) { + super(uri, component); + } + + public Producer createProducer() throws Exception { + return new SystemGroupProducer(this); + } + + public Consumer createConsumer(Processor processor) throws Exception { + return null; + } + + public boolean isSingleton() { + return true; + } + + public String getSystemName() { + return systemName; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + public String getPreferredConnector() { + return preferredConnector; + } + + public void setPreferredConnector(String preferredConnector) { + this.preferredConnector = preferredConnector; + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupProducer.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupProducer.java new file mode 100644 index 00000000..fee39669 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/SystemGroupProducer.java @@ -0,0 +1,88 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.component; + +import org.apache.camel.Exchange; +import org.apache.camel.support.DefaultProducer; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import ru.entaxy.esb.system.common.exception.ProfileNotFound; +import ru.entaxy.esb.system.groups.registry.system.groups.profile.SystemGroupCollectorListener; +import ru.entaxy.esb.system.groups.registry.system.groups.profile.SystemGroupProfile; + + +public class SystemGroupProducer extends DefaultProducer { + + private static final Logger LOG = LoggerFactory.getLogger(SystemGroupProducer.class); + private final SystemGroupEndpoint endpoint; + + private SystemGroupCollectorListener systemGroupCollectorListener; + + public SystemGroupProducer(SystemGroupEndpoint endpoint) { + super(endpoint); + this.endpoint = endpoint; + } + + public void process(Exchange exchange) throws Exception { + LOG.debug("In SystemGroupProducer " + exchange.getIn().getBody()); + + //get System Group Profile from systemRegistry endpoint.getSystemName() + SystemGroupProfile systemGroupProfile = null; + + systemGroupProfile = getSystemGroupProfile(endpoint.getSystemName()); + + LOG.debug("Called system group profile " + (systemGroupProfile != null ? systemGroupProfile.getProfileName() : "NULL")); + + systemGroupProfile.send(exchange); + } + + public SystemGroupProfile getSystemGroupProfile(String nameSystem) throws ProfileNotFound { + systemGroupCollectorListener = getSystemGroupCollectorListener(); + LOG.info("Registry SystemGroupProfile {}; services count {}", nameSystem, systemGroupCollectorListener.getReferenceNames().size()); + SystemGroupProfile systemGroupProfile = null; + if (systemGroupCollectorListener.isRegistered(nameSystem)) { + systemGroupProfile = (SystemGroupProfile) systemGroupCollectorListener.getReference(nameSystem); + } else { + throw new ProfileNotFound("Profile for group system " + nameSystem + " not found"); + } + return systemGroupProfile; + } + + + public SystemGroupCollectorListener getSystemGroupCollectorListener() { + if (systemGroupCollectorListener == null) { + BundleContext bundleContext = FrameworkUtil.getBundle(SystemGroupProducer.class).getBundleContext(); + ServiceReference systemGroupCollectorListenerServiceReference = + bundleContext.getServiceReference(SystemGroupCollectorListener.class); + systemGroupCollectorListener = bundleContext.getService(systemGroupCollectorListenerServiceReference); + } + return systemGroupCollectorListener; + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/util/SystemGroupConstants.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/util/SystemGroupConstants.java new file mode 100644 index 00000000..195b5146 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/java/ru/entaxy/esb/system/groups/component/util/SystemGroupConstants.java @@ -0,0 +1,34 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-component + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.component.util; + +public class SystemGroupConstants { + + public static final String PARAMETER_PREFERRED_CONNECTOR = "preferredConnector"; + + private SystemGroupConstants() { + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/resources/META-INF/services/org/apache/camel/component/system b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/resources/META-INF/services/org/apache/camel/component/system new file mode 100644 index 00000000..6c2e88c8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/resources/META-INF/services/org/apache/camel/component/system @@ -0,0 +1 @@ +class=ru.entaxy.esb.system.component.SystemComponent diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/resources/META-INF/services/org/apache/camel/component/system-group b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/resources/META-INF/services/org/apache/camel/component/system-group new file mode 100644 index 00000000..36f402c5 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-camel-components/src/main/resources/META-INF/services/org/apache/camel/component/system-group @@ -0,0 +1 @@ +class=ru.entaxy.esb.system.groups.component.SystemGroupComponent diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/LICENSE.txt b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/pom.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/pom.xml new file mode 100644 index 00000000..77166111 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + profile-implementation + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations.profile-implementation + profile-runtime-legacy-support + bundle + + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: PROFILE :: RUNTIME LEGACY + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: PROFILE :: RUNTIME LEGACY + + + + ru.entaxy.esb.system.profile.commons, + ru.entaxy.esb.system.profile.commons.connectors, + ru.entaxy.esb.system.profile.commons.connectors.in, + ru.entaxy.esb.system.profile.commons.connectors.out, + ru.entaxy.esb.system.profile.commons.profile_output, + ru.entaxy.esb.system.registry.systems.profile, + ru.entaxy.esb.system.registry.systems.profile.collector, + ru.entaxy.esb.system.registry.systems.profile.impl.defaults, + ru.entaxy.esb.system.groups.registry.system.groups.profile, + ru.entaxy.esb.system.groups.registry.system.groups.profile.collector, + ru.entaxy.esb.system.groups.registry.system.groups.profile.impl.defaults + + + + + + org.apache.camel + camel-api + + + ru.entaxy.esb.platform.runtime.core + core-support-runtime-legacy + ${project.version} + + + + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/SystemGroupCollectorListener.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/SystemGroupCollectorListener.java new file mode 100644 index 00000000..822fcbde --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/SystemGroupCollectorListener.java @@ -0,0 +1,31 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-profile-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.registry.system.groups.profile; + +import ru.entaxy.platform.base.support.osgi.service.NamedReferenceListener; + +public interface SystemGroupCollectorListener extends NamedReferenceListener { +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/SystemGroupProfile.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/SystemGroupProfile.java new file mode 100644 index 00000000..c88d2c4a --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/SystemGroupProfile.java @@ -0,0 +1,36 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-profile-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.registry.system.groups.profile; + +import ru.entaxy.esb.system.profile.commons.Profile; + +public interface SystemGroupProfile extends Profile { + + String getProfileName(); + + void send(Object request); + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/collector/SystemGroupProfileNamedListener.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/collector/SystemGroupProfileNamedListener.java new file mode 100644 index 00000000..a2aedc0c --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/collector/SystemGroupProfileNamedListener.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-profile-collector + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.registry.system.groups.profile.collector; + +import ru.entaxy.esb.system.groups.registry.system.groups.profile.SystemGroupCollectorListener; +import ru.entaxy.esb.system.groups.registry.system.groups.profile.SystemGroupProfile; +import ru.entaxy.platform.base.support.osgi.service.CommonNamedReferenceListener; + +public class SystemGroupProfileNamedListener extends CommonNamedReferenceListener + implements SystemGroupCollectorListener { + + @Override + protected String getObjectName(SystemGroupProfile systemGroupProfile) { + return systemGroupProfile.getProfileName(); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/impl/defaults/DefaultSystemGroupProfile.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/impl/defaults/DefaultSystemGroupProfile.java new file mode 100644 index 00000000..4f6a3700 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/groups/registry/system/groups/profile/impl/defaults/DefaultSystemGroupProfile.java @@ -0,0 +1,104 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-group-profile-impl-default + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.groups.registry.system.groups.profile.impl.defaults; + +import org.apache.camel.CamelContext; +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.jms.JmsComponent; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import ru.entaxy.esb.system.groups.registry.system.groups.profile.SystemGroupProfile; +import ru.entaxy.esb.system.profile.commons.CommonProfile; +import ru.entaxy.esb.system.registry.systems.profile.SystemCollectorListener; + +import javax.jms.ConnectionFactory; + +public class DefaultSystemGroupProfile extends CommonProfile implements SystemGroupProfile { + + private static final Log LOG = LogFactory.getLog(DefaultSystemGroupProfile.class); + private static final String NAME_JMS_COMPONENT = "jms"; + + private String systemGroupName = "system"; + private String profileName = "default"; + private String destination = "default"; + private final String dlq = "DLQ"; + private ConnectionFactory jmsConnectionFactory; + + private SystemCollectorListener systemCollectorListener; + + public DefaultSystemGroupProfile() { + } + + @Override + public String getProfileName() { + return profileName; + } + + @Override + protected void doSend(Object request) { + LOG.info("Send request " + request + "in " + destination); + Exchange exchange = (Exchange) request; + + ProducerTemplate template = exchange.getContext().createProducerTemplate(); + addJmsComponent(exchange.getContext()); + + Message message = exchange.getMessage(); + message.setHeader("NTX_SystemId", systemGroupName); + message.setHeader("ExchangePattern", "InOnly"); + + template.send(destination, exchange); + } + + private void addJmsComponent(CamelContext context) { + if (!context.getComponentNames().contains(NAME_JMS_COMPONENT)) + addJmsComponent(context, NAME_JMS_COMPONENT); + } + + private void addJmsComponent(CamelContext context, String componentName) { + JmsComponent component = new JmsComponent(context); + component.setConnectionFactory(jmsConnectionFactory); + + context.addComponent(componentName, component); + } + + public void setSystemGroupName(String systemGroupName) { + this.systemGroupName = systemGroupName; + } + + public void setProfileName(String profileName) { + this.profileName = profileName; + } + + public void setDestination(String destination) { + this.destination = destination; + } + + public void setJmsConnectionFactory(ConnectionFactory jmsConnectionFactory) { + this.jmsConnectionFactory = jmsConnectionFactory; + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/CommonProfile.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/CommonProfile.java new file mode 100644 index 00000000..f9dca8ac --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/CommonProfile.java @@ -0,0 +1,90 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons; + +import ru.entaxy.esb.system.profile.commons.profile_output.ProfileOutput; + +import java.util.Objects; + +public abstract class CommonProfile implements Profile { + + protected String systemName = "system"; + protected ProfileOutput profileOutput; + protected InConnectorCollector inConnectorCollector; + + @Override + public void send(Object request) { + doSend(request); + } + + protected abstract void doSend(Object request); + + @Override + public String getSystemName() { + return systemName; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + @Override + public ProfileOutput getProfileOutput() { + return profileOutput; + } + + public void setProfileOutput(ProfileOutput profileOutput) { + this.profileOutput = profileOutput; + } + + public InConnectorCollector getInConnectorCollector() { + return inConnectorCollector; + } + + public void setInConnectorCollector(InConnectorCollector inConnectorCollector) { + this.inConnectorCollector = inConnectorCollector; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CommonProfile that = (CommonProfile) o; + return Objects.equals(systemName, that.systemName); + } + + @Override + public int hashCode() { + return Objects.hash(systemName); + } + + @Override + public String toString() { + return "CommonProfile{" + + "systemName='" + systemName + '\'' + + '}'; + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/ConnectorRegistry.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/ConnectorRegistry.java new file mode 100644 index 00000000..8e53e2fa --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/ConnectorRegistry.java @@ -0,0 +1,60 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons; + +import org.apache.camel.Exchange; +import org.apache.camel.Header; + +import ru.entaxy.esb.system.common.exception.ConnectorNotFound; +import ru.entaxy.esb.system.profile.commons.connectors.Connector; +import ru.entaxy.platform.base.support.osgi.service.CommonNamedReferenceListener; + +public class ConnectorRegistry extends CommonNamedReferenceListener { + + public String getParam(String systemName, String paramName) { + Connector connector = getReference(systemName); + if (connector != null) { + return connector.getParam(paramName); + } else { + throw new ConnectorNotFound("Connector for " + systemName + " not found"); + } + } + + public void send(@Header("X-SystemName") String systemName, Exchange exchange) { + Connector connector = getReference(systemName); + if (connector != null) { + connector.send(exchange); + } else { + throw new ConnectorNotFound("Connector for " + systemName + " not found"); + } + } + + @Override + protected String getObjectName(Connector Connector) { + return Connector.getSystemName(); + } +} + diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/InConnectorCollector.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/InConnectorCollector.java new file mode 100644 index 00000000..4de28bd6 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/InConnectorCollector.java @@ -0,0 +1,37 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons; + +import ru.entaxy.esb.system.profile.commons.connectors.in.InConnector; +import ru.entaxy.platform.base.support.osgi.service.CommonNamedReferenceListener; + +public class InConnectorCollector extends CommonNamedReferenceListener { + + @Override + protected String getObjectName(InConnector inConnector) { + return inConnector == null ? null : inConnector.getEndpointName(); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/Profile.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/Profile.java new file mode 100644 index 00000000..d0b0a476 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/Profile.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons; + +import ru.entaxy.esb.system.profile.commons.profile_output.ProfileOutput; + +public interface Profile { + + ProfileOutput getProfileOutput(); + + String getSystemName(); + + InConnectorCollector getInConnectorCollector(); + + void send(Object request); +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/CommonConnector.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/CommonConnector.java new file mode 100644 index 00000000..5bd431fa --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/CommonConnector.java @@ -0,0 +1,79 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.connectors; + +import ru.entaxy.esb.system.profile.commons.Profile; + +import java.util.Map; + +public abstract class CommonConnector implements Connector { + protected String endpointName; + protected Profile profile; + protected String systemName; + protected Map params; + + public void setEndpointName(String endpointName) { + this.endpointName = endpointName; + } + + public void setProfile(Profile profile) { + this.profile = profile; + } + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + public void setParams(Map params) { + this.params = params; + } + + @Override + public String getEndpointName() { + return endpointName; + } + + @Override + public Profile getProfile() { + return profile; + } + + @Override + public String getSystemName() { + return systemName; + } + + @Override + public Map getParams() { + return params; + } + + @Override + public String getParam(String paramName) { + return params.get(paramName); + } + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/Connector.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/Connector.java new file mode 100644 index 00000000..f0527aba --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/Connector.java @@ -0,0 +1,53 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.connectors; + +import org.apache.camel.Exchange; +import ru.entaxy.esb.system.profile.commons.Profile; + +import java.util.Map; + +public interface Connector { + + public static final String HEADERS_START = "NTX_Connector_"; + public static final String ROLE = "role"; + public static final String TYPE = "type"; + public static final String SUBTYPE = "subtype"; + + String getEndpointName(); + + String getEndpointType(); + + Profile getProfile(); + + String getSystemName(); + + Map getParams(); + + String getParam(String paramName); + + void send(Exchange exchange); +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/in/DirectVMInConnectorImpl.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/in/DirectVMInConnectorImpl.java new file mode 100644 index 00000000..cb27dd82 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/in/DirectVMInConnectorImpl.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.connectors.in; + +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import ru.entaxy.esb.system.profile.commons.connectors.CommonConnector; + +public class DirectVMInConnectorImpl extends CommonConnector implements InConnector { + + @Override + public String getEndpointType() { + return endpointType; + } + + @Override + public void send(Exchange exchange) { + ProducerTemplate template = exchange.getContext().createProducerTemplate(); + exchange.getIn().setHeader(HEADERS_START + ROLE, getParam(ROLE)); + exchange.getIn().setHeader(HEADERS_START + TYPE, getParam(TYPE)); + exchange.getIn().setHeader(HEADERS_START + SUBTYPE, getParam(SUBTYPE)); + template.send("direct-vm:" + endpointName + "-" + endpointType + "-connector-" + systemName + + "?block=true&timeout=60000", exchange); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/in/InConnector.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/in/InConnector.java new file mode 100644 index 00000000..845b035e --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/in/InConnector.java @@ -0,0 +1,33 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.connectors.in; + +import ru.entaxy.esb.system.profile.commons.connectors.Connector; + +public interface InConnector extends Connector { + + String endpointType = "in"; +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/out/DirectVMOutConnectorImpl.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/out/DirectVMOutConnectorImpl.java new file mode 100644 index 00000000..1bcdf299 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/out/DirectVMOutConnectorImpl.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.connectors.out; + +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import ru.entaxy.esb.system.profile.commons.connectors.CommonConnector; + +public class DirectVMOutConnectorImpl extends CommonConnector implements OutConnector { + + @Override + public String getEndpointType() { + return endpointType; + } + + @Override + public void send(Exchange exchange) { + ProducerTemplate template = exchange.getContext().createProducerTemplate(); + template.send("direct-vm:" + endpointName + "-" + + endpointType + "-connector-" + systemName + "?block=true&timeout=60000", exchange); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/out/OutConnector.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/out/OutConnector.java new file mode 100644 index 00000000..bdf512e7 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/connectors/out/OutConnector.java @@ -0,0 +1,33 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.connectors.out; + +import ru.entaxy.esb.system.profile.commons.connectors.Connector; + +public interface OutConnector extends Connector { + + String endpointType = "out"; +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/profile_output/ProfileOutput.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/profile_output/ProfileOutput.java new file mode 100644 index 00000000..a9b00676 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/profile_output/ProfileOutput.java @@ -0,0 +1,48 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.profile_output; + +import org.apache.camel.Exchange; +import org.apache.camel.Header; +import ru.entaxy.esb.system.profile.commons.connectors.out.OutConnector; + +import java.util.List; + +import static ru.entaxy.esb.system.profile.commons.connectors.Connector.*; + +public interface ProfileOutput { + OutConnector getOutConnector(String endpointName, String role, String type, String subtype); + + void send(Exchange exchange); + + void sendTo(@Header("EndpointName") String endpointName, + @Header(HEADERS_START + ROLE) String role, + @Header(HEADERS_START + TYPE) String type, + @Header(HEADERS_START + SUBTYPE) String subtype, + Exchange exchange); + + public List getReferenceNames(); +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/profile_output/ProfileOutputImpl.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/profile_output/ProfileOutputImpl.java new file mode 100644 index 00000000..3166e6a2 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/profile/commons/profile_output/ProfileOutputImpl.java @@ -0,0 +1,148 @@ +/*- + * ~~~~~~licensing~~~~~~ + * profile-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.profile.commons.profile_output; + +import static ru.entaxy.esb.system.profile.commons.connectors.Connector.HEADERS_START; +import static ru.entaxy.esb.system.profile.commons.connectors.Connector.ROLE; +import static ru.entaxy.esb.system.profile.commons.connectors.Connector.SUBTYPE; +import static ru.entaxy.esb.system.profile.commons.connectors.Connector.TYPE; + +import java.util.concurrent.CountDownLatch; + +import org.apache.camel.Exchange; +import org.apache.camel.Header; +import org.apache.camel.ProducerTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.system.common.exception.ConnectorNotFound; +import ru.entaxy.esb.system.profile.commons.connectors.out.OutConnector; +import ru.entaxy.platform.base.support.osgi.service.CommonNamedReferenceListener; + +public class ProfileOutputImpl extends CommonNamedReferenceListener implements ProfileOutput { + + private static final Logger log = LoggerFactory.getLogger(ProfileOutputImpl.class); + + protected String systemName; + + public void setSystemName(String systemName) { + this.systemName = systemName; + } + + @Override + public OutConnector getOutConnector(String endpointName, String role, String type, String subtype) { + for (OutConnector outConnector : registeredReferences.values()) { + if ((role == null || role.equals(outConnector.getParam(ROLE))) && + type != null && type.equals(outConnector.getParam(TYPE)) && + subtype != null && subtype.equals(outConnector.getParam(SUBTYPE))) { + return outConnector; + } else if ((role == null || role.equals(outConnector.getParam(ROLE))) && + type != null && type.equals(outConnector.getParam(TYPE))) { + return outConnector; + } else if (role != null && role.equals(outConnector.getParam(ROLE))) { + return outConnector; + } + } + if (endpointName == null || registeredReferences.get(endpointName) == null) { + for (OutConnector outConnector : registeredReferences.values()) { + return outConnector; + } + } + return registeredReferences.get(endpointName); + } + + @Override + public void send(Exchange exchange) { + /* + * !!! WE ARE NOT SURE THE SENDING FROM PROCESSOR (COMPONENT) IS ALLOWED IN CAMEL !!! + * but we managed to do this + * + * we need another Thread to execute because when sending + * from system to itself the execution stops in waiting forever + * due to existing running ReactiveExecutor will be found for this thread + * and the task will be placed in it's queue while being in + * execution of the previous task from another Workers's queue + * of the same ReactiveExecutor + * + * Example (without separate thread): + * + * profile_s1 (ExtendedCamelContext_1 -> ReactiveExecutor_1) + * -> task (we're in it now!) -> [switch to ExtendedCamelContext_2] producer (vmdirect) + * -> ExtendedCamelContext_2 (with ReactiveExecutor_2) (route_s1) + * -> consumer (profile_s1) + * -> task { + * Who will execute? Let's check if there's already a ReactiveExecutor !!for current Thread!! + * in target context. If no, our executor will be used. + * Oh! We've found ReactiveExecutor_1, it will execute. + * } -> enqueue (ReactiveExecutor_1) + * -> (execution is still in ExtendedCamelContext_2 - route_s1) + * -> wait for task to be executed. + * + * Result: being in previous (current) task we're waiting for the next task + * in the same ReactiveExecutor's queue to be executed. + * This will never happen. + * + */ + CountDownLatch latch = new CountDownLatch(1); + Thread exec = new Thread(new Runnable() { + + @Override + public void run() { + ProducerTemplate template = exchange.getContext().createProducerTemplate(); + template.send("direct-vm:profile-" + systemName + "-enter-point?block=true&timeout=60000", exchange); + latch.countDown(); + } + }); + exec.setContextClassLoader(Thread.currentThread().getContextClassLoader()); + exec.start(); + try { + // we have to wait the thread to be executed + // because we're calling synchronously + latch.await(); + } catch (InterruptedException e) { + // e.printStackTrace(); + log.error("Error awaiting latch", e); + } + } + + @Override + public void sendTo(@Header("ENTAXY_EndpointName") String endpointName, + @Header(HEADERS_START + ROLE) String role, + @Header(HEADERS_START + TYPE) String type, + @Header(HEADERS_START + SUBTYPE) String subtype, + Exchange exchange) { + try { + getOutConnector(endpointName, role, type, subtype).send(exchange); + } catch (NullPointerException ex) { + throw new ConnectorNotFound("Out connector for " + systemName + " not found"); + } + } + + @Override + protected String getObjectName(OutConnector outConnector) { + return outConnector == null ? null : outConnector.getEndpointName(); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/SystemCollectorListener.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/SystemCollectorListener.java new file mode 100644 index 00000000..7d5563a0 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/SystemCollectorListener.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-profile-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.registry.systems.profile; + +import ru.entaxy.platform.base.support.osgi.service.NamedReferenceListener; + +public interface SystemCollectorListener extends NamedReferenceListener { + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/SystemProfile.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/SystemProfile.java new file mode 100644 index 00000000..408dd27d --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/SystemProfile.java @@ -0,0 +1,32 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-profile-api + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.registry.systems.profile; + +import ru.entaxy.esb.system.profile.commons.Profile; + +public interface SystemProfile extends Profile { + +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/collector/SystemProfileNamedListener.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/collector/SystemProfileNamedListener.java new file mode 100644 index 00000000..153c5d2a --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/collector/SystemProfileNamedListener.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-profile-collector + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.registry.systems.profile.collector; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.istack.NotNull; + +import ru.entaxy.esb.system.registry.systems.profile.SystemCollectorListener; +import ru.entaxy.esb.system.registry.systems.profile.SystemProfile; +import ru.entaxy.platform.base.support.osgi.service.CommonNamedReferenceListener; + +public class SystemProfileNamedListener extends CommonNamedReferenceListener + implements SystemCollectorListener { + protected static final Logger log = LoggerFactory.getLogger(SystemProfileNamedListener.class); + + @Override + protected String getObjectName(@NotNull SystemProfile systemProfile) { + return systemProfile.getSystemName(); + } + + private SystemProfile getSystemProfile(String id) { + return registeredReferences.get(id); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/impl/defaults/DefaultSystemProfile.java b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/impl/defaults/DefaultSystemProfile.java new file mode 100644 index 00000000..ea11e295 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/java/ru/entaxy/esb/system/registry/systems/profile/impl/defaults/DefaultSystemProfile.java @@ -0,0 +1,45 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-profile-impl-default + * ========== + * 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~~~~~~ + */ +package ru.entaxy.esb.system.registry.systems.profile.impl.defaults; + +import org.apache.camel.Exchange; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import ru.entaxy.esb.system.profile.commons.CommonProfile; +import ru.entaxy.esb.system.registry.systems.profile.SystemProfile; + +public class DefaultSystemProfile extends CommonProfile implements SystemProfile { + + private static final Log LOG = LogFactory.getLog(DefaultSystemProfile.class); + + public DefaultSystemProfile() { + } + + @Override + protected void doSend(Object request) { + profileOutput.send((Exchange) request); + } +} diff --git a/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/resources/OSGI-INF/blueprint/blueprint.xml new file mode 100644 index 00000000..5a1c7c40 --- /dev/null +++ b/platform/runtime/core/objects-implementations/profile-implementation/profile-runtime-legacy-support/src/main/resources/OSGI-INF/blueprint/blueprint.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/repository-implementation/LICENSE.txt b/platform/runtime/core/objects-implementations/repository-implementation/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/repository-implementation/pom.xml b/platform/runtime/core/objects-implementations/repository-implementation/pom.xml new file mode 100644 index 00000000..02dd1c6b --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/pom.xml @@ -0,0 +1,16 @@ + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core + objects-implementations + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + repository-implementation + pom + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATION :: REPOSITORY + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATION :: REPOSITORY + + repository-producing + + diff --git a/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/LICENSE.txt b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/pom.xml b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/pom.xml new file mode 100644 index 00000000..19db773f --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + repository-implementation + 1.10.0 + + repository-producing + ru.entaxy.esb.platform.runtime.core.objects-implementations.repository-implementation + bundle + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATION :: REPOSITORY :: PRODUCING + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATION :: REPOSITORY :: PRODUCING + + + + org.apache.felix + maven-bundle-plugin + true + + + true + true + true + + + + + + diff --git a/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/extensions/objectproducer/producer/config.json b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/extensions/objectproducer/producer/config.json new file mode 100644 index 00000000..1e9c3c05 --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/extensions/objectproducer/producer/config.json @@ -0,0 +1,3 @@ +{ + "supportedTypes": ["entaxy.runtime.repository"] +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/factory/artifact-repository.json b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/factory/artifact-repository.json new file mode 100644 index 00000000..135d235c --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/factory/artifact-repository.json @@ -0,0 +1,135 @@ +{ + "factory": { + "id": "artifact-repository", + "type": "entaxy.runtime.repository", + "description": "Factory artifact-repository of entaxy.runtime.repository. For more details see Entaxy docs", + "isAbstract": false + }, + "entaxy.runtime.repository": { + }, + "fields": { + "repo_name": { + "displayName": "Name", + "type": "String", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${objectId}", + "lazy": false + } + } + }, + "repo_location": { + "displayName": "Location", + "description": "Path to repository directory. If empty repository created at {Entaxy Home}/data/cave/repository/{Object Id}. For more details see Entaxy docs", + "type": "String" + }, + "repo_proxy": { + "displayName": "Proxy", + "description": "Enable to use remote repositories. For more details see Entaxy docs", + "type": "Boolean", + "group": "remotes", + "required": true, + "defaultValue": false + }, + "repo_mirror": { + "displayName": "Mirror", + "description": "Enable storing a copy of the artifact in the local repository when using a proxy. Required when downloading artifacts from remote repositories. Not required for uploading artifacts to a remote repository. For more details see Entaxy docs", + "type": "Boolean", + "group": "remotes" + }, + "repo_remotes": { + "displayName": "Remotes", + "description": "Remote repository address. For more details see Entaxy docs", + "type": "String", + "group": "remotes" + }, + "repo_readOnly": { + "displayName": "Read Only", + "description": "Activates read-only mode. For more details see Entaxy docs", + "type": "Boolean", + "required": true, + "defaultValue": false + }, + "repo_copyOnChange": { + "displayName": "Copy On Change", + "isHidden": true, + "type": "Boolean" + }, + "repo_username": { + "description": "Specifies the username used to authenticate when accessing to remote repository. For more details see Entaxy docs", + "displayName": "Username", + "type": "String", + "group": "remotes" + }, + "repo_password": { + "description": "Specifies the password associated with username for authentication when accessing to remote repository. For more details see Entaxy docs", + "displayName": "Password", + "type": "password", + "group": "remotes" + }, + "repo_snapshots": { + "description": "Determines whether this repository should be used for downloading snapshot artifacts. For more details see Entaxy docs", + "displayName": "Snapshots", + "type": "Boolean" + }, + "repo_enabled": { + "displayName": "Enabled", + "type": "Boolean", + "required": true, + "isHidden": true, + "defaultValue": true + }, + "repo_remoteHostSuffix": { + "description": "Specifies the suffix appended to the base URL of the remote repository, forming the full access URL (e.g., if the base URL is https://nexus.entaxy.ru, and the the suffix is /nexus/, the full URL will become https://nexus.entaxy.ru/nexus/). For more details see Entaxy docs", + "displayName": "Remote Host Suffix", + "type": "String", + "group": "remotes" + }, + "repo_system": { + "displayName": "System", + "type": "Boolean", + "required": true, + "isHidden": true, + "defaultValue": false + + }, + "repo_lookupEnabled": { + "displayName": "Lookup Enabled", + "description": "Add the repository to the list of repositories to search for artifacts (org.ops4j.pax.url.mvn.repositories). For more details see Entaxy docs", + "type": "Boolean", + "required": true, + "defaultValue": true + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "repo_name": {}, + "repo_location": {}, + "repo_proxy": {}, + "repo_mirror": {}, + "repo_remotes": {}, + "repo_readOnly": {}, + "repo_copyOnChange": {}, + "repo_username": {}, + "repo_password": {}, + "repo_snapshots": {}, + "repo_enabled": {}, + "repo_remoteHostSuffix": {}, + "repo_system": {}, + "repo_lookupEnabled": {} + }, + "config": { + "configurable": true, + "fieldsConfigurableByDefault": true, + "configurableFields": { + "includePatterns": ["repo_*"], + "excludeNames": ["##publish"] + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/templates/artifact-repository/init.ftl b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/templates/artifact-repository/init.ftl new file mode 100644 index 00000000..61f7f3ca --- /dev/null +++ b/platform/runtime/core/objects-implementations/repository-implementation/repository-producing/src/main/resources/ru/entaxy/templates/artifact-repository/init.ftl @@ -0,0 +1,24 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + +[#import "templates:object-commons/common-utils.ftl" as utils] + + + [=utils.createBeanProperties(properties, "repo_", true, ["##publish"])] + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/redeliveryPolicy-originalFromCamel.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/redeliveryPolicy-originalFromCamel.json new file mode 100644 index 00000000..38aa239d --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/redeliveryPolicy-originalFromCamel.json @@ -0,0 +1,41 @@ +{ + "component": { + "kind": "model", + "name": "redeliveryPolicy", + "title": "Redelivery Policy", + "description": "To configure re-delivery for error handling", + "deprecated": false, + "label": "configuration", + "javaType": "org.apache.camel.model.RedeliveryPolicyDefinition", + "artifactId": "camel-core-engine", + "input": false, + "output": false + }, + "componentProperties": {}, + "properties": { + "maximumRedeliveries": { "kind": "attribute", "displayName": "Maximum Redeliveries", "required": false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false, "secret": false, "description": "Sets the maximum redeliveries x = redeliver at most x times 0 = no redeliveries -1 = redeliver forever" }, + "redeliveryDelay": { "kind": "attribute", "displayName": "Redelivery Delay", "required": false, "type": "duration", "javaType": "java.lang.String", "deprecated": false, "secret": false, "description": "Sets the initial redelivery delay" }, + "asyncDelayedRedelivery": { "kind": "attribute", "displayName": "Async Delayed Redelivery", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Allow synchronous delayed redelivery. The route, in particular the consumer's component, must support the Asynchronous Routing Engine (e.g. seda)." }, + "backOffMultiplier": { "kind": "attribute", "displayName": "Back Off Multiplier", "required": false, "type": "number", "javaType": "java.lang.Double", "deprecated": false, "secret": false, "description": "Sets the back off multiplier" }, + "useExponentialBackOff": { "kind": "attribute", "displayName": "Use Exponential Back Off", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Turn on exponential backk off" }, + "collisionAvoidanceFactor": { "kind": "attribute", "displayName": "Collision Avoidance Factor", "required": false, "type": "number", "javaType": "java.lang.Double", "deprecated": false, "secret": false, "description": "Sets the collision avoidance factor" }, + "useCollisionAvoidance": { "kind": "attribute", "displayName": "Use Collision Avoidance", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Turn on collision avoidance." }, + "maximumRedeliveryDelay": { "kind": "attribute", "displayName": "Maximum Redelivery Delay", "required": false, "type": "duration", "javaType": "java.lang.String", "deprecated": false, "secret": false, "description": "Sets the maximum delay between redelivery" }, + "retriesExhaustedLogLevel": { "kind": "attribute", "displayName": "Retries Exhausted Log Level", "required": false, "type": "object", "javaType": "org.apache.camel.LoggingLevel", "deprecated": false, "secret": false, "description": "Sets the logging level to use when retries has exhausted" }, + "retryAttemptedLogLevel": { "kind": "attribute", "displayName": "Retry Attempted Log Level", "required": false, "type": "object", "javaType": "org.apache.camel.LoggingLevel", "deprecated": false, "secret": false, "description": "Sets the logging level to use for logging retry attempts" }, + "retryAttemptedLogInterval": { "kind": "attribute", "displayName": "Retry Attempted Log Interval", "required": false, "type": "integer", "javaType": "java.lang.Integer", "deprecated": false, "secret": false, "description": "Sets the interval to use for logging retry attempts" }, + "logRetryAttempted": { "kind": "attribute", "displayName": "Log Retry Attempted", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether retry attempts should be logged or not. Can be used to include or reduce verbose." }, + "logStackTrace": { "kind": "attribute", "displayName": "Log Stack Trace", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether stack traces should be logged. Can be used to include or reduce verbose." }, + "logRetryStackTrace": { "kind": "attribute", "displayName": "Log Retry Stack Trace", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether stack traces should be logged when an retry attempt failed. Can be used to include or reduce verbose." }, + "logHandled": { "kind": "attribute", "displayName": "Log Handled", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether handled exceptions should be logged or not. Can be used to include or reduce verbose." }, + "logNewException": { "kind": "attribute", "displayName": "Log New Exception", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether new exceptions should be logged or not. Can be used to include or reduce verbose. A new exception is an exception that was thrown while handling a previous exception." }, + "logContinued": { "kind": "attribute", "displayName": "Log Continued", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether continued exceptions should be logged or not. Can be used to include or reduce verbose." }, + "logExhausted": { "kind": "attribute", "displayName": "Log Exhausted", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether exhausted exceptions should be logged or not. Can be used to include or reduce verbose." }, + "logExhaustedMessageHistory": { "kind": "attribute", "displayName": "Log Exhausted Message History", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether exhausted exceptions should be logged including message history or not (supports property placeholders). Can be used to include or reduce verbose." }, + "logExhaustedMessageBody": { "kind": "attribute", "displayName": "Log Exhausted Message Body", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Sets whether exhausted message body should be logged including message history or not (supports property placeholders). Can be used to include or reduce verbose. Requires logExhaustedMessageHistory to be enabled." }, + "disableRedelivery": { "kind": "attribute", "displayName": "Disable Redelivery", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Disables redelivery (same as setting maximum redeliveries to 0)" }, + "delayPattern": { "kind": "attribute", "displayName": "Delay Pattern", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "secret": false, "description": "Sets the delay pattern with delay intervals." }, + "allowRedeliveryWhileStopping": { "kind": "attribute", "displayName": "Allow Redelivery While Stopping", "required": false, "type": "boolean", "javaType": "java.lang.Boolean", "deprecated": false, "secret": false, "defaultValue": false, "description": "Controls whether to allow redelivery while stopping\/shutting down a route that uses error handling." }, + "exchangeFormatterRef": { "kind": "attribute", "displayName": "Exchange Formatter Ref", "required": false, "type": "string", "javaType": "java.lang.String", "deprecated": false, "secret": false, "description": "Sets the reference of the instance of org.apache.camel.spi.ExchangeFormatter to generate the log message from exchange." } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibrary.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibrary.java new file mode 100644 index 00000000..185fd6a8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibrary.java @@ -0,0 +1,95 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library; + +import java.util.List; + +import org.osgi.framework.Filter; + +public interface ComponentLibrary { + + String COMPONENT_LIBRARY_PROVIDER_HEADER = "Entaxy-Component-Library-Provider"; + String COMPONENT_LIBRARY_RESOURCE_PROTOCOL = "component-library"; + + String getName(); + + String getUrl(); + + List getSchemas(); + + default Filter getObjectFilter() { + return null; + }; + + public interface Schema { + + String getRoot(); + + default String getRootUrl() { + return getRoot(); + } + + String getNamespace(); + + String getPrefix(); + + boolean isPublic(); + + default ComponentLibrary getLibrary() { + return null; + }; + + default Filter getObjectFilter() { + return null; + }; + + List getTransformations(); + + String getUiDescriptor(); + + } + + public interface Transformation { + + String getProcessor(); + + String getSource(); + + default String getSourceUrl() { + return getSource(); + } + + default Filter getObjectFilter() { + return null; + }; + + default ComponentLibrary.Schema getSchema() { + return null; + } + + } + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibraryManager.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibraryManager.java new file mode 100644 index 00000000..698ad04b --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibraryManager.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library; + +import java.util.List; +import java.util.Map; + +public interface ComponentLibraryManager { + + List getLibraries(); + + List getLibrariesForContext(Map context); + + List getSchemasForNamespace(String namespace); + + List getSchemasForPrefix(String prefix); + + List getSchemasForContext(Map context); + + List getAllSchemas(); + + List getAllSchemasWithUiDescriptor(); + + List getTransformationsForContext(Map context); + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibraryResourceProcessor.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibraryResourceProcessor.java new file mode 100644 index 00000000..3807f212 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/ComponentLibraryResourceProcessor.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessor; +import ru.entaxy.platform.core.producer.resources.EntaxyResourceProducingProcessorService; + +@Component(service = EntaxyResourceProducingProcessor.class, immediate = true) +public class ComponentLibraryResourceProcessor implements EntaxyResourceProducingProcessor { + + private static final Logger LOG = LoggerFactory.getLogger(ComponentLibraryResourceProcessor.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + EntaxyResourceProducingProcessorService producingProcessorService; + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ComponentLibraryManager componentLibraryManager; + + @Override + public String getName() { + return "component-library"; + } + + @SuppressWarnings("unchecked") + @Override + public Object process(Object value, Map properties) throws Exception { + + LOG.debug("\n\t ComponentLibraryResourceProcessor:"); + LOG.debug("\n\t" + properties.toString()); + + Map parameters; + if (properties.containsKey("resourceContext") && (properties.get("resourceContext") instanceof Map)) + parameters = new HashMap<>((Map) properties.get("resourceContext")); + else + parameters = new HashMap<>(properties); + + if (properties.containsKey("parameters") && (properties.get("parameters") instanceof Map)) + parameters.putAll((Map) properties.get("parameters")); + + // List libraries = + // componentLibraryManager.getLibrariesForContext(parameters); + // List schemas = + // componentLibraryManager.getSchemasForContext(parameters); + List transformations = + componentLibraryManager.getTransformationsForContext(parameters); + + LOG.info("\n\t TO APPLY:" + + "\n\tTRANSFORMATIONS:\n\t" + + transformations.stream().map(t -> "[" + t.getProcessor() + "] " + t.getSource()) + .collect(Collectors.joining("\n\t"))); + + + Object result = value; + + for (ComponentLibrary.Transformation transformation : transformations) { + + Map processorProperties = new HashMap<>(); + processorProperties.put(PROP_PROCESSOR, transformation.getProcessor()); + processorProperties.put("source", transformation.getSourceUrl()); + processorProperties.put("parameters", parameters); + + LOG.info("\n EXEC TRANSFORM: [{}]/[{}]/[{}]/[{}]\nWITH PROPERTIES:\n{}", transformation.getSourceUrl(), + transformation.getProcessor(), transformation.getSchema().getRoot(), + transformation.getSchema().getLibrary().getName(), + processorProperties); + + result = producingProcessorService.process(result, processorProperties); + + } + + return result; + } + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/impl/ComponentLibraryManagerImpl.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/impl/ComponentLibraryManagerImpl.java new file mode 100644 index 00000000..b1091939 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/impl/ComponentLibraryManagerImpl.java @@ -0,0 +1,326 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.impl; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.Filter; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.esb.resources.EntaxyResourceURLFactory; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.routes.design.library.ComponentLibrary; +import ru.entaxy.platform.routes.design.library.ComponentLibrary.Schema; +import ru.entaxy.platform.routes.design.library.ComponentLibrary.Transformation; +import ru.entaxy.platform.routes.design.library.ComponentLibraryManager; +import ru.entaxy.platform.routes.design.library.storage.ComponentLibraryStorage; + +@Component(service = ComponentLibraryManager.class, immediate = true) +public class ComponentLibraryManagerImpl implements ComponentLibraryManager, ComponentLibraryStorage.StorageListener { + + private static final Logger LOG = LoggerFactory.getLogger(ComponentLibraryManagerImpl.class); + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + ComponentLibraryStorage libraryStorage; + + protected List libraries = new ArrayList<>(); + protected List schemas = new ArrayList<>(); + protected List transformations = new ArrayList<>(); + + protected Object librariesLock = new Object(); + + @Activate + public void activate(ComponentContext componentContext) { + initialize(); + this.libraryStorage.registerListener(this); + } + + @Deactivate + public void deactivate(ComponentContext componentContext) { + this.libraryStorage.unregisterListener(this); + } + + protected void initialize() { + synchronized (librariesLock) { + this.libraries = wrap(libraryStorage.getLibraries()); + for (ComponentLibrary lib : libraries) + for (ComponentLibrary.Schema schema : lib.getSchemas()) { + schemas.add(schema); + for (ComponentLibrary.Transformation transformation : schema.getTransformations()) { + transformations.add(transformation); + } + } + } + } + + protected void reload() { + synchronized (librariesLock) { + libraries.clear(); + schemas.clear(); + transformations.clear(); + } + initialize(); + } + + @Override + public List getLibraries() { + return this.libraries; + } + + @Override + public List getLibrariesForContext(Map context) { + return this.libraries.stream().filter(l -> l.getObjectFilter() == null || l.getObjectFilter().matches(context)) + .collect(Collectors.toList()); + } + + @Override + public List getSchemasForNamespace(String namespace) { + return this.schemas.stream().filter(s -> s.getNamespace().equals(namespace)) + .collect(Collectors.toList()); + } + + @Override + public List getSchemasForPrefix(String prefix) { + return this.schemas.stream().filter(s -> s.getPrefix().equals(prefix)) + .collect(Collectors.toList()); + } + + @Override + public List getSchemasForContext(Map context) { + return this.schemas.stream().filter(s -> s.getObjectFilter() == null || s.getObjectFilter().matches(context)) + .collect(Collectors.toList()); + } + + @Override + public List getAllSchemas() { + return this.schemas; + } + + @Override + public List getAllSchemasWithUiDescriptor() { + return this.schemas.stream().filter(s -> CommonUtils.isValid(s.getUiDescriptor())).collect(Collectors.toList()); + } + + @Override + public List getTransformationsForContext(Map context) { + return this.transformations.stream() + .filter(t -> t.getObjectFilter() == null || t.getObjectFilter().matches(context)) + .collect(Collectors.toList()); + } + + /* ComponentLibraryStorage.StorageListener */ + @Override + public void storageUpdated() { + reload(); + } + + protected URL resolve(ComponentLibrary library, String relative) { + try { + URL libraryUrl = new URL(library.getUrl() + "/"); + URI uri = libraryUrl.toURI().resolve(relative); + return uri.toURL(); + } catch (URISyntaxException | MalformedURLException e) { + LOG.error(String.format("Error resolving url [%s] for library [%s]", relative, library.getName()), e); + return null; + } + } + + /* wrappers */ + + protected List wrap(List originList) { + return originList.stream().map(l -> new LibraryWrapper(l)).collect(Collectors.toList()); + } + + protected class LibraryWrapper implements ComponentLibrary { + + ComponentLibrary origin; + + List wrappedSchemas = null; + + public LibraryWrapper(ComponentLibrary origin) { + this.origin = origin; + } + + @Override + public String getName() { + return origin.getName(); + } + + @Override + public String getUrl() { + try { + return EntaxyResourceURLFactory.getGlobalUrl(origin.getUrl()).toString(); + } catch (MalformedURLException e) { + LOG.error("Error getting global URL for [{}]", origin.getUrl()); + return origin.getUrl(); + } + } + + @Override + public List getSchemas() { + if (wrappedSchemas == null) { + wrappedSchemas = new ArrayList<>(); + + for (ComponentLibrary.Schema schema : origin.getSchemas()) + wrappedSchemas.add(new SchemaWrapper(schema, this)); + + } + return wrappedSchemas; + } + + @Override + public Filter getObjectFilter() { + return origin.getObjectFilter(); + } + + } + + protected class SchemaWrapper implements ComponentLibrary.Schema { + + ComponentLibrary library; + ComponentLibrary.Schema origin; + + List wrappedTransformations = null; + + public SchemaWrapper(ComponentLibrary.Schema origin, ComponentLibrary library) { + this.library = library; + this.origin = origin; + } + + @Override + public String getRoot() { + return origin.getRoot(); + } + + @Override + public String getRootUrl() { + URL resolved = resolve(library, getRoot()); + if (resolved != null) + return resolved.toString(); + return getRoot(); + } + + @Override + public String getNamespace() { + return origin.getNamespace(); + } + + @Override + public String getPrefix() { + return origin.getPrefix(); + } + + @Override + public boolean isPublic() { + return origin.isPublic(); + } + + @Override + public List getTransformations() { + if (wrappedTransformations == null) { + wrappedTransformations = new ArrayList<>(); + + for (ComponentLibrary.Transformation transformation : origin.getTransformations()) + wrappedTransformations.add(new TransformationWrapper(transformation, this)); + + } + return wrappedTransformations; + } + + @Override + public ComponentLibrary getLibrary() { + return this.library; + } + + @Override + public Filter getObjectFilter() { + Filter originFilter = origin.getObjectFilter(); + return originFilter == null ? library.getObjectFilter() : originFilter; + } + + @Override + public String getUiDescriptor() { + return origin.getUiDescriptor(); + } + + } + + protected class TransformationWrapper implements ComponentLibrary.Transformation { + + ComponentLibrary.Transformation origin; + ComponentLibrary.Schema schema; + + public TransformationWrapper(ComponentLibrary.Transformation origin, ComponentLibrary.Schema schema) { + this.origin = origin; + this.schema = schema; + } + + @Override + public String getProcessor() { + return origin.getProcessor(); + } + + @Override + public String getSource() { + return origin.getSource(); + } + + @Override + public String getSourceUrl() { + if (!CommonUtils.isValid(getSource())) + return null; + URL resolved = resolve(schema.getLibrary(), getSource()); + if (resolved != null) + return resolved.toString(); + return getSource(); + } + + @Override + public Schema getSchema() { + return this.schema; + } + + @Override + public Filter getObjectFilter() { + Filter originFilter = origin.getObjectFilter(); + return originFilter == null ? schema.getObjectFilter() : originFilter; + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/shell/CommandLibraryList.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/shell/CommandLibraryList.java new file mode 100644 index 00000000..bddb7348 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/shell/CommandLibraryList.java @@ -0,0 +1,65 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.shell; + +import java.util.stream.Collectors; + +import org.apache.karaf.shell.api.action.Action; +import org.apache.karaf.shell.api.action.Command; +import org.apache.karaf.shell.api.action.lifecycle.Service; + +import ru.entaxy.platform.base.support.karaf.shell.ShellTableExt; +import ru.entaxy.platform.routes.design.library.ComponentLibrary; + +@Service +@Command(scope = ComponentLibraryCommandSupport.COMMAND_SCOPE, name = "component-library-list") +public class CommandLibraryList extends ComponentLibraryCommandSupport implements Action { + + @Override + public Object execute() throws Exception { + + ShellTableExt tableExt = new ShellTableExt(); + tableExt.column("Name"); + tableExt.column("Url"); + tableExt.column("Filter"); + tableExt.column("Schemas"); + + for (ComponentLibrary library : componentLibraryManager.getLibraries()) { + tableExt.addRow().addContent( + library.getName(), + library.getUrl(), + library.getObjectFilter() == null ? "" : library.getObjectFilter().toString(), + library.getSchemas().stream().map(s -> s.getRoot() + " [" + s.getRootUrl() + "]") + .collect(Collectors.joining("\n"))); + } + + // output to console + tableExt.print(System.out); + return null; + + } + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/shell/ComponentLibraryCommandSupport.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/shell/ComponentLibraryCommandSupport.java new file mode 100644 index 00000000..d7e06820 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/shell/ComponentLibraryCommandSupport.java @@ -0,0 +1,39 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.shell; + +import org.apache.karaf.shell.api.action.lifecycle.Reference; + +import ru.entaxy.platform.routes.design.library.ComponentLibraryManager; + +public class ComponentLibraryCommandSupport { + + public static final String COMMAND_SCOPE = "entaxy"; + + @Reference + ComponentLibraryManager componentLibraryManager; + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ComponentLibraryResourceProvider.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ComponentLibraryResourceProvider.java new file mode 100644 index 00000000..80929d78 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ComponentLibraryResourceProvider.java @@ -0,0 +1,55 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.storage; + +import java.util.ArrayList; +import java.util.List; + +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; + +import ru.entaxy.esb.resources.EntaxyResourceProcessor; +import ru.entaxy.esb.resources.EntaxyResourceProviderProxy; +import ru.entaxy.esb.resources.impl.AbstractResourceProviderProxy; +import ru.entaxy.platform.routes.design.library.ComponentLibrary; + +@Component(service = EntaxyResourceProviderProxy.class, immediate = true) +public class ComponentLibraryResourceProvider extends AbstractResourceProviderProxy { + + @Activate + public void activate() { + + setProtocol(ComponentLibrary.COMPONENT_LIBRARY_RESOURCE_PROTOCOL); + setTargetProtocol("entaxy-file-internal"); + setTargetPath(".component-library"); + + List processors = new ArrayList<>(); + + setProcessors(processors); + + } + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ComponentLibraryStorage.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ComponentLibraryStorage.java new file mode 100644 index 00000000..cfedb7b8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ComponentLibraryStorage.java @@ -0,0 +1,392 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.storage; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import org.osgi.framework.BundleContext; +import org.osgi.framework.Filter; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import ru.entaxy.esb.resources.EntaxyResource; +import ru.entaxy.esb.resources.EntaxyResourceProvider; +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.routes.design.library.ComponentLibrary; +import ru.entaxy.platform.routes.design.library.storage.ProvidedLibraryDescriptor.ProvidedLibraryResource; + +@Component(service = ComponentLibraryStorage.class, immediate = true) +public class ComponentLibraryStorage { + + private static final Logger LOG = LoggerFactory.getLogger(ComponentLibraryStorage.class); + + protected static final String PROVIDER_FILTER = + "(protocol=" + ComponentLibrary.COMPONENT_LIBRARY_RESOURCE_PROTOCOL + ")"; + + public static final String LIBRARY_DESCRIPTOR_NAME = "library.json"; + + protected static final String LIBRARIES_RESOURCE = "libraries.json"; + + @Reference(cardinality = ReferenceCardinality.MANDATORY, target = PROVIDER_FILTER) + EntaxyResourceProvider resourceProvider; + + protected BundleContext bundleContext; + + // protected ComponentLibraryTracker libraryTracker; + + protected EntaxyResource librariesResource; + + protected Libraries libraries; + + protected Object librariesLock = new Object(); + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + reload(); + + /* + if (libraryTracker != null) + libraryTracker.close(); + libraryTracker = ComponentLibraryTracker.create(this, this.bundleContext); + libraryTracker.open(); + */ + } + + @Deactivate + public void deactivate() { + /* + if (libraryTracker != null) + libraryTracker.close(); + */ + } + + protected void load() { + librariesResource = resourceProvider.getResource(LIBRARIES_RESOURCE); + if (!librariesResource.exists()) { + libraries = new Libraries(); + try { + updateLibrariesResource(); + } catch (IOException e) { + LOG.error("Error saving [" + LIBRARIES_RESOURCE + "]", e); + } + } else { + libraries = new Libraries(librariesResource.getAsString()); + } + } + + protected void updateLibrariesResource() throws IOException { + try (InputStream is = new ByteArrayInputStream(libraries.toJson().toString().getBytes())) { + librariesResource.save(is); + } + } + + public void reload() { + load(); + } + + synchronized public void addLibrary(ProvidedLibraryDescriptor descriptor, Library library) { + Library existing = libraries.get(library.getName()); + long bundleLastModified = descriptor.bundle.getLastModified(); + if (existing != null) { + if (existing.lastModified != bundleLastModified) { + LOG.info("Library [{}] must be updated", library.getName()); + synchronized (librariesLock) { + try { + uploadLibraryResources(descriptor); + } catch (Exception e) { + LOG.error(String.format("Error uploading resources for library [%s]", library.getName()), e); + } + libraries.update(library, bundleLastModified); + try { + updateLibrariesResource(); + LOG.info("Updated library [{}]", library.getName()); + notifyListeners(); + } catch (IOException e) { + LOG.error("Error updating libraries", e); + } + } + } else { + LOG.info("Library [{}] not changed", library.getName()); + } + } else { + LOG.info("Adding new library [{}]", library.getName()); + library.lastModified = descriptor.bundle.getLastModified(); + + synchronized (librariesLock) { + try { + uploadLibraryResources(descriptor); + } catch (Exception e) { + LOG.error(String.format("Error uploading resources for library [%s]", library.getName()), e); + } + libraries.add(library); + try { + updateLibrariesResource(); + LOG.info("Added new library [{}]", library.getName()); + notifyListeners(); + } catch (IOException e) { + LOG.error("Error updating libraries", e); + } + } + + } + } + + protected void uploadLibraryResources(ProvidedLibraryDescriptor descriptor) throws Exception { + + for (ProvidedLibraryResource provided : descriptor.getLibraryResources()) { + String targetPath = descriptor.libraryName + "/" + provided.path; + EntaxyResource resource = resourceProvider.getResource(targetPath); + try (InputStream is = provided.url.openStream()) { + resource.save(is); + } catch (IOException e) { + LOG.error(String.format("Error uploading resource [%s]", targetPath), e); + throw e; + } + + } + + } + + public List getLibraries() { + return libraries.librariesMap.values().stream().map(l -> (ComponentLibrary) l).collect(Collectors.toList()); + } + + protected class Libraries { + + Map librariesMap; + + Object librariesMapLock = new Object(); + + public Libraries() { + librariesMap = new HashMap<>(); + } + + public Libraries(String jsonOrigin) { + JsonObject jo = JSONUtils.getJsonRootObject(jsonOrigin); + Type type = new TypeToken>() {}.getType(); + librariesMap = JSONUtils.GSON.fromJson(jo, type); + for (Library lib : librariesMap.values()) + lib.libraryUrl = resourceProvider.getResource(lib.getName()).getURL(); + } + + public JsonElement toJson() { + return JSONUtils.GSON.toJsonTree(librariesMap); + } + + public Library get(String libraryName) { + return librariesMap.get(libraryName); + } + + public void add(Library library) { + synchronized (librariesMapLock) { + library.libraryUrl = resourceProvider.getResource(library.getName()).getURL(); + this.librariesMap.put(library.getName(), library); + } + } + + public void update(Library library, long lastModified) { + this.librariesMap.get(library.getName()).update(library); + this.librariesMap.get(library.getName()).lastModified = lastModified; + } + } + + public static abstract class ObjectFilterAware { + + public String objectFilter; + + transient Filter targetFilter = null; + + public Filter getObjectFilter() { + if (!CommonUtils.isValid(objectFilter)) + return null; + if (targetFilter == null) { + try { + return FrameworkUtil.createFilter(objectFilter); + } catch (InvalidSyntaxException e) { + LOG.error(String.format("Error creating filter for [%s]", objectFilter), e); + } + } + return targetFilter; + } + + } + + public static class Library extends ObjectFilterAware implements ComponentLibrary { + + public String library; + + public long lastModified = -1; + + public List schemas; + + transient public String libraryUrl; + + @Override + public String getName() { + return library; + } + + @Override + public String getUrl() { + return libraryUrl; + } + + public void update(Library library) { + this.lastModified = library.lastModified; + if (this.schemas == null) { + this.schemas = new ArrayList<>(); + } else { + this.schemas.clear(); + } + if (library.schemas != null) + this.schemas.addAll(library.schemas); + } + + @Override + public List getSchemas() { + return this.schemas.stream().map(s -> (ComponentLibrary.Schema) s).collect(Collectors.toList()); + } + + public static class IncludedSchema extends ObjectFilterAware implements ComponentLibrary.Schema { + public String root; + public String namespace; + public String prefix; + public boolean isPublic; + public List> transform; + public String uiDescriptor; + + transient List transformations = null; + + @Override + public String getRoot() { + return root; + } + + @Override + public String getNamespace() { + return namespace; + } + + @Override + public String getPrefix() { + return prefix; + } + + @Override + public boolean isPublic() { + return isPublic; + } + + @Override + public List getTransformations() { + if (this.transformations == null) { + this.transformations = new ArrayList<>(); + for (Map transformationData : transform) { + transformations.add(new IncludedTransformation(transformationData)); + } + } + return this.transformations.stream().map(t -> (ComponentLibrary.Transformation) t) + .collect(Collectors.toList()); + } + + @Override + public String getUiDescriptor() { + return uiDescriptor; + } + } + public static class IncludedTransformation extends ObjectFilterAware + implements ComponentLibrary.Transformation { + + protected Map data; + + public IncludedTransformation(Map data) { + this.data = new HashMap<>(data); + this.objectFilter = data.getOrDefault("objectFilter", "").toString(); + } + + @Override + public String getProcessor() { + return data.getOrDefault("processor", "unknown").toString(); + } + + @Override + public String getSource() { + return data.getOrDefault("source", "unknown").toString(); + } + + } + } + + protected List listeners = new ArrayList<>(); + + protected Object listenersLock = new Object(); + + public void registerListener(StorageListener listener) { + synchronized (listenersLock) { + if (!listeners.contains(listener)) + listeners.add(listener); + } + } + + public void unregisterListener(StorageListener listener) { + synchronized (listenersLock) { + listeners.remove(listener); + } + } + + protected void notifyListeners() { + synchronized (listenersLock) { + for (StorageListener listener : listeners) + listener.storageUpdated(); + } + } + + public interface StorageListener { + void storageUpdated(); + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ProvidedLibraryDescriptor.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ProvidedLibraryDescriptor.java new file mode 100644 index 00000000..926dac40 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/storage/ProvidedLibraryDescriptor.java @@ -0,0 +1,107 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.storage; + +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +import org.osgi.framework.Bundle; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import ru.entaxy.platform.routes.design.library.ComponentLibrary; + +public class ProvidedLibraryDescriptor { + + private static final Logger LOG = LoggerFactory.getLogger(ProvidedLibraryDescriptor.class); + + public static final String LIBRARY_PATH = "/ru/entaxy/" + ComponentLibrary.COMPONENT_LIBRARY_RESOURCE_PROTOCOL; + + public Bundle bundle; + public String libraryPath; + public String libraryName; + + protected List libraryResources = null; + + public ProvidedLibraryDescriptor(Bundle bundle, String path, String name) { + this.bundle = bundle; + this.libraryPath = path; + this.libraryName = name; + } + + public List getLibraryResources() { + if (libraryResources == null) { + libraryResources = new ArrayList<>(); + + Enumeration entries = bundle.findEntries(libraryPath, "*.*", true); + if (entries != null) { + + while (entries.hasMoreElements()) { + URL entry = entries.nextElement(); + String entryUrl = entry.toString(); + + if (entryUrl.endsWith("/")) + continue; + + String resourcePath = entryUrl.substring(entryUrl.indexOf(libraryPath) + libraryPath.length()); + + /* + if (resourcePath.equals(ComponentLibraryStorage.LIBRARY_DESCRIPTOR_NAME)) + continue; + */ + + String resourceName = null; + int index = resourcePath.lastIndexOf('/'); + if (index < 0) + resourceName = resourcePath; + else + resourceName = resourcePath.substring(index + 1); + + ProvidedLibraryResource resource = new ProvidedLibraryResource(); + resource.url = entry; + resource.path = resourcePath; + resource.name = resourceName; + + libraryResources.add(resource); + } + + } + + } + return libraryResources; + } + + public static class ProvidedLibraryResource { + + URL url; + String name; + String path; + + } + +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/tracker/ComponentLibraryTracker.java b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/tracker/ComponentLibraryTracker.java new file mode 100644 index 00000000..55661163 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/java/ru/entaxy/platform/routes/design/library/tracker/ComponentLibraryTracker.java @@ -0,0 +1,223 @@ +/*- + * ~~~~~~licensing~~~~~~ + * route-producing + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.routes.design.library.tracker; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.Map; + +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.BundleEvent; +import org.osgi.service.component.ComponentContext; +import org.osgi.service.component.annotations.Activate; +import org.osgi.service.component.annotations.Component; +import org.osgi.service.component.annotations.Deactivate; +import org.osgi.service.component.annotations.Reference; +import org.osgi.service.component.annotations.ReferenceCardinality; +import org.osgi.util.tracker.BundleTracker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.gson.JsonObject; + +import ru.entaxy.platform.base.support.CommonUtils; +import ru.entaxy.platform.base.support.JSONUtils; +import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerCustomizerListener; +import ru.entaxy.platform.base.support.osgi.tracker.BundleTrackerUtils; +import ru.entaxy.platform.base.support.osgi.tracker.UniformBundleTrackerCustomizer; +import ru.entaxy.platform.base.support.osgi.tracker.filter.BundleHeaderFilter; +import ru.entaxy.platform.routes.design.library.ComponentLibrary; +import ru.entaxy.platform.routes.design.library.storage.ComponentLibraryStorage; +import ru.entaxy.platform.routes.design.library.storage.ComponentLibraryStorage.Library; +import ru.entaxy.platform.routes.design.library.storage.ProvidedLibraryDescriptor; + +@Component(service = ComponentLibraryTracker.class, immediate = true) +public class ComponentLibraryTracker { + + private static final Logger LOG = LoggerFactory.getLogger(ComponentLibraryTracker.class); + + public static ComponentLibraryTracker create(ComponentLibraryStorage storage, BundleContext bundleContext) { + return new ComponentLibraryTracker(storage, bundleContext); + } + + @Reference(cardinality = ReferenceCardinality.MANDATORY) + protected ComponentLibraryStorage storage; + + protected BundleContext bundleContext; + + protected BundleTracker> tracker; + + public ComponentLibraryTracker() { + super(); + } + + @Activate + public void activate(ComponentContext componentContext) { + this.bundleContext = componentContext.getBundleContext(); + tracker = BundleTrackerUtils.>createBuilder() + .addFilter( + (new BundleHeaderFilter()).header(ComponentLibrary.COMPONENT_LIBRARY_PROVIDER_HEADER)) + .customizer( + (new LibraryTrackerCusomizer()) + .listener(new LibraryTrackerCusomizerListener())) + .bundleState(Bundle.ACTIVE | Bundle.INSTALLED | Bundle.RESOLVED) + .get(); + tracker.open(); + } + + @Deactivate + public void deactivate() { + if (tracker != null) + tracker.close(); + } + + protected ComponentLibraryTracker(ComponentLibraryStorage storage, BundleContext bundleContext) { + + this.storage = storage; + this.bundleContext = bundleContext; + + + + } + + public void open() { + if (tracker != null) + tracker.open(); + } + + public void close() { + if (tracker != null) + tracker.close(); + } + + protected class LibraryTrackerCusomizer extends UniformBundleTrackerCustomizer> { + + @Override + protected List createManagedObject(Bundle bundle, BundleEvent event, + Map> filterResults) { + + Enumeration foundEntries = bundle.findEntries(ProvidedLibraryDescriptor.LIBRARY_PATH, "*", false); + if (foundEntries == null) { + LOG.warn("Bundle [{}] marked as library provider but contains no libraries", bundle.getSymbolicName()); + return null; + } + + List result = new ArrayList<>(); + + while (foundEntries.hasMoreElements()) { + + URL entry = foundEntries.nextElement(); + String entryUrl = entry.toString(); + if (!entryUrl.endsWith("/")) + continue; + + int index = entryUrl.indexOf(ProvidedLibraryDescriptor.LIBRARY_PATH); + String libraryPath = entryUrl.substring(index); + String libraryName = libraryPath.substring(ProvidedLibraryDescriptor.LIBRARY_PATH.length() + 1, + libraryPath.length() - 1); + LOG.info("Found library [{}] in bundle [{}]", libraryName, bundle.getSymbolicName()); + result.add(new ProvidedLibraryDescriptor(bundle, libraryPath, libraryName)); + } + + return result; + } + + } + + protected class LibraryTrackerCusomizerListener + implements BundleTrackerCustomizerListener> { + + @Override + public void added(List managedObject) { + for (ProvidedLibraryDescriptor descriptor : managedObject) { + + URL entry = descriptor.bundle + .getEntry(descriptor.libraryPath + ComponentLibraryStorage.LIBRARY_DESCRIPTOR_NAME); + if (entry == null) { + LOG.warn("Descrptor not found for library [{}] in bundle [{}]", descriptor.libraryName, + descriptor.bundle.getSymbolicName()); + continue; + } + + String content = null; + + try (InputStream is = entry.openStream()) { + content = new String(is.readAllBytes()); + } catch (IOException e) { + LOG.error(String.format("Error reading library descriptor [%s] in bundle [%s]", + descriptor.libraryPath + ComponentLibraryStorage.LIBRARY_DESCRIPTOR_NAME, + descriptor.bundle.getSymbolicName()), e); + continue; + } + + if (!CommonUtils.isValid(content)) { + LOG.error(String.format("Library descriptor is empty: [%s] in bundle [%s]", + descriptor.libraryPath + ComponentLibraryStorage.LIBRARY_DESCRIPTOR_NAME, + descriptor.bundle.getSymbolicName())); + continue; + } + + JsonObject jo = JSONUtils.getJsonRootObject(content); + if ((jo == null) || jo.keySet().isEmpty()) { + LOG.error(String.format("Invalid library descriptor: [%s] in bundle [%s]", + descriptor.libraryPath + ComponentLibraryStorage.LIBRARY_DESCRIPTOR_NAME, + descriptor.bundle.getSymbolicName())); + continue; + } + + Library library = JSONUtils.GSON.fromJson(jo, Library.class); + if ((library == null) || !CommonUtils.isValid(library.library)) { + LOG.error(String.format("Invalid library descriptor content: [%s] in bundle [%s]", + descriptor.libraryPath + ComponentLibraryStorage.LIBRARY_DESCRIPTOR_NAME, + descriptor.bundle.getSymbolicName())); + continue; + } + + LOG.info("Recognized library [{}] having [{}] schemas", library.library, + library.schemas == null ? -1 : library.schemas.size()); + + storage.addLibrary(descriptor, library); + + } + } + + @Override + public void modified(List managedObject) { + // ignore + } + + @Override + public void removed(List managedObject) { + // ignore + } + + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/blueprint-entaxy.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/blueprint-entaxy.xsd new file mode 100644 index 00000000..7284de26 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/blueprint-entaxy.xsd @@ -0,0 +1,993 @@ + + + + + + + if used as a qualified namespace, "bp" is the recommended + namespace prefix. + ]]> + + + + + , , + and elements are all derived from + the Tcomponent type. This type defines an id attribute + that is used create references between different components. + Component elements can also be inlined within other component + definitions. The id attribute is not valid when inlined. + ]]> + + + + + element. + ]]> + + + + + or elements with unstatisfied + manadatory references, then the depends-on relationship will also + be used to determine whether this service is enabled or not. + ]]> + + + + + + element is the root element for a blueprint + configuration file. A blueprint configuration has two sections. + The first section (contained within the element) + identifies components that are used for converting values into + different target types. The type converters are optional, so + the file does not need to specify a type converter section. + + Following the type converters are the component definitions. + Components are , , , and + elements that identify the bundle components that will + be managed by the blueprint service. + ]]> + + + + + + + + + + + + + + + + + + + + + + + element can override the specified configuration + default. + ]]> + + + + + , and components. The + normal default is "mandatory", and can be changed by individual + service reference components. + ]]> + + + + + + + + element. The + section is a set of , , or + elements that identify the type converter components. + ]]> + + + + + + + + + + + + element + or an inlined or . + ]]> + + + + + + + + + + + , , , and . + ]]> + + + + + + + + + + element. + ]]> + + + + + + + + + + + + + component. The + attributes provide the characteristics for how to create a + bean instance. Constructor arguments and injected properties + are specified via child and elements. + ]]> + + + + + + + + + + + + + + + + + elements. Those elements have some restrictions on + the attributes that can be used to define them. + ]]> + + + + + + + + + + + + + + + + + + + + + component. The elements are the arguments for the + bean class constructor or passed to the bean factory method. + + The type, if specified, is used to disambiguate the constructor + or method signature. Arguments may also be matched up with + arguments by explicitly specifying the index position. If the + index is used, then all elements for the bean must + also specify the index. + + The value and ref attributes are convenience shortcuts to make + the tag easier to code. A fuller set of injected + values and types can be specified using one of the "value" + type elements. + ]]> + + + + + + + + + + + + + + component. The elements correspond to named + JavaBean setting methods for a created bean object. + + The value and ref attributes are convenience shortcuts to make + the tag easier to code. A fuller set of injected + values and types can be specified using one of the "value" + type elements. + ]]> + + + + + + + + + + + + element. + ]]> + + + + + + + element. These + are instances of the TserviceReference type, with the addition + of a timeout attribute. If the timeout is not specified, + the default-timeout value is inherited from the encapsulating + definition. + ]]> + + + + + + + + + + + + + elements. + ]]> + + + + + + + + + + + + + + + + + + + + + + + . This adds in the characteristics that + only apply to collections of references (e.g., member-type). + ]]> + + + + + + + + + + + + + elements. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + and elements. This type defines all of the + characteristics common to both sorts of references. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + element. + ]]> + + + + + + + + + + + + + to a or element, or an inline + or . + ]]> + + + + + + + or element. The listener + object can be specified as a or as an inline or + component. Listener events are mapped to the indicated + bind or unbind methods. + ]]> + + + + + + + + + + + default-activation attribute and the + activation attribute. + ]]> + + + + + + + + + default-availability attribute and the + and availability attribute. + ]]> + + + + + + + + + + to a component or an + bean component. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + elements. + ]]> + + + + + + + + + + + + + + + + + + + + + + + element also has + a shortcut interface attribute for the usual case of just + a single interface being used. This also cannot be used if + the auto-export attribute is used. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + to a or component, or an inline + or component definition. The registration-method and + unregistration-method attributes define the methods that will be called + for the respective events. + + For the very common case of using a to a listener component, the + ref attribute may also be used as a shortcut. + ]]> + + + + + + + + + + + + and elements, any of the + component types (, , etc.) as inline components, the + generic element for types sourced from string values, any of the + collection types (, , , , ), and the + type to inject a null value. + ]]> + + + + + + + + + value type. + ]]> + + + + + and elements, any of the + component types (, , etc.) as inline components, the + generic element for types sourced from string values, and any of the + collection types (, , , , ). + + The type is NOT a member of this group. + ]]> + + + + + + + + + + + + + + + elements. This specifies a required + component id for the reference component. + ]]> + + + + + + elements. The element + is used for types that can be created from a single string value. + The string value is the data value for the element. The optional + type attribute allows a target conversion value to be explicitly + specified. + ]]> + + + + + + + + + + + + + , , and elements. + ]]> + + + + + + + + + + value element. The prop elements + are pairs of string-valued keys and values. + ]]> + + + + + + + + value type. The property + value can be specified using either the attribute, or as value data for + the property element. + ]]> + + + + + + + + elements. A map may have a + default value type specified, so it inherits from the TtypeCollection + type. A key type can also be specified, and the map members are + created from the entry elements, which require a key/value pair. + ]]> + + + + + + + + + + + + + + elements nested inside of a element. + Each instance defines a key/value pair that will be added to the + Map. Both the keys and values may be arbitrary types. Keys must not + be but is permitted for entry values. A default type + can be specified for both the keys and the values, but individual keys + or values can override the default. + ]]> + + + + + + + + + + + + + + elements. + The syntax is similar to what is defined for , but keys must be + string values and there are no type defaults that can be specified. + created from the entry elements, which require a key/value pair. + ]]> + + + + + + + + + + + element. This does not allow a child element and there are no + key-ref or value-ref attributes. + ]]> + + + + + + + + + + + element type to allow documentation to added to the + blueprint configuration. + ]]> + + + + + + element used for + ]]> + + + + + + + + element. + This is just a xxxxx element where the contained + value is the name of an interface class. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/blueprint.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/blueprint.xsd new file mode 100644 index 00000000..f608e141 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/blueprint.xsd @@ -0,0 +1,991 @@ + + + + + + + if used as a qualified namespace, "bp" is the recommended + namespace prefix. + ]]> + + + + + , , + and elements are all derived from + the Tcomponent type. This type defines an id attribute + that is used create references between different components. + Component elements can also be inlined within other component + definitions. The id attribute is not valid when inlined. + ]]> + + + + + element. + ]]> + + + + + or elements with unstatisfied + manadatory references, then the depends-on relationship will also + be used to determine whether this service is enabled or not. + ]]> + + + + + + element is the root element for a blueprint + configuration file. A blueprint configuration has two sections. + The first section (contained within the element) + identifies components that are used for converting values into + different target types. The type converters are optional, so + the file does not need to specify a type converter section. + + Following the type converters are the component definitions. + Components are , , , and + elements that identify the bundle components that will + be managed by the blueprint service. + ]]> + + + + + + + + + + + + + + + + + + + + + + + element can override the specified configuration + default. + ]]> + + + + + , and components. The + normal default is "mandatory", and can be changed by individual + service reference components. + ]]> + + + + + + + + element. The + section is a set of , , or + elements that identify the type converter components. + ]]> + + + + + + + + + + + + element + or an inlined or . + ]]> + + + + + + + + + + + , , , and . + ]]> + + + + + + + + + + element. + ]]> + + + + + + + + + + + + + component. The + attributes provide the characteristics for how to create a + bean instance. Constructor arguments and injected properties + are specified via child and elements. + ]]> + + + + + + + + + + + + + + + + + elements. Those elements have some restrictions on + the attributes that can be used to define them. + ]]> + + + + + + + + + + + + + + + + + + + + + component. The elements are the arguments for the + bean class constructor or passed to the bean factory method. + + The type, if specified, is used to disambiguate the constructor + or method signature. Arguments may also be matched up with + arguments by explicitly specifying the index position. If the + index is used, then all elements for the bean must + also specify the index. + + The value and ref attributes are convenience shortcuts to make + the tag easier to code. A fuller set of injected + values and types can be specified using one of the "value" + type elements. + ]]> + + + + + + + + + + + + + + component. The elements correspond to named + JavaBean setting methods for a created bean object. + + The value and ref attributes are convenience shortcuts to make + the tag easier to code. A fuller set of injected + values and types can be specified using one of the "value" + type elements. + ]]> + + + + + + + + + + + + element. + ]]> + + + + + + + element. These + are instances of the TserviceReference type, with the addition + of a timeout attribute. If the timeout is not specified, + the default-timeout value is inherited from the encapsulating + definition. + ]]> + + + + + + + + + + + + + elements. + ]]> + + + + + + + + + + + + + + + + + + + + + + + . This adds in the characteristics that + only apply to collections of references (e.g., member-type). + ]]> + + + + + + + + + + + + + elements. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + and elements. This type defines all of the + characteristics common to both sorts of references. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + element. + ]]> + + + + + + + + + + + + + to a or element, or an inline + or . + ]]> + + + + + + + or element. The listener + object can be specified as a or as an inline or + component. Listener events are mapped to the indicated + bind or unbind methods. + ]]> + + + + + + + + + + + default-activation attribute and the + activation attribute. + ]]> + + + + + + + + + default-availability attribute and the + and availability attribute. + ]]> + + + + + + + + + + to a component or an + bean component. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + elements. + ]]> + + + + + + + + + + + + + + + + + + + + + + + element also has + a shortcut interface attribute for the usual case of just + a single interface being used. This also cannot be used if + the auto-export attribute is used. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + to a or component, or an inline + or component definition. The registration-method and + unregistration-method attributes define the methods that will be called + for the respective events. + + For the very common case of using a to a listener component, the + ref attribute may also be used as a shortcut. + ]]> + + + + + + + + + + + + and elements, any of the + component types (, , etc.) as inline components, the + generic element for types sourced from string values, any of the + collection types (, , , , ), and the + type to inject a null value. + ]]> + + + + + + + + + value type. + ]]> + + + + + and elements, any of the + component types (, , etc.) as inline components, the + generic element for types sourced from string values, and any of the + collection types (, , , , ). + + The type is NOT a member of this group. + ]]> + + + + + + + + + + + + + + + elements. This specifies a required + component id for the reference component. + ]]> + + + + + + elements. The element + is used for types that can be created from a single string value. + The string value is the data value for the element. The optional + type attribute allows a target conversion value to be explicitly + specified. + ]]> + + + + + + + + + + + + + , , and elements. + ]]> + + + + + + + + + + value element. The prop elements + are pairs of string-valued keys and values. + ]]> + + + + + + + + value type. The property + value can be specified using either the attribute, or as value data for + the property element. + ]]> + + + + + + + + elements. A map may have a + default value type specified, so it inherits from the TtypeCollection + type. A key type can also be specified, and the map members are + created from the entry elements, which require a key/value pair. + ]]> + + + + + + + + + + + + + + elements nested inside of a element. + Each instance defines a key/value pair that will be added to the + Map. Both the keys and values may be arbitrary types. Keys must not + be but is permitted for entry values. A default type + can be specified for both the keys and the values, but individual keys + or values can override the default. + ]]> + + + + + + + + + + + + + + elements. + The syntax is similar to what is defined for , but keys must be + string values and there are no type defaults that can be specified. + created from the entry elements, which require a key/value pair. + ]]> + + + + + + + + + + + element. This does not allow a child element and there are no + key-ref or value-ref attributes. + ]]> + + + + + + + + + + + element type to allow documentation to added to the + blueprint configuration. + ]]> + + + + + + element used for + ]]> + + + + + + + + element. + This is just a xxxxx element where the contained + value is the name of an interface class. + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/camel-entaxy.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/camel-entaxy.xsd new file mode 100644 index 00000000..8757653a --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/camel-entaxy.xsd @@ -0,0 +1,13755 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/camel.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/camel.xsd new file mode 100644 index 00000000..e75023b1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/camel.xsd @@ -0,0 +1,13730 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.json new file mode 100644 index 00000000..d0877f95 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.json @@ -0,0 +1,38 @@ +{ + "m:connector-selector": { + "topChild": true, + "children": [ + "m:properties-to-use", + "m:patterns", + "m:options" + ] + }, + "m:properties-to-use": { + "children": [ + "m:property" + ] + }, + "m:property": {"children": []}, + "m:patterns": { + "children": [ + "m:pattern" + ] + }, + "m:pattern": {"children": []}, + "m:options": { + "children": [ + "m:fail-back-to-legacy-router", + "m:use-the-only-connector", + "m:use-default-connector", + "m:connector-preferred-as-mandatory", + "m:allow-all-stars-pattern", + "m:treat-no-property-as-any" + ] + }, + "m:fail-back-to-legacy-router": {"children": []}, + "m:use-the-only-connector": {"children": []}, + "m:use-default-connector": {"children": []}, + "m:connector-preferred-as-mandatory": {"children": []}, + "m:allow-all-stars-pattern": {"children": []}, + "m:treat-no-property-as-any": {"children": []} +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.xsd new file mode 100644 index 00000000..c61abeb6 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.xsd @@ -0,0 +1,38 @@ + + + + + Comment describing your root element + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.xslt new file mode 100644 index 00000000..7695d34c --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/connector-selector.xslt @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + generated from 'connector-selector' + + + bean:selector- + + + + + + + + selector- + + + + + + + + + + + + + + { + + "_end":true} + + + + "properties":[ + + "" + + , + + + ], + + + + "patterns":[ + + "" + + , + + + ], + + + + "options":{ + + "": + + + + + + , + + + "", + + + + + true, + + + + "_end":true}, + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-connectors.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-connectors.xslt new file mode 100644 index 00000000..f46bfc54 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-connectors.xslt @@ -0,0 +1,194 @@ + + + + + + + + + + + + + + . + + + + + + + + + + + + direct:connector--response-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + direct:connector--pre-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + direct:connector--pre-output + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + + + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.json new file mode 100644 index 00000000..0fe78208 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.json @@ -0,0 +1,325 @@ +{ + "m:standard-router": { + "topChild": true, + "children": [] + }, + "m:set-destination": { + "topChild": true, + "children": [] + }, + "m:default-destination": { + "topChild": true, + "children": [] + }, + "m:prefer-connector": { + "topChild": true, + "children": ["protocol", "classifier", "type"] + }, + "protocol": { + "children": [] + }, + "classifier": { + "children": [] + }, + "type": { + "children": [] + }, + "m:next-route": { + "topChild": true, + "attrs": { + "local": null, + "async": null + }, + "children": [] + }, + "m:respond": { + "topChild": true, + "attrs": { + "now": null, + "continue": null, + "continueAsync": null + }, + "children": [] + }, + "m:xslt": { + "topChild": true, + "attrs": { + "resource": null, + "params": null + }, + "children": [] + }, + "m:xslt-xalan": { + "topChild": true, + "attrs": { + "resource": null, + "params": null + }, + "children": [] + }, + "m:atlasmap": { + "topChild": true, + "attrs": { + "resource": null, + "params": null + }, + "children": [] + }, + "m:read-secret": { + "topChild": true, + "attrs": { + "vault": null, + "property": null, + "alias": null + }, + "children": [] + }, + "m:to-connection": { + "topChild": true, + "attrs": { + "name": null, + "path": null, + "dynamic": null + }, + "children": [] + }, + "m:entaxy-trace": { + "topChild": true, + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:call-route": { + "topChild": true, + "attrs": { + "name": null, + "library": null, + "async": null + }, + "children": [] + }, + "m:set-log-key": { + "topChild": true, + "children": [ + "m:service", + "m:operation", + "m:objectId", + "m:parameter", + "m:sender", + "m:receiver", + "m:custom" + ] + }, + "m:service": { + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:operation": { + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:objectId": { + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:parameter": { + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:sender": { + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:receiver": { + "attrs": { + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:custom": { + "attrs": { + "name": null, + "reset": null + }, + "children": [ + "expressionDefinition", + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xtokenize", + "xpath", + "xquery" + ] + }, + "m:log": { + "topChild": true, + "attrs": { + "message": null, + "loggingLevel": null, + "logName": null, + "marker": null, + "loggerRef": null, + "inheritErrorHandler": null, + "customId": null, + "id": null + }, + "children": [ + "description" + ] + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.xsd new file mode 100644 index 00000000..78fe36b1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.xsd @@ -0,0 +1,163 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.xslt new file mode 100644 index 00000000..86e21a91 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-mediators.xslt @@ -0,0 +1,763 @@ + + + + + + + + + + + + + + + + + + + + + BEGIN standard-router + + + ${headers.ENTAXY_Destination} == null + + ${header.NTX_loggingKey} Destination isn't set + ERROR + + + + + ${headers.ENTAXY_DestinationType} == 'system.name' + + system:${headers.ENTAXY_Destination} + + + + ${headers.ENTAXY_DestinationType} == 'system-group.name' + + system-group:${headers.ENTAXY_Destination} + + + + ${headers.ENTAXY_DestinationType} == 'queue.name' + + entaxy-broker:queue:${headers.ENTAXY_Destination} + + + + ${headers.ENTAXY_DestinationType} == 'topic.name' + + entaxy-broker:topic:${headers.ENTAXY_Destination} + + + + + system:${headers.ENTAXY_Destination} + + + + + END standard-router + + + + + + + + + + + + + + + + + + generated from 'set-destination' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + generated from 'default-destination' + + + ${headers.ENTAXY_Destination} == null || ${headers.ENTAXY_Destination} == '' + + + + + + + + + + + + + + + + + + + + + + + + { + + "": "" + + + + , + + + + } + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + false + + + + + + + + + + + false + + + + + + + + direct + + -vm + + + + + + seda + + + vm + + + + + + + + + + generated from 'next-route' + + + : + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + __SECRET__ + + + + + + + + + + secret + + + + + $ + + + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + + + + true + + + + + + + + + + true + + + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Generated from 'call-route': name=; library=; async= + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ${headers.ENTAXY_TRACE} != null + + ${headers.ENTAXY_TRACE} -> + + + + + + + + + ${headers.ENTAXY_TRACE} == null + + [${headers.NTX_TRACE_RECORD}] + + + + + ${headers.ENTAXY_TRACE}[${headers.NTX_TRACE_RECORD}] + + + + + + + + + + + + + + + + + + + + + + + + + & + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-profiles.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-profiles.xslt new file mode 100644 index 00000000..f252861b --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-profiles.xslt @@ -0,0 +1,161 @@ + + + + + + + + + + + + + + + + + + + + + direct:profile--in-flow-pre-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + direct:profile--in-flow-response-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + direct:profile--out-flow-pre-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + direct:profile--out-flow-response-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + direct:profile--connector-selector + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + + + + + + + + + + + direct-vm:profile--default-route + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-routes.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-routes.xslt new file mode 100644 index 00000000..22cd55c7 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-routes.xslt @@ -0,0 +1,293 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + globalAsync = + globalSync = + localAsync = + localSync = + + + + + async + local + seda + + + + + + + + + sync + local + direct + + + + + + + + + async + global + vm + + + + + + + + + sync + global + direct-vm + + + + + + + + + + + direct: + + + generated from 'entaxy:common-route' for : + + + + + + + + + + + + + + + + + + + + + generated from 'entaxy:common-route' for : + + + + + + + WARNING: UNSUPPORTED ROUTE TYPE: + + + + + + + + + + + + + + + ---entry-point + + + () entry point for + + + : + + + + + direct: + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-services.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-services.xslt new file mode 100644 index 00000000..b4e9fc5f --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-services.xslt @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + direct:-operation-router + + + generated from 'entaxy:object-route' for :/ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-struct.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-struct.xslt new file mode 100644 index 00000000..e8892529 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-struct.xslt @@ -0,0 +1,51 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-test.xml b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-test.xml new file mode 100644 index 00000000..7d4c4ce6 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy-test.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + qwe + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy.xsd new file mode 100644 index 00000000..2f57aeda --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/entaxy.xsd @@ -0,0 +1,466 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/library.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/library.json new file mode 100644 index 00000000..65e10c16 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/library.json @@ -0,0 +1,101 @@ +{ + "library": "entaxy-main", + "objectFilter": "", + "schemas": [ + { + "root": "entaxy.xsd", + "namespace": "http://www.entaxy.ru/schemas/1.0", + "prefix": "entaxy", + "isPublic": true, + "objectFilter": "", + "transform": [ + { + "processor": "xslt", + "source": "entaxy-struct.xslt", + "objectFilter": "" + }, + { + "processor": "xslt", + "source": "entaxy-profiles.xslt", + "objectFilter": "(|(context.type=entaxy.runtime.profile)(context.type=entaxy.runtime.default-route))" + }, + { + "processor": "xslt", + "source": "entaxy-connectors.xslt", + "objectFilter": "(context.type=entaxy.runtime.connector)" + }, + { + "processor": "xslt", + "source": "entaxy-services.xslt", + "objectFilter": "(context.type=entaxy.runtime.service)" + }, + { + "processor": "xslt", + "source": "entaxy-routes.xslt", + "objectFilter": "(context.type=entaxy.runtime.route)" + } + + ] + }, + { + "root": "connector-selector.xsd", + "namespace": "http://www.entaxy.ru/schemas/entaxy-mediators/1.0", + "prefix": "m", + "isPublic": true, + "objectFilter": "(&(context.type=entaxy.runtime.profile)(context.fieldName=connector-selector))", + "transform": [ + { + "processor": "xslt", + "source": "connector-selector.xslt", + "objectFilter": "" + } + ], + "uiDescriptor": "connector-selector.json" + }, + { + "root": "entaxy-mediators.xsd", + "namespace": "http://www.entaxy.ru/schemas/entaxy-mediators/1.0", + "prefix": "m", + "isPublic": true, + "objectFilter": "", + "transform": [ + { + "processor": "xslt", + "source": "entaxy-mediators.xslt", + "objectFilter": "" + } + ], + "uiDescriptor": "entaxy-mediators.json" + }, + { + "root": "rest-service-components.xsd", + "namespace": "http://www.entaxy.ru/schemas/entaxy-mediators/1.0", + "prefix": "m", + "isPublic": true, + "objectFilter": "(&(|(context.type=entaxy.runtime.service)(context.type=entaxy.runtime.connector))(context.factory.typeinfo.serviceType=REST))", + "transform": [ + { + "processor": "xslt", + "source": "rest-service-components.xslt", + "objectFilter": "" + } + ], + "uiDescriptor": "rest-service-components.json" + }, + { + "root": "soap-service-components.xsd", + "namespace": "http://www.entaxy.ru/schemas/entaxy-mediators/1.0", + "prefix": "m", + "isPublic": true, + "objectFilter": "(&(|(context.type=entaxy.runtime.service)(context.type=entaxy.runtime.connector))(context.factory.typeinfo.serviceType=SOAP))", + "transform": [ + { + "processor": "xslt", + "source": "soap-service-components.xslt", + "objectFilter": "" + } + ], + "uiDescriptor": "soap-service-components.json" + } + ] +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.json new file mode 100644 index 00000000..cab00fd8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.json @@ -0,0 +1,174 @@ +{ + "m:operation-router": { + "topChild": true, + "children": [ + "m:operation", + "m:unknown-operation" + ] + }, + "m:operation": { + "attrs": { + "name": null + }, + "children": [ + "onException", + "when", + "onCompletion", + "intercept", + "interceptFrom", + "interceptSendToEndpoint", + "to", + "toD", + "route", + "aggregate", + "bean", + "doCatch", + "choice", + "otherwise", + "circuitBreaker", + "claimCheck", + "convertBodyTo", + "delay", + "dynamicRouter", + "enrich", + "filter", + "doFinally", + "idempotentConsumer", + "inOnly", + "inOut", + "loadBalance", + "log", + "loop", + "marshal", + "multicast", + "onFallback", + "pipeline", + "policy", + "pollEnrich", + "process", + "recipientList", + "removeHeader", + "removeHeaders", + "removeProperties", + "removeProperty", + "resequence", + "rollback", + "routingSlip", + "saga", + "sample", + "script", + "setBody", + "setExchangePattern", + "setHeader", + "setProperty", + "sort", + "split", + "step", + "stop", + "threads", + "throttle", + "throwException", + "transacted", + "transform", + "doTry", + "unmarshal", + "validate", + "whenSkipSendToEndpoint", + "wireTap", + "serviceCall", + "m:standard-router", + "m:set-destination", + "m:default-destination", + "m:prefer-connector", + "m:next-route", + "m:respond", + "m:xslt", + "m:xslt-xalan", + "m:atlasmap", + "m:read-secret", + "m:to-connection", + "m:entaxy-trace", + "m:call-route", + "m:set-log-key", + "m:log" + ] + }, + "m:unknown-operation": { + "children": [ + "onException", + "when", + "onCompletion", + "intercept", + "interceptFrom", + "interceptSendToEndpoint", + "to", + "toD", + "route", + "aggregate", + "bean", + "doCatch", + "choice", + "otherwise", + "circuitBreaker", + "claimCheck", + "convertBodyTo", + "delay", + "dynamicRouter", + "enrich", + "filter", + "doFinally", + "idempotentConsumer", + "inOnly", + "inOut", + "loadBalance", + "log", + "loop", + "marshal", + "multicast", + "onFallback", + "pipeline", + "policy", + "pollEnrich", + "process", + "recipientList", + "removeHeader", + "removeHeaders", + "removeProperties", + "removeProperty", + "resequence", + "rollback", + "routingSlip", + "saga", + "sample", + "script", + "setBody", + "setExchangePattern", + "setHeader", + "setProperty", + "sort", + "split", + "step", + "stop", + "threads", + "throttle", + "throwException", + "transacted", + "transform", + "doTry", + "unmarshal", + "validate", + "whenSkipSendToEndpoint", + "wireTap", + "serviceCall" + ] + }, + "m:service-connector": { + "topChild": true, + "attrs": { + "direction": [ + "in", + "out" + ] + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.xsd new file mode 100644 index 00000000..0d8dbbcf --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.xsd @@ -0,0 +1,106 @@ + + + + + + Comment describing your root element + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.xslt new file mode 100644 index 00000000..55f0a105 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/rest-service-components.xslt @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + ${headers.operationName} == '' + + + + + + + + + + + + + + + + + + + + + + ${headers.NTX_targetConnector} != null + + ${headers.NTX_targetConnector} + + + + + + + + + + + + + + + + m:service-connector element is only applicable for protected services + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.json new file mode 100644 index 00000000..cab00fd8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.json @@ -0,0 +1,174 @@ +{ + "m:operation-router": { + "topChild": true, + "children": [ + "m:operation", + "m:unknown-operation" + ] + }, + "m:operation": { + "attrs": { + "name": null + }, + "children": [ + "onException", + "when", + "onCompletion", + "intercept", + "interceptFrom", + "interceptSendToEndpoint", + "to", + "toD", + "route", + "aggregate", + "bean", + "doCatch", + "choice", + "otherwise", + "circuitBreaker", + "claimCheck", + "convertBodyTo", + "delay", + "dynamicRouter", + "enrich", + "filter", + "doFinally", + "idempotentConsumer", + "inOnly", + "inOut", + "loadBalance", + "log", + "loop", + "marshal", + "multicast", + "onFallback", + "pipeline", + "policy", + "pollEnrich", + "process", + "recipientList", + "removeHeader", + "removeHeaders", + "removeProperties", + "removeProperty", + "resequence", + "rollback", + "routingSlip", + "saga", + "sample", + "script", + "setBody", + "setExchangePattern", + "setHeader", + "setProperty", + "sort", + "split", + "step", + "stop", + "threads", + "throttle", + "throwException", + "transacted", + "transform", + "doTry", + "unmarshal", + "validate", + "whenSkipSendToEndpoint", + "wireTap", + "serviceCall", + "m:standard-router", + "m:set-destination", + "m:default-destination", + "m:prefer-connector", + "m:next-route", + "m:respond", + "m:xslt", + "m:xslt-xalan", + "m:atlasmap", + "m:read-secret", + "m:to-connection", + "m:entaxy-trace", + "m:call-route", + "m:set-log-key", + "m:log" + ] + }, + "m:unknown-operation": { + "children": [ + "onException", + "when", + "onCompletion", + "intercept", + "interceptFrom", + "interceptSendToEndpoint", + "to", + "toD", + "route", + "aggregate", + "bean", + "doCatch", + "choice", + "otherwise", + "circuitBreaker", + "claimCheck", + "convertBodyTo", + "delay", + "dynamicRouter", + "enrich", + "filter", + "doFinally", + "idempotentConsumer", + "inOnly", + "inOut", + "loadBalance", + "log", + "loop", + "marshal", + "multicast", + "onFallback", + "pipeline", + "policy", + "pollEnrich", + "process", + "recipientList", + "removeHeader", + "removeHeaders", + "removeProperties", + "removeProperty", + "resequence", + "rollback", + "routingSlip", + "saga", + "sample", + "script", + "setBody", + "setExchangePattern", + "setHeader", + "setProperty", + "sort", + "split", + "step", + "stop", + "threads", + "throttle", + "throwException", + "transacted", + "transform", + "doTry", + "unmarshal", + "validate", + "whenSkipSendToEndpoint", + "wireTap", + "serviceCall" + ] + }, + "m:service-connector": { + "topChild": true, + "attrs": { + "direction": [ + "in", + "out" + ] + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.xsd b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.xsd new file mode 100644 index 00000000..0d8dbbcf --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.xsd @@ -0,0 +1,106 @@ + + + + + + Comment describing your root element + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.xslt b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.xslt new file mode 100644 index 00000000..b3ec53f6 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/component-library/entaxy-main/soap-service-components.xslt @@ -0,0 +1,98 @@ + + + + + + + + + + + + + + + + + + + + + + ${headers.operationName} == '' + + + + + + + + + + + + + + + + + + + + + + ${headers.NTX_targetConnector} != null + + ${headers.NTX_targetConnector} + + + + + + + + + + + + + + + + m:service-connector element is only applicable for protected services + + + + + + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/extensions/objectproducer/merge/config/BlueprintMergeProcessor.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/extensions/objectproducer/merge/config/BlueprintMergeProcessor.json new file mode 100644 index 00000000..4afaa97b --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/extensions/objectproducer/merge/config/BlueprintMergeProcessor.json @@ -0,0 +1,46 @@ +{ + "bean:http://www.osgi.org/xmlns/blueprint/v1.0.0": { + "targetNodeName": "##root", + "targetNodeNamespace": "http://www.osgi.org/xmlns/blueprint/v1.0.0", + "position": "inside_first", + "unique": ["id"], + "conflict": "ignore" /*[ignore, replace]*/ + }, + "bean:http://camel.apache.org/schema/blueprint": { + "conflict": "ignore" + }, + "route-container": { + "isTransparent": true + }, + "route:http://camel.apache.org/schema/blueprint": { + "recoursive": true, + "targetNodeName": "camelContext", + "unique": ["id"], + "position": "inside_last", + "createTargetNode": true, + "targetNodeXML": "", + "conflicts": ["merge", "replace"], + "childrenOrder": [ + "description:http://camel.apache.org/schema/blueprint", + "from:http://camel.apache.org/schema/blueprint", + "inputType:http://camel.apache.org/schema/blueprint", + "outputType:http://camel.apache.org/schema/blueprint", + "*", + "routeProperty:http://camel.apache.org/schema/blueprint" + ] + }, + "aggregate:http://camel.apache.org/schema/blueprint": { + "recoursive": true, + "unique": ["id"], + "position": "inside_last", + "conflicts": ["merge", "replace"], + "childrenOrder": [ + "correlationExpression:http://camel.apache.org/schema/blueprint", + "completionPredicate:http://camel.apache.org/schema/blueprint", + "completionTimeoutExpression:http://camel.apache.org/schema/blueprint", + "completionSizeExpression:http://camel.apache.org/schema/blueprint", + "optimisticLockRetryPolicy:http://camel.apache.org/schema/blueprint", + "*" + ] + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/extensions/objectproducer/producer/config.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/extensions/objectproducer/producer/config.json new file mode 100644 index 00000000..10c11dae --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/extensions/objectproducer/producer/config.json @@ -0,0 +1,9 @@ +{ + "supportedTypes": [ + "entaxy.runtime.route", + "entaxy.runtime.route.*", + "entaxy.runtime.route-container", + "entaxy.runtime.route-library", + "entaxy.runtime.camel-model" + ] +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-component.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-component.json new file mode 100644 index 00000000..5308a9d7 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-component.json @@ -0,0 +1,14 @@ +{ + "factory": { + "id": "abstract-camel-component", + "type": "entaxy.runtime.camel-component", + "description": "abstract-camel-component", + "isAbstract": true, + "parent": "abstract-camel-item", + "label": "", + "category": "" + }, + "entaxy.runtime.camel-component": {}, + "fields": {}, + "outputs": {} +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-item.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-item.json new file mode 100644 index 00000000..fea13f67 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-item.json @@ -0,0 +1,14 @@ +{ + "factory": { + "id": "abstract-camel-item", + "type": "entaxy.runtime.camel.item", + "description": "", + "isAbstract": true, + "parent": "base-object", + "label": "", + "category": "" + }, + "entaxy.runtime.camel.item": {}, + "fields": {}, + "outputs": {} +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-model.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-model.json new file mode 100644 index 00000000..c3d30f19 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/abstract-camel-model.json @@ -0,0 +1,14 @@ +{ + "factory": { + "id": "abstract-camel-model", + "type": "entaxy.runtime.camel-model", + "description": "", + "isAbstract": false, + "parent": "abstract-camel-item", + "label": "", + "category": "" + }, + "entaxy.runtime.camel-model": {}, + "fields": {}, + "outputs": {} +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/components/camel-quartz.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/components/camel-quartz.json new file mode 100644 index 00000000..d29c6b5a --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/components/camel-quartz.json @@ -0,0 +1,1299 @@ +{ + "factory": { + "id": "camel-quartz", + "type": "entaxy.runtime.camel-component", + "isAbstract": true, + "parent": "abstract-camel-component", + "category": "", + "camelOriginComponent": "quartz", + "label": "scheduling", + "description": "Schedule sending of messages using the Quartz 2.x scheduler.", + "camelOrigin": "camel-quartz", + "camelOriginJavaType": "org.apache.camel.component.quartz.QuartzComponent" + }, + "entaxy.runtime.camel-component": { + }, + "fields": { + "bridgeErrorHandler": { + "displayName": "Bridge Error Handler", + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. For more details see Entaxy docs and Camel docs", + "label": "consumer", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "enableJmx": { + "displayName": "Enable Jmx", + "description": "Whether to enable Quartz JMX which allows to manage the Quartz scheduler from JMX. This options is default true For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "prefixInstanceName": { + "displayName": "Prefix Instance Name", + "description": "Whether to prefix the Quartz Scheduler instance name with the CamelContext name. This is enabled by default, to let each CamelContext use its own Quartz scheduler instance by default. You can set this option to false to reuse Quartz scheduler instances between multiple CamelContext\u0027s. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "prefixJobNameWithEndpointId": { + "displayName": "Prefix Job Name With Endpoint Id", + "description": "Whether to prefix the quartz job with the endpoint id. This option is default false. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "properties": { + "displayName": "Properties", + "description": "Properties to configure the Quartz scheduler. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "object", + "kind": "property", + "required": false, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map", + "deprecated": false + } + }, + "propertiesFile": { + "displayName": "Properties File", + "description": "File name of the properties to load from the classpath For more details see Entaxy docs and Camel docs", + "label": "", + "type": "string", + "kind": "property", + "required": false, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "propertiesRef": { + "displayName": "Properties Ref", + "description": "References to an existing Properties or Map to lookup in the registry to use for configuring quartz. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "string", + "kind": "property", + "required": false, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "basicPropertyBinding": { + "displayName": "Basic Property Binding", + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "scheduler": { + "displayName": "Scheduler", + "description": "To use the custom configured Quartz scheduler, instead of creating a new Scheduler. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "object", + "kind": "property", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.quartz.Scheduler", + "deprecated": false + } + }, + "schedulerFactory": { + "displayName": "Scheduler Factory", + "description": "To use the custom SchedulerFactory which is used to create the Scheduler. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "object", + "kind": "property", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.quartz.SchedulerFactory", + "deprecated": false + } + }, + "autoStartScheduler": { + "displayName": "Auto Start Scheduler", + "description": "Whether or not the scheduler should be auto started. This options is default true For more details see Entaxy docs and Camel docs", + "label": "scheduler", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "scheduler", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "interruptJobsOnShutdown": { + "displayName": "Interrupt Jobs On Shutdown", + "description": "Whether to interrupt jobs on shutdown which forces the scheduler to shutdown quicker and attempt to interrupt any running jobs. If this is enabled then any running jobs can fail due to being interrupted. For more details see Entaxy docs and Camel docs", + "label": "scheduler", + "type": "boolean", + "kind": "property", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "scheduler", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "startDelayedSeconds": { + "displayName": "Start Delayed Seconds", + "description": "Seconds to wait before starting the quartz scheduler. For more details see Entaxy docs and Camel docs", + "label": "scheduler", + "type": "number", + "required": false, + "hidden": false, + "group": "scheduler", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "int", + "deprecated": false + }, + "new": { + "javaType": "int", + "deprecated": false + } + } + }, + "groupName": { + "displayName": "Group Name", + "description": "The quartz group name to use. The combination of group name and timer name should be unique. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "string", + "kind": "path", + "required": false, + "hidden": false, + "defaultValue": "Camel", + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "triggerName": { + "displayName": "Trigger Name", + "description": "The quartz timer name to use. The combination of group name and timer name should be unique. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "string", + "kind": "path", + "required": true, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "" + } + }, + "cron": { + "displayName": "Cron", + "description": "Specifies a cron expression to define when to trigger. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "deleteJob": { + "displayName": "Delete Job", + "description": "If set to true, then the trigger automatically delete when route stop. Else if set to false, it will remain in scheduler. When set to false, it will also mean user may reuse pre-configured trigger with camel Uri. Just ensure the names match. Notice you cannot have both deleteJob and pauseJob set to true. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "durableJob": { + "displayName": "Durable Job", + "description": "Whether or not the job should remain stored after it is orphaned (no triggers point to it). For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "pauseJob": { + "displayName": "Pause Job", + "description": "If set to true, then the trigger automatically pauses when route stop. Else if set to false, it will remain in scheduler. When set to false, it will also mean user may reuse pre-configured trigger with camel Uri. Just ensure the names match. Notice you cannot have both deleteJob and pauseJob set to true. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "recoverableJob": { + "displayName": "Recoverable Job", + "description": "Instructs the scheduler whether or not the job should be re-executed if a \u0027recovery\u0027 or \u0027fail-over\u0027 situation is encountered. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "stateful": { + "displayName": "Stateful", + "description": "Uses a Quartz PersistJobDataAfterExecution and DisallowConcurrentExecution instead of the default job. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "exceptionHandler": { + "displayName": "Exception Handler", + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. For more details see Entaxy docs and Camel docs", + "label": "consumer,advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "consumer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false + } + }, + "exchangePattern": { + "displayName": "Exchange Pattern", + "description": "Sets the exchange pattern when the consumer creates an exchange. For more details see Entaxy docs and Camel docs", + "label": "consumer,advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "consumer (advanced)", + "@TYPEINFO": { + "type": "enum", + "values": [ + "InOnly", + "InOut", + "InOptionalOut" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.ExchangePattern", + "deprecated": false + } + }, + "customCalendar": { + "displayName": "Custom Calendar", + "description": "Specifies a custom calendar to avoid specific range of date For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.quartz.Calendar", + "deprecated": false + } + }, + "jobParameters": { + "displayName": "Job Parameters", + "description": "To configure additional options on the job. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "job.", + "multiValue": true, + "deprecated": false + } + }, + "synchronous": { + "displayName": "Synchronous", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "triggerParameters": { + "displayName": "Trigger Parameters", + "description": "To configure additional options on the trigger. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "trigger.", + "multiValue": true, + "deprecated": false + } + }, + "usingFixedCamelContextName": { + "displayName": "Using Fixed Camel Context Name", + "description": "If it is true, JobDataMap uses the CamelContext name directly to reference the CamelContext, if it is false, JobDataMap uses use the CamelContext management name which could be changed during the deploy time. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "fireNow": { + "displayName": "Fire Now", + "description": "If it is true will fire the trigger when the route is start when using SimpleTrigger. For more details see Entaxy docs and Camel docs", + "label": "scheduler", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "scheduler", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "triggerStartDelay": { + "displayName": "Trigger Start Delay", + "description": "In case of scheduler has already started, we want the trigger start slightly after current time to ensure endpoint is fully started before the job kicks in. For more details see Entaxy docs and Camel docs", + "label": "scheduler", + "type": "duration", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "500", + "group": "scheduler", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "hidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "component": { + "kind": "component", + "name": "quartz", + "title": "Quartz", + "description": "Schedule sending of messages using the Quartz 2.x scheduler.", + "deprecated": false, + "firstVersion": "2.12.0", + "label": "scheduling", + "javaType": "org.apache.camel.component.quartz.QuartzComponent", + "supportLevel": "Stable", + "groupId": "org.apache.camel", + "artifactId": "camel-quartz", + "version": "3.4.5-SNAPSHOT", + "scheme": "quartz", + "extendsScheme": "", + "syntax": "quartz:groupName/triggerName", + "async": false, + "consumerOnly": true, + "producerOnly": false, + "lenientProperties": false + }, + "componentProperties": { + "bridgeErrorHandler": { + "kind": "property", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "enableJmx": { + "kind": "property", + "displayName": "Enable Jmx", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether to enable Quartz JMX which allows to manage the Quartz scheduler from JMX. This options is default true" + }, + "prefixInstanceName": { + "kind": "property", + "displayName": "Prefix Instance Name", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether to prefix the Quartz Scheduler instance name with the CamelContext name. This is enabled by default, to let each CamelContext use its own Quartz scheduler instance by default. You can set this option to false to reuse Quartz scheduler instances between multiple CamelContext\u0027s." + }, + "prefixJobNameWithEndpointId": { + "kind": "property", + "displayName": "Prefix Job Name With Endpoint Id", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether to prefix the quartz job with the endpoint id. This option is default false." + }, + "properties": { + "kind": "property", + "displayName": "Properties", + "group": "consumer", + "label": "", + "required": false, + "type": "object", + "javaType": "java.util.Map", + "deprecated": false, + "secret": false, + "description": "Properties to configure the Quartz scheduler." + }, + "propertiesFile": { + "kind": "property", + "displayName": "Properties File", + "group": "consumer", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "File name of the properties to load from the classpath" + }, + "propertiesRef": { + "kind": "property", + "displayName": "Properties Ref", + "group": "consumer", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "References to an existing Properties or Map to lookup in the registry to use for configuring quartz." + }, + "basicPropertyBinding": { + "kind": "property", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "scheduler": { + "kind": "property", + "displayName": "Scheduler", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.quartz.Scheduler", + "deprecated": false, + "secret": false, + "description": "To use the custom configured Quartz scheduler, instead of creating a new Scheduler." + }, + "schedulerFactory": { + "kind": "property", + "displayName": "Scheduler Factory", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.quartz.SchedulerFactory", + "deprecated": false, + "secret": false, + "description": "To use the custom SchedulerFactory which is used to create the Scheduler." + }, + "autoStartScheduler": { + "kind": "property", + "displayName": "Auto Start Scheduler", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether or not the scheduler should be auto started. This options is default true" + }, + "interruptJobsOnShutdown": { + "kind": "property", + "displayName": "Interrupt Jobs On Shutdown", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether to interrupt jobs on shutdown which forces the scheduler to shutdown quicker and attempt to interrupt any running jobs. If this is enabled then any running jobs can fail due to being interrupted." + }, + "startDelayedSeconds": { + "kind": "property", + "displayName": "Start Delayed Seconds", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "Seconds to wait before starting the quartz scheduler." + } + }, + "properties": { + "groupName": { + "kind": "path", + "displayName": "Group Name", + "group": "consumer", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "defaultValue": "Camel", + "description": "The quartz group name to use. The combination of group name and timer name should be unique." + }, + "triggerName": { + "kind": "path", + "displayName": "Trigger Name", + "group": "consumer", + "label": "", + "required": true, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "", + "secret": false, + "description": "The quartz timer name to use. The combination of group name and timer name should be unique." + }, + "bridgeErrorHandler": { + "kind": "parameter", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "cron": { + "kind": "parameter", + "displayName": "Cron", + "group": "consumer", + "label": "", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Specifies a cron expression to define when to trigger." + }, + "deleteJob": { + "kind": "parameter", + "displayName": "Delete Job", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "If set to true, then the trigger automatically delete when route stop. Else if set to false, it will remain in scheduler. When set to false, it will also mean user may reuse pre-configured trigger with camel Uri. Just ensure the names match. Notice you cannot have both deleteJob and pauseJob set to true." + }, + "durableJob": { + "kind": "parameter", + "displayName": "Durable Job", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether or not the job should remain stored after it is orphaned (no triggers point to it)." + }, + "pauseJob": { + "kind": "parameter", + "displayName": "Pause Job", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If set to true, then the trigger automatically pauses when route stop. Else if set to false, it will remain in scheduler. When set to false, it will also mean user may reuse pre-configured trigger with camel Uri. Just ensure the names match. Notice you cannot have both deleteJob and pauseJob set to true." + }, + "recoverableJob": { + "kind": "parameter", + "displayName": "Recoverable Job", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Instructs the scheduler whether or not the job should be re-executed if a \u0027recovery\u0027 or \u0027fail-over\u0027 situation is encountered." + }, + "stateful": { + "kind": "parameter", + "displayName": "Stateful", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Uses a Quartz PersistJobDataAfterExecution and DisallowConcurrentExecution instead of the default job." + }, + "exceptionHandler": { + "kind": "parameter", + "displayName": "Exception Handler", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false, + "secret": false, + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "exchangePattern": { + "kind": "parameter", + "displayName": "Exchange Pattern", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.ExchangePattern", + "enum": [ + "InOnly", + "InOut", + "InOptionalOut" + ], + "deprecated": false, + "secret": false, + "description": "Sets the exchange pattern when the consumer creates an exchange." + }, + "basicPropertyBinding": { + "kind": "parameter", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "customCalendar": { + "kind": "parameter", + "displayName": "Custom Calendar", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "org.quartz.Calendar", + "deprecated": false, + "secret": false, + "description": "Specifies a custom calendar to avoid specific range of date" + }, + "jobParameters": { + "kind": "parameter", + "displayName": "Job Parameters", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "job.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "To configure additional options on the job." + }, + "prefixJobNameWithEndpointId": { + "kind": "parameter", + "displayName": "Prefix Job Name With Endpoint Id", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the job name should be prefixed with endpoint id" + }, + "synchronous": { + "kind": "parameter", + "displayName": "Synchronous", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported)." + }, + "triggerParameters": { + "kind": "parameter", + "displayName": "Trigger Parameters", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Map\u003cjava.lang.String, java.lang.Object\u003e", + "prefix": "trigger.", + "multiValue": true, + "deprecated": false, + "secret": false, + "description": "To configure additional options on the trigger." + }, + "usingFixedCamelContextName": { + "kind": "parameter", + "displayName": "Using Fixed Camel Context Name", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If it is true, JobDataMap uses the CamelContext name directly to reference the CamelContext, if it is false, JobDataMap uses use the CamelContext management name which could be changed during the deploy time." + }, + "autoStartScheduler": { + "kind": "parameter", + "displayName": "Auto Start Scheduler", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether or not the scheduler should be auto started." + }, + "fireNow": { + "kind": "parameter", + "displayName": "Fire Now", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If it is true will fire the trigger when the route is start when using SimpleTrigger." + }, + "startDelayedSeconds": { + "kind": "parameter", + "displayName": "Start Delayed Seconds", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "integer", + "javaType": "int", + "deprecated": false, + "secret": false, + "description": "Seconds to wait before starting the quartz scheduler." + }, + "triggerStartDelay": { + "kind": "parameter", + "displayName": "Trigger Start Delay", + "group": "scheduler", + "label": "scheduler", + "required": false, + "type": "duration", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "500", + "description": "In case of scheduler has already started, we want the trigger start slightly after current time to ensure endpoint is fully started before the job kicks in." + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/components/camel-timer.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/components/camel-timer.json new file mode 100644 index 00000000..0dd7f47a --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/components/camel-timer.json @@ -0,0 +1,804 @@ +{ + "factory": { + "id": "camel-timer", + "type": "entaxy.runtime.camel-component", + "isAbstract": false, + "parent": "abstract-camel-component", + "category": "", + "camelOriginComponent": "timer", + "label": "core,scheduling", + "description": "Generate messages in specified intervals using java.util.Timer.", + "camelOrigin": "camel-timer", + "camelOriginJavaType": "org.apache.camel.component.timer.TimerComponent" + }, + "entaxy.runtime.camel-component": {}, + "fields": { + "bridgeErrorHandler": { + "displayName": "Bridge Error Handler", + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.", + "label": "consumer", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "basicPropertyBinding": { + "displayName": "Basic Property Binding", + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities", + "label": "advanced", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "timerName": { + "displayName": "Timer Name", + "description": "The name of the timer", + "label": "", + "type": "string", + "kind": "path", + "required": true, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "" + } + }, + "delay": { + "displayName": "Delay", + "description": "Delay before first event is triggered.", + "label": "", + "type": "duration", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "1s", + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "fixedRate": { + "displayName": "Fixed Rate", + "description": "Events take place at approximately regular intervals, separated by the specified period.", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "includeMetadata": { + "displayName": "Include Metadata", + "description": "Whether to include metadata in the exchange such as fired time, timer name, timer count etc. This information is default included.", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "period": { + "displayName": "Period", + "description": "If greater than 0, generate periodic events every period.", + "label": "", + "type": "duration", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "1s", + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "repeatCount": { + "displayName": "Repeat Count", + "description": "Specifies a maximum limit of number of fires. So if you set it to 1, the timer will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.", + "label": "", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": 0, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "exceptionHandler": { + "displayName": "Exception Handler", + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.", + "label": "consumer,advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "consumer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false + } + }, + "exchangePattern": { + "displayName": "Exchange Pattern", + "description": "Sets the exchange pattern when the consumer creates an exchange.", + "label": "consumer,advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "consumer (advanced)", + "@TYPEINFO": { + "type": "enum", + "values": [ + "InOnly", + "InOut", + "InOptionalOut" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.ExchangePattern", + "deprecated": false + } + }, + "daemon": { + "displayName": "Daemon", + "description": "Specifies whether or not the thread associated with the timer endpoint runs as a daemon. The default value is true.", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "pattern": { + "displayName": "Pattern", + "description": "Allows you to specify a custom Date pattern to use for setting the time option using URI syntax.", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "synchronous": { + "displayName": "Synchronous", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported).", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "time": { + "displayName": "Time", + "description": "A java.util.Date the first event should be generated. If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss or yyyy-MM-dd\u0027T\u0027HH:mm:ss.", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Date", + "deprecated": false + } + }, + "timer": { + "displayName": "Timer", + "description": "To use a custom Timer", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Timer", + "deprecated": false + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "hidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "component": { + "kind": "component", + "name": "timer", + "title": "Timer", + "description": "Generate messages in specified intervals using java.util.Timer.", + "deprecated": false, + "firstVersion": "1.0.0", + "label": "core,scheduling", + "javaType": "org.apache.camel.component.timer.TimerComponent", + "supportLevel": "Stable", + "groupId": "org.apache.camel", + "artifactId": "camel-timer", + "version": "3.4.5", + "scheme": "timer", + "extendsScheme": "", + "syntax": "timer:timerName", + "async": false, + "consumerOnly": true, + "producerOnly": false, + "lenientProperties": false + }, + "componentProperties": { + "bridgeErrorHandler": { + "kind": "property", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "basicPropertyBinding": { + "kind": "property", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + } + }, + "properties": { + "timerName": { + "kind": "path", + "displayName": "Timer Name", + "group": "consumer", + "label": "", + "required": true, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "", + "secret": false, + "description": "The name of the timer" + }, + "bridgeErrorHandler": { + "kind": "parameter", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "delay": { + "kind": "parameter", + "displayName": "Delay", + "group": "consumer", + "label": "", + "required": false, + "type": "duration", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1s", + "description": "Delay before first event is triggered." + }, + "fixedRate": { + "kind": "parameter", + "displayName": "Fixed Rate", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Events take place at approximately regular intervals, separated by the specified period." + }, + "includeMetadata": { + "kind": "parameter", + "displayName": "Include Metadata", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether to include metadata in the exchange such as fired time, timer name, timer count etc. This information is default included." + }, + "period": { + "kind": "parameter", + "displayName": "Period", + "group": "consumer", + "label": "", + "required": false, + "type": "duration", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1s", + "description": "If greater than 0, generate periodic events every period." + }, + "repeatCount": { + "kind": "parameter", + "displayName": "Repeat Count", + "group": "consumer", + "label": "", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "0", + "description": "Specifies a maximum limit of number of fires. So if you set it to 1, the timer will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever." + }, + "exceptionHandler": { + "kind": "parameter", + "displayName": "Exception Handler", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false, + "secret": false, + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "exchangePattern": { + "kind": "parameter", + "displayName": "Exchange Pattern", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.ExchangePattern", + "enum": [ + "InOnly", + "InOut", + "InOptionalOut" + ], + "deprecated": false, + "secret": false, + "description": "Sets the exchange pattern when the consumer creates an exchange." + }, + "basicPropertyBinding": { + "kind": "parameter", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "daemon": { + "kind": "parameter", + "displayName": "Daemon", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Specifies whether or not the thread associated with the timer endpoint runs as a daemon. The default value is true." + }, + "pattern": { + "kind": "parameter", + "displayName": "Pattern", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Allows you to specify a custom Date pattern to use for setting the time option using URI syntax." + }, + "synchronous": { + "kind": "parameter", + "displayName": "Synchronous", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported)." + }, + "time": { + "kind": "parameter", + "displayName": "Time", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "string", + "javaType": "java.util.Date", + "deprecated": false, + "secret": false, + "description": "A java.util.Date the first event should be generated. If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss or yyyy-MM-dd\u0027T\u0027HH:mm:ss." + }, + "timer": { + "kind": "parameter", + "displayName": "Timer", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Timer", + "deprecated": false, + "secret": false, + "description": "To use a custom Timer" + } + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-aggregate.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-aggregate.json new file mode 100644 index 00000000..80342f99 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-aggregate.json @@ -0,0 +1,1311 @@ +{ + "factory": { + "id": "model-aggregate", + "type": "entaxy.runtime.camel-model", + "isAbstract": false, + "parent": "abstract-camel-model", + "category": "", + "camelOriginComponent": "aggregate", + "label": "eip,routing", + "description": "Aggregates many messages into a single message", + "camelOriginJavaType": "org.apache.camel.model.AggregateDefinition" + }, + "entaxy.runtime.camel-model": { + }, + "fields": { + "correlationExpression": { + "@PUBLISH_UNRESOLVED": "object", + "isRef": true, + "isRefByValueOnly": true, + "refField": "##_CONTENT", + "resolveAlways": true, + "refExtended": { + "@SKIP_MERGE": true + }, + "displayName": "Correlation Expression", + "description": "The expression used to calculate the correlation key to use for aggregation. The Exchange which has the same correlation key is aggregated together. If the correlation key could not be evaluated an Exception is thrown. You can disable this by using the ignoreBadCorrelationKeys option. For more details see Entaxy docs and Camel docs", + "type": "entaxy.runtime.route.component.expression", + "objectScope": "private", + "objectFactory": { + "filter": "(&(type=entaxy.runtime.route.component.expression)(isAbstract=false))" + }, + "kind": "expression", + "required": true, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false + }, + "@TYPEINFO": { + "innerObject": true + } + }, + "completionPredicate": { + "@PUBLISH_UNRESOLVED": "object", + "displayName": "Completion Predicate", + "description": "A Predicate to indicate when an aggregated exchange is complete. If this is not specified and the AggregationStrategy object implements Predicate, the aggregationStrategy object will be used as the completionPredicate. For more details see Entaxy docs and Camel docs", + "type": "entaxy.runtime.route.component.expression", + "objectScope": "private", + "objectFactory": { + "filter": "(&(type=entaxy.runtime.route.component.expression)(isAbstract=false))" + }, + "isRef": true, + "isRefByValueOnly": true, + "refField": "##_CONTENT", + "resolveAlways": true, + "refExtended": { + "@SKIP_MERGE": true + }, + "kind": "expression", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false, + "asPredicate": true + }, + "@TYPEINFO": { + "innerObject": true + } + }, + "completionTimeoutExpression": { + "displayName": "Completion Timeout Expression", + "description": "Time in millis that an aggregated exchange should be inactive before its complete (timeout). This option can be set as either a fixed value or using an Expression which allows you to evaluate a timeout dynamically - will use Long as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. You cannot use this option together with completionInterval, only one of the two can be used. By default the timeout checker runs every second, you can use the completionTimeoutCheckerInterval option to configure how frequently to run the checker. The timeout is an approximation and there is no guarantee that the a timeout is triggered exactly after the timeout value. It is not recommended to use very low timeout values or checker intervals. For more details see Entaxy docs and Camel docs", + "type": "entaxy.runtime.route.component.expression", + "objectScope": "private", + "objectFactory": { + "filter": "(&(type=entaxy.runtime.route.component.expression)(isAbstract=false))" + }, + "isRef": true, + "isRefByValueOnly": true, + "refField": "##_CONTENT", + "resolveAlways": true, + "refExtended": { + "@SKIP_MERGE": true + }, + "kind": "expression", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false + }, + "@TYPEINFO": { + "innerObject": true + } + }, + "completionSizeExpression": { + "@PUBLISH_UNRESOLVED": "object", + "displayName": "Completion Size Expression", + "description": "Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an Expression which allows you to evaluate a size dynamically - will use Integer as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. For more details see Entaxy docs and Camel docs", + "type": "entaxy.runtime.route.component.expression", + "objectScope": "private", + "objectFactory": { + "filter": "(&(type=entaxy.runtime.route.component.expression)(isAbstract=false))" + }, + "isRef": true, + "isRefByValueOnly": true, + "refField": "##_CONTENT", + "resolveAlways": true, + "refExtended": { + "@SKIP_MERGE": true + }, + "kind": "expression", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false + }, + "@TYPEINFO": { + "innerObject": true + } + }, + "optimisticLockRetryPolicy": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Optimistic Lock Retry Policy", + "description": "Allows to configure retry settings when using optimistic locking. For more details see Entaxy docs and Camel docs", + "type": "object", + "kind": "element", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.model.OptimisticLockRetryPolicyDefinition", + "deprecated": false + } + }, + "parallelProcessing": { + "displayName": "Parallel Processing", + "description": "When aggregated are completed they are being send out of the aggregator. This option indicates whether or not Camel should use a thread pool with multiple threads for concurrency. If no custom thread pool has been specified then Camel creates a default pool with 10 concurrent threads. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "optimisticLocking": { + "displayName": "Optimistic Locking", + "description": "Turns on using optimistic locking, which requires the aggregationRepository being used, is supporting this by implementing org.apache.camel.spi.OptimisticLockingAggregationRepository . For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "executorServiceRef": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Executor Service Ref", + "description": "If using parallelProcessing you can specify a custom thread pool to be used. In fact also if you are not using parallelProcessing this custom thread pool is used to send out aggregated exchanges as well. For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "timeoutCheckerExecutorServiceRef": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Timeout Checker Executor Service Ref", + "description": "If using either of the completionTimeout, completionTimeoutExpression, or completionInterval options a background thread is created to check for the completion for every aggregator. Set this option to provide a custom thread pool to be used rather than creating a new thread for every aggregator. For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "aggregationRepositoryRef": { + "@PUBLISH_UNRESOLVED": "object", + "displayName": "Aggregation Repository Ref", + "description": "Sets the custom aggregate repository to use. Will by default use org.apache.camel.processor.aggregate.MemoryAggregationRepository For more details see Entaxy docs and Camel docs", + "type": "entaxy.runtime.route.component.aggregation.repository", + "objectScope": "private", + "objectFactory": { + "filter": "(&(type=entaxy.runtime.route.component.aggregation.repository)(isAbstract=false))" + }, + "isRef": true, + "isRefByValueOnly": false, + "refField": "##_CONTENT", + "resolveAlways": false, + "refExtended": { + "@SKIP_MERGE": false + }, + "kind": "attribute", + "required": true, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + }, + "@TYPEINFO": { + "innerObject": true + } + }, + "strategyRef": { + "@PUBLISH_UNRESOLVED": "object", + "displayName": "Strategy Ref", + "description": "A reference to lookup the AggregationStrategy in the Registry. Configuring an AggregationStrategy is required, and is used to merge the incoming Exchange with the existing already merged exchanges. At first call the oldExchange parameter is null. On subsequent invocations the oldExchange contains the merged exchanges and newExchange is of course the new incoming Exchange. For more details see Entaxy docs and Camel docs", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "kind": "attribute", + "required": true, + "isHidden": false, + "objectScope": "private", + "objectFactory": { + "filter": "(&(type=entaxy.runtime.route.component.aggregation.strategy)(isAbstract=false))" + }, + "@REF_CONFIG": { + "isRef": true, + "isRefByValueOnly": true, + "refField": "beanId", + "resolveAlways": true, + "refExtended": { + "@SKIP_MERGE": false + } + }, + "defaultValue": { + "factoryId": "aggregation-strategy-camel-grouped-body", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "scope": "private", + "refConfig": { + "isRefByValueOnly": true, + "refField": "beanId", + "resolveAlways": true, + "refExtended": { + "@SKIP_MERGE": false + } + } + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + }, + "@TYPEINFO": { + "innerObject": true + } + }, + "strategyMethodName": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Strategy Method Name", + "description": "This option can be used to explicit declare the method name to use, when using POJOs as the AggregationStrategy. For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "strategyMethodAllowNull": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Strategy Method Allow Null", + "description": "If this option is false then the aggregate method is not used for the very first aggregation. If this option is true then null values is used as the oldExchange (at the very first aggregation), when using POJOs as the AggregationStrategy. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": true, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "completionSize": { + "displayName": "Completion Size", + "description": "Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an Expression which allows you to evaluate a size dynamically - will use Integer as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. For more details see Entaxy docs and Camel docs", + "type": "number", + "kind": "attribute", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Integer", + "deprecated": false + } + }, + "completionInterval": { + "displayName": "Completion Interval", + "description": "A repeating period in millis by which the aggregator will complete all current aggregated exchanges. Camel has a background task which is triggered every period. You cannot use this option together with completionTimeout, only one of them can be used. For more details see Entaxy docs and Camel docs", + "type": "duration", + "kind": "attribute", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "completionTimeout": { + "displayName": "Completion Timeout", + "description": "Time in millis that an aggregated exchange should be inactive before its complete (timeout). This option can be set as either a fixed value or using an Expression which allows you to evaluate a timeout dynamically - will use Long as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. You cannot use this option together with completionInterval, only one of the two can be used. By default the timeout checker runs every second, you can use the completionTimeoutCheckerInterval option to configure how frequently to run the checker. The timeout is an approximation and there is no guarantee that the a timeout is triggered exactly after the timeout value. It is not recommended to use very low timeout values or checker intervals. For more details see Entaxy docs and Camel docs", + "type": "number", + "camel-type": "duration", + "kind": "attribute", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "completionTimeoutCheckerInterval": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Completion Timeout Checker Interval", + "description": "Interval in millis that is used by the background task that checks for timeouts ( org.apache.camel.TimeoutMap ). By default the timeout checker runs every second. The timeout is an approximation and there is no guarantee that the a timeout is triggered exactly after the timeout value. It is not recommended to use very low timeout values or checker intervals. For more details see Entaxy docs and Camel docs", + "type": "duration", + "kind": "attribute", + "required": false, + "isHidden": true, + "defaultValue": "1s", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "completionFromBatchConsumer": { + "displayName": "Completion From Batch Consumer", + "description": "Enables the batch completion mode where we aggregate from a org.apache.camel.BatchConsumer and aggregate the total number of exchanges the org.apache.camel.BatchConsumer has reported as total by checking the exchange property org.apache.camel.Exchange#BATCH_COMPLETE when its complete. This option cannot be used together with discardOnAggregationFailure. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "completionOnNewCorrelationGroup": { + "displayName": "Completion On New Correlation Group", + "description": "Enables completion on all previous groups when a new incoming correlation group. This can for example be used to complete groups with same correlation keys when they are in consecutive order. Notice when this is enabled then only 1 correlation group can be in progress as when a new correlation group starts, then the previous groups is forced completed. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "eagerCheckCompletion": { + "displayName": "Eager Check Completion", + "description": "Use eager completion checking which means that the completionPredicate will use the incoming Exchange. As opposed to without eager completion checking the completionPredicate will use the aggregated Exchange. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "ignoreInvalidCorrelationKeys": { + "displayName": "Ignore Invalid Correlation Keys", + "description": "If a correlation key cannot be successfully evaluated it will be ignored by logging a DEBUG and then just ignore the incoming Exchange. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "closeCorrelationKeyOnCompletion": { + "displayName": "Close Correlation Key On Completion", + "description": "Closes a correlation key when its complete. Any late received exchanges which has a correlation key that has been closed, it will be defined and a ClosedCorrelationKeyException is thrown. For more details see Entaxy docs and Camel docs", + "type": "number", + "kind": "attribute", + "required": false, + "isHidden": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Integer", + "deprecated": false + } + }, + "discardOnCompletionTimeout": { + "displayName": "Discard On Completion Timeout", + "description": "Discards the aggregated message on completion timeout. This means on timeout the aggregated message is dropped and not sent out of the aggregator. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "discardOnAggregationFailure": { + "displayName": "Discard On Aggregation Failure", + "description": "Discards the aggregated message when aggregation failed (an exception was thrown from AggregationStrategy . This means the partly aggregated message is dropped and not sent out of the aggregator. This option cannot be used together with completionFromBatchConsumer. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "forceCompletionOnStop": { + "displayName": "Force Completion On Stop", + "description": "Indicates to complete all current aggregated exchanges when the context is stopped For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "completeAllOnStop": { + "displayName": "Complete All On Stop", + "description": "Indicates to wait to complete all current and partial (pending) aggregated exchanges when the context is stopped. This also means that we will wait for all pending exchanges which are stored in the aggregation repository to complete so the repository is empty before we can stop. You may want to enable this when using the memory based aggregation repository that is memory based only, and do not store data on disk. When this option is enabled, then the aggregator is waiting to complete all those exchanges before its stopped, when stopping CamelContext or the route using it. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "required": false, + "isHidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false + } + }, + "aggregateControllerRef": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Aggregate Controller Ref", + "description": "To use a org.apache.camel.processor.aggregate.AggregateController to allow external sources to control this aggregator. For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "id": { + "@TO_REMOVE": true, + "displayName": "Id", + "description": "Sets the id of this node For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "_description": { + "@TO_REMOVE": true, + "displayName": "Description", + "description": "Sets the description of this node For more details see Entaxy docs and Camel docs", + "type": "object", + "kind": "element", + "required": false, + "isHidden": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.model.DescriptionDefinition", + "deprecated": false + } + }, + "aggregatorId": { + "type": "String", + "required": true, + "isHidden": true, + "defaultVlaue": { + "@CALCULATED": { + "expression": "${objectId}", + "lazy": false, + "resultType": "String" + } + } + } + }, + "outputs": { + "init": { + "fields": { + "aggregatorId": {}, + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property", + "attribute", + "expression" + ] + } + ] + } + } + ] + }, + "scopes": ["private", "public"] + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "IsHidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "model": { + "kind": "model", + "name": "aggregate", + "title": "Aggregate", + "description": "Aggregates many messages into a single message", + "deprecated": false, + "label": "eip,routing", + "javaType": "org.apache.camel.model.AggregateDefinition", + "input": true, + "output": false + }, + "properties": { + "correlationExpression": { + "kind": "expression", + "displayName": "Correlation Expression", + "required": true, + "type": "object", + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false, + "secret": false, + "description": "The expression used to calculate the correlation key to use for aggregation. The Exchange which has the same correlation key is aggregated together. If the correlation key could not be evaluated an Exception is thrown. You can disable this by using the ignoreBadCorrelationKeys option." + }, + "completionPredicate": { + "kind": "expression", + "displayName": "Completion Predicate", + "required": false, + "type": "object", + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false, + "secret": false, + "asPredicate": true, + "description": "A Predicate to indicate when an aggregated exchange is complete. If this is not specified and the AggregationStrategy object implements Predicate, the aggregationStrategy object will be used as the completionPredicate." + }, + "completionTimeoutExpression": { + "kind": "expression", + "displayName": "Completion Timeout Expression", + "required": false, + "type": "object", + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false, + "secret": false, + "description": "Time in millis that an aggregated exchange should be inactive before its complete (timeout). This option can be set as either a fixed value or using an Expression which allows you to evaluate a timeout dynamically - will use Long as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. You cannot use this option together with completionInterval, only one of the two can be used. By default the timeout checker runs every second, you can use the completionTimeoutCheckerInterval option to configure how frequently to run the checker. The timeout is an approximation and there is no guarantee that the a timeout is triggered exactly after the timeout value. It is not recommended to use very low timeout values or checker intervals." + }, + "completionSizeExpression": { + "kind": "expression", + "displayName": "Completion Size Expression", + "required": false, + "type": "object", + "javaType": "org.apache.camel.model.ExpressionSubElementDefinition", + "oneOf": [ + "constant", + "exchangeProperty", + "groovy", + "header", + "hl7terser", + "jsonpath", + "language", + "method", + "mvel", + "ognl", + "ref", + "simple", + "spel", + "tokenize", + "xpath", + "xquery", + "xtokenize" + ], + "deprecated": false, + "secret": false, + "description": "Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an Expression which allows you to evaluate a size dynamically - will use Integer as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0." + }, + "optimisticLockRetryPolicy": { + "kind": "element", + "displayName": "Optimistic Lock Retry Policy", + "required": false, + "type": "object", + "javaType": "org.apache.camel.model.OptimisticLockRetryPolicyDefinition", + "deprecated": false, + "secret": false, + "description": "Allows to configure retry settings when using optimistic locking." + }, + "parallelProcessing": { + "kind": "attribute", + "displayName": "Parallel Processing", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "When aggregated are completed they are being send out of the aggregator. This option indicates whether or not Camel should use a thread pool with multiple threads for concurrency. If no custom thread pool has been specified then Camel creates a default pool with 10 concurrent threads." + }, + "optimisticLocking": { + "kind": "attribute", + "displayName": "Optimistic Locking", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Turns on using optimistic locking, which requires the aggregationRepository being used, is supporting this by implementing org.apache.camel.spi.OptimisticLockingAggregationRepository ." + }, + "executorServiceRef": { + "kind": "attribute", + "displayName": "Executor Service Ref", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "If using parallelProcessing you can specify a custom thread pool to be used. In fact also if you are not using parallelProcessing this custom thread pool is used to send out aggregated exchanges as well." + }, + "timeoutCheckerExecutorServiceRef": { + "kind": "attribute", + "displayName": "Timeout Checker Executor Service Ref", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "If using either of the completionTimeout, completionTimeoutExpression, or completionInterval options a background thread is created to check for the completion for every aggregator. Set this option to provide a custom thread pool to be used rather than creating a new thread for every aggregator." + }, + "aggregationRepositoryRef": { + "kind": "attribute", + "displayName": "Aggregation Repository Ref", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the custom aggregate repository to use. Will by default use org.apache.camel.processor.aggregate.MemoryAggregationRepository" + }, + "strategyRef": { + "kind": "attribute", + "displayName": "Strategy Ref", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "A reference to lookup the AggregationStrategy in the Registry. Configuring an AggregationStrategy is required, and is used to merge the incoming Exchange with the existing already merged exchanges. At first call the oldExchange parameter is null. On subsequent invocations the oldExchange contains the merged exchanges and newExchange is of course the new incoming Exchange." + }, + "strategyMethodName": { + "kind": "attribute", + "displayName": "Strategy Method Name", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "This option can be used to explicit declare the method name to use, when using POJOs as the AggregationStrategy." + }, + "strategyMethodAllowNull": { + "kind": "attribute", + "displayName": "Strategy Method Allow Null", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If this option is false then the aggregate method is not used for the very first aggregation. If this option is true then null values is used as the oldExchange (at the very first aggregation), when using POJOs as the AggregationStrategy." + }, + "completionSize": { + "kind": "attribute", + "displayName": "Completion Size", + "required": false, + "type": "integer", + "javaType": "java.lang.Integer", + "deprecated": false, + "secret": false, + "description": "Number of messages aggregated before the aggregation is complete. This option can be set as either a fixed value or using an Expression which allows you to evaluate a size dynamically - will use Integer as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0." + }, + "completionInterval": { + "kind": "attribute", + "displayName": "Completion Interval", + "required": false, + "type": "duration", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "A repeating period in millis by which the aggregator will complete all current aggregated exchanges. Camel has a background task which is triggered every period. You cannot use this option together with completionTimeout, only one of them can be used." + }, + "completionTimeout": { + "kind": "attribute", + "displayName": "Completion Timeout", + "required": false, + "type": "duration", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Time in millis that an aggregated exchange should be inactive before its complete (timeout). This option can be set as either a fixed value or using an Expression which allows you to evaluate a timeout dynamically - will use Long as result. If both are set Camel will fallback to use the fixed value if the Expression result was null or 0. You cannot use this option together with completionInterval, only one of the two can be used. By default the timeout checker runs every second, you can use the completionTimeoutCheckerInterval option to configure how frequently to run the checker. The timeout is an approximation and there is no guarantee that the a timeout is triggered exactly after the timeout value. It is not recommended to use very low timeout values or checker intervals." + }, + "completionTimeoutCheckerInterval": { + "kind": "attribute", + "displayName": "Completion Timeout Checker Interval", + "required": false, + "type": "duration", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "defaultValue": "1s", + "description": "Interval in millis that is used by the background task that checks for timeouts ( org.apache.camel.TimeoutMap ). By default the timeout checker runs every second. The timeout is an approximation and there is no guarantee that the a timeout is triggered exactly after the timeout value. It is not recommended to use very low timeout values or checker intervals." + }, + "completionFromBatchConsumer": { + "kind": "attribute", + "displayName": "Completion From Batch Consumer", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Enables the batch completion mode where we aggregate from a org.apache.camel.BatchConsumer and aggregate the total number of exchanges the org.apache.camel.BatchConsumer has reported as total by checking the exchange property org.apache.camel.Exchange#BATCH_COMPLETE when its complete. This option cannot be used together with discardOnAggregationFailure." + }, + "completionOnNewCorrelationGroup": { + "kind": "attribute", + "displayName": "Completion On New Correlation Group", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Enables completion on all previous groups when a new incoming correlation group. This can for example be used to complete groups with same correlation keys when they are in consecutive order. Notice when this is enabled then only 1 correlation group can be in progress as when a new correlation group starts, then the previous groups is forced completed." + }, + "eagerCheckCompletion": { + "kind": "attribute", + "displayName": "Eager Check Completion", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Use eager completion checking which means that the completionPredicate will use the incoming Exchange. As opposed to without eager completion checking the completionPredicate will use the aggregated Exchange." + }, + "ignoreInvalidCorrelationKeys": { + "kind": "attribute", + "displayName": "Ignore Invalid Correlation Keys", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "If a correlation key cannot be successfully evaluated it will be ignored by logging a DEBUG and then just ignore the incoming Exchange." + }, + "closeCorrelationKeyOnCompletion": { + "kind": "attribute", + "displayName": "Close Correlation Key On Completion", + "required": false, + "type": "integer", + "javaType": "java.lang.Integer", + "deprecated": false, + "secret": false, + "description": "Closes a correlation key when its complete. Any late received exchanges which has a correlation key that has been closed, it will be defined and a ClosedCorrelationKeyException is thrown." + }, + "discardOnCompletionTimeout": { + "kind": "attribute", + "displayName": "Discard On Completion Timeout", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Discards the aggregated message on completion timeout. This means on timeout the aggregated message is dropped and not sent out of the aggregator." + }, + "discardOnAggregationFailure": { + "kind": "attribute", + "displayName": "Discard On Aggregation Failure", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Discards the aggregated message when aggregation failed (an exception was thrown from AggregationStrategy . This means the partly aggregated message is dropped and not sent out of the aggregator. This option cannot be used together with completionFromBatchConsumer." + }, + "forceCompletionOnStop": { + "kind": "attribute", + "displayName": "Force Completion On Stop", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Indicates to complete all current aggregated exchanges when the context is stopped" + }, + "completeAllOnStop": { + "kind": "attribute", + "displayName": "Complete All On Stop", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Indicates to wait to complete all current and partial (pending) aggregated exchanges when the context is stopped. This also means that we will wait for all pending exchanges which are stored in the aggregation repository to complete so the repository is empty before we can stop. You may want to enable this when using the memory based aggregation repository that is memory based only, and do not store data on disk. When this option is enabled, then the aggregator is waiting to complete all those exchanges before its stopped, when stopping CamelContext or the route using it." + }, + "aggregateControllerRef": { + "kind": "attribute", + "displayName": "Aggregate Controller Ref", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "To use a org.apache.camel.processor.aggregate.AggregateController to allow external sources to control this aggregator." + }, + "id": { + "kind": "attribute", + "displayName": "Id", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the id of this node" + }, + "description": { + "kind": "element", + "displayName": "Description", + "required": false, + "type": "object", + "javaType": "org.apache.camel.model.DescriptionDefinition", + "deprecated": false, + "secret": false, + "description": "Sets the description of this node" + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-quartz.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-quartz.json new file mode 100644 index 00000000..d1b0aaaf --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-quartz.json @@ -0,0 +1,84 @@ +{ + "factory": { + "id": "model-quartz", + "type": "entaxy.runtime.camel-model", + "parent": "abstract-camel-model", + "isAbstract": false, + "description": "Factory route-quartz of entaxy.runtime.route. Provides a scheduled delivery of messages." + }, + "entaxy.runtime.camel-model": { + }, + "fields": { + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + }, + "fields": { + "routeContent": { + "displayName": "Route content" + }, + "groupName": { + "group": "general", + "defaultValue": "" + }, + "triggerName": { + "group": "general" + }, + "camel_cron": { + "description": "Specifies a cron expression to define when to trigger. Sing + to be used instead of spaces, example 0+0/1+*+1/1+*+?+* (every minute). Default value is every second." + }, + "camel_exceptionHandler": { + "@TODO": "Now hidden, to process in next releases", + "isHidden": true + }, + "camel_customCalendar": { + "@TODO": "Now hidden, to process in next releases", + "isHidden": true + }, + "camel_jobParameters":{ + "@TODO": "Now hidden, to process in next releases. Use parameters with job. prefix.", + "isHidden": true + }, + "camel_triggerParameters":{ + "@TODO": "Now hidden, to process in next releases Use parameters with trigger. prefix.", + "isHidden": true + }, + "@IMPORT": [ + { + "sourceFactoryId": "camel-quartz", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + } + ] + } + }, + { + "sourceFactoryId": "camel-quartz", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-timer.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-timer.json new file mode 100644 index 00000000..88e6393d --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/camel/model/model-timer.json @@ -0,0 +1,854 @@ +{ + "factory": { + "id": "model-timer", + "type": "entaxy.runtime.camel-model", + "parent": "abstract-camel-model", + "isAbstract": false, + "camelOriginComponent": "timer", + "label": "core,scheduling", + "description": "Generate messages in specified intervals using java.util.Timer.", + "camelOrigin": "camel-timer", + "camelOriginJavaType": "org.apache.camel.component.timer.TimerComponent" + }, + "entaxy.runtime.camel-model": {}, + "fields": { + "bridgeErrorHandler": { + "displayName": "Bridge Error Handler", + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. For more details see Entaxy docs and Camel docs", + "label": "consumer", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "basicPropertyBinding": { + "displayName": "Basic Property Binding", + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "boolean", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "##camelDiff": { + "old": { + "javaType": "boolean", + "deprecated": false + }, + "new": { + "javaType": "boolean", + "deprecated": false + } + } + }, + "timerName": { + "displayName": "Timer Name", + "description": "The name of the timer For more details see Entaxy docs and Camel docs", + "label": "", + "type": "string", + "kind": "path", + "required": true, + "hidden": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "" + } + }, + "delay": { + "displayName": "Delay", + "description": "Delay before first event is triggered. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "duration", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "1s", + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "fixedRate": { + "displayName": "Fixed Rate", + "description": "Events take place at approximately regular intervals, separated by the specified period. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "includeMetadata": { + "displayName": "Include Metadata", + "description": "Whether to include metadata in the exchange such as fired time, timer name, timer count etc. This information is default included. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "period": { + "displayName": "Period", + "description": "If greater than 0, generate periodic events every period. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "duration", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": "1s", + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "repeatCount": { + "displayName": "Repeat Count", + "description": "Specifies a maximum limit of number of fires. So if you set it to 1, the timer will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever. For more details see Entaxy docs and Camel docs", + "label": "", + "type": "number", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": 0, + "group": "consumer", + "##origin": "camel", + "##camelDiff": { + "javaType": "long", + "deprecated": false + } + }, + "exceptionHandler": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Exception Handler", + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. For more details see Entaxy docs and Camel docs", + "label": "consumer,advanced", + "type": "object", + "kind": "parameter", + "required": false, + "isHidden": true, + "group": "consumer (advanced)", + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false + } + }, + "exchangePattern": { + "displayName": "Exchange Pattern", + "description": "Sets the exchange pattern when the consumer creates an exchange. For more details see Entaxy docs and Camel docs", + "label": "consumer,advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "consumer (advanced)", + "@TYPEINFO": { + "type": "enum", + "values": [ + "InOnly", + "InOut", + "InOptionalOut" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.ExchangePattern", + "deprecated": false + } + }, + "daemon": { + "displayName": "Daemon", + "description": "Specifies whether or not the thread associated with the timer endpoint runs as a daemon. The default value is true. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": true, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "pattern": { + "displayName": "Pattern", + "description": "Allows you to specify a custom Date pattern to use for setting the time option using URI syntax. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "synchronous": { + "displayName": "Synchronous", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported). For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "boolean", + "kind": "parameter", + "required": false, + "hidden": false, + "defaultValue": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "boolean", + "deprecated": false + } + }, + "time": { + "displayName": "Time", + "description": "A java.util.Date the first event should be generated. If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss or yyyy-MM-dd\u0027T\u0027HH:mm:ss. For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Date", + "deprecated": false + } + }, + "timer": { + "@TODO": "Now hidden, to process in next releases", + "displayName": "Timer", + "description": "To use a custom Timer For more details see Entaxy docs and Camel docs", + "label": "advanced", + "type": "object", + "kind": "parameter", + "required": false, + "isHidden": true, + "group": "advanced", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.util.Timer", + "deprecated": false + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "hidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "timerName": { + "group": "general" + }, + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "component": { + "kind": "component", + "name": "timer", + "title": "Timer", + "description": "Generate messages in specified intervals using java.util.Timer.", + "deprecated": false, + "firstVersion": "1.0.0", + "label": "core,scheduling", + "javaType": "org.apache.camel.component.timer.TimerComponent", + "supportLevel": "Stable", + "groupId": "org.apache.camel", + "artifactId": "camel-timer", + "version": "3.4.5", + "scheme": "timer", + "extendsScheme": "", + "syntax": "timer:timerName", + "async": false, + "consumerOnly": true, + "producerOnly": false, + "lenientProperties": false + }, + "componentProperties": { + "bridgeErrorHandler": { + "kind": "property", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "basicPropertyBinding": { + "kind": "property", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the component should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + } + }, + "properties": { + "timerName": { + "kind": "path", + "displayName": "Timer Name", + "group": "consumer", + "label": "", + "required": true, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "deprecationNote": "", + "secret": false, + "description": "The name of the timer" + }, + "bridgeErrorHandler": { + "kind": "parameter", + "displayName": "Bridge Error Handler", + "group": "consumer", + "label": "consumer", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "delay": { + "kind": "parameter", + "displayName": "Delay", + "group": "consumer", + "label": "", + "required": false, + "type": "duration", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1s", + "description": "Delay before first event is triggered." + }, + "fixedRate": { + "kind": "parameter", + "displayName": "Fixed Rate", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Events take place at approximately regular intervals, separated by the specified period." + }, + "includeMetadata": { + "kind": "parameter", + "displayName": "Include Metadata", + "group": "consumer", + "label": "", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Whether to include metadata in the exchange such as fired time, timer name, timer count etc. This information is default included." + }, + "period": { + "kind": "parameter", + "displayName": "Period", + "group": "consumer", + "label": "", + "required": false, + "type": "duration", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "1s", + "description": "If greater than 0, generate periodic events every period." + }, + "repeatCount": { + "kind": "parameter", + "displayName": "Repeat Count", + "group": "consumer", + "label": "", + "required": false, + "type": "integer", + "javaType": "long", + "deprecated": false, + "secret": false, + "defaultValue": "0", + "description": "Specifies a maximum limit of number of fires. So if you set it to 1, the timer will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever." + }, + "exceptionHandler": { + "kind": "parameter", + "displayName": "Exception Handler", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.spi.ExceptionHandler", + "optionalPrefix": "consumer.", + "deprecated": false, + "secret": false, + "description": "To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored." + }, + "exchangePattern": { + "kind": "parameter", + "displayName": "Exchange Pattern", + "group": "consumer (advanced)", + "label": "consumer,advanced", + "required": false, + "type": "object", + "javaType": "org.apache.camel.ExchangePattern", + "enum": [ + "InOnly", + "InOut", + "InOptionalOut" + ], + "deprecated": false, + "secret": false, + "description": "Sets the exchange pattern when the consumer creates an exchange." + }, + "basicPropertyBinding": { + "kind": "parameter", + "displayName": "Basic Property Binding", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Whether the endpoint should use basic property binding (Camel 2.x) or the newer property binding with additional capabilities" + }, + "daemon": { + "kind": "parameter", + "displayName": "Daemon", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "true", + "description": "Specifies whether or not the thread associated with the timer endpoint runs as a daemon. The default value is true." + }, + "pattern": { + "kind": "parameter", + "displayName": "Pattern", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Allows you to specify a custom Date pattern to use for setting the time option using URI syntax." + }, + "synchronous": { + "kind": "parameter", + "displayName": "Synchronous", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "boolean", + "javaType": "boolean", + "deprecated": false, + "secret": false, + "defaultValue": "false", + "description": "Sets whether synchronous processing should be strictly used, or Camel is allowed to use asynchronous processing (if supported)." + }, + "time": { + "kind": "parameter", + "displayName": "Time", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "string", + "javaType": "java.util.Date", + "deprecated": false, + "secret": false, + "description": "A java.util.Date the first event should be generated. If using the URI, the pattern expected is: yyyy-MM-dd HH:mm:ss or yyyy-MM-dd\u0027T\u0027HH:mm:ss." + }, + "timer": { + "kind": "parameter", + "displayName": "Timer", + "group": "advanced", + "label": "advanced", + "required": false, + "type": "object", + "javaType": "java.util.Timer", + "deprecated": false, + "secret": false, + "description": "To use a custom Timer" + } + } + } + }, + "outputs": { + "init": { + "fields": { + "timerName": { + "group": "general" + }, + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + } + ] + } + }, + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/ftp-client-config.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/ftp-client-config.json new file mode 100644 index 00000000..38917003 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/ftp-client-config.json @@ -0,0 +1,34 @@ +{ + "factory": { + "id": "ftp-client-config", + "type": "entaxy.runtime.route.component", + "isAbstract": false, + "parent": "abstract-route-component" + }, + "entaxy.runtime.route.component": {}, + "fields": { + "camel_ftpClient.controlEncoding": { + "displayName": "FTP Control encoding", + "description": "Character encoding used for communicating over an FTP control connection. The default encoding is an ASCII-compatible encoding. Some FTP servers expect other encodings.", + "type": "string", + "group": "ftp client" + }, + "camel_ftpClient.autodetectUTF8": { + "displayName": "Autodetect UTF8", + "description": "Controls the automatic server encoding detection (only UTF-8 supported).", + "type": "boolean", + "group": "ftp client", + "defaultValue": false + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + }, + "config": { + "configurable": false + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/redelivery-policy.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/redelivery-policy.json new file mode 100644 index 00000000..cd4bfe9d --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/redelivery-policy.json @@ -0,0 +1,867 @@ +{ + "factory": { + "id": "redelivery-policy", + "type": "entaxy.runtime.route.component", + "isAbstract": false, + "parent": "base-object", + "camelOriginComponent": "redeliveryPolicy", + "label": "configuration", + "group": "errorHandler", + "description": "To configure re-delivery for error handling", + "camelOrigin": "camel-core-engine", + "camelOriginJavaType": "org.apache.camel.model.RedeliveryPolicyDefinition" + }, + "entaxy.runtime.route.component": {}, + "fields": { + "maximumRedeliveries": { + "displayName": "Maximum Redeliveries", + "description": "Sets the maximum redeliveries x \u003d redeliver at most x times 0 \u003d no redeliveries -1 \u003d redeliver forever. For more details see Entaxy docs and Camel docs", + "type": "number", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": 0, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Integer", + "deprecated": false + } + }, + "redeliveryDelay": { + "displayName": "Redelivery Delay", + "description": "Sets the initial redelivery delay. For more details see Entaxy docs and Camel docs", + "type": "duration", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": "1000", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "asyncDelayedRedelivery": { + "displayName": "Async Delayed Redelivery", + "description": "Allow synchronous delayed redelivery. The route, in particular the consumer\u0027s component, must support the Asynchronous Routing Engine (e.g. seda). For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "backOffMultiplier": { + "displayName": "Back Off Multiplier", + "description": "Sets the back off multiplier. For more details see Entaxy docs and Camel docs", + "type": "number", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": 2, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Double", + "deprecated": false + } + }, + "useExponentialBackOff": { + "displayName": "Use Exponential Back Off", + "description": "Turn on exponential back off. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "collisionAvoidanceFactor": { + "displayName": "Collision Avoidance Factor", + "description": "Sets the collision avoidance factor. For more details see Entaxy docs and Camel docs", + "type": "number", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": 0.15, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Double", + "deprecated": false + } + }, + "useCollisionAvoidance": { + "displayName": "Use Collision Avoidance", + "description": "Turn on collision avoidance. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "maximumRedeliveryDelay": { + "displayName": "Maximum Redelivery Delay", + "description": "Sets the maximum delay between redelivery. For more details see Entaxy docs and Camel docs", + "type": "duration", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": "60000", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "retriesExhaustedLogLevel": { + "displayName": "Retries Exhausted Log Level", + "description": "Sets the logging level to use when retries has exhausted. For more details see Entaxy docs and Camel docs", + "type": "object", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": "ERROR", + "@TYPEINFO": { + "type": "enum", + "values": [ + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "OFF" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.LoggingLevel", + "deprecated": false + } + }, + "retryAttemptedLogLevel": { + "displayName": "Retry Attempted Log Level", + "description": "Sets the logging level to use for logging retry attempts. For more details see Entaxy docs and Camel docs", + "type": "object", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": "DEBUG", + "@TYPEINFO": { + "type": "enum", + "values": [ + "TRACE", + "DEBUG", + "INFO", + "WARN", + "ERROR", + "OFF" + ] + }, + "##origin": "camel", + "##camelDiff": { + "javaType": "org.apache.camel.LoggingLevel", + "deprecated": false + } + }, + "retryAttemptedLogInterval": { + "displayName": "Retry Attempted Log Interval", + "description": "Sets the interval to use for logging retry attempts. For more details see Entaxy docs and Camel docs", + "type": "number", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": 1, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Integer", + "deprecated": false + } + }, + "logRetryAttempted": { + "displayName": "Log Retry Attempted", + "description": "Sets whether retry attempts should be logged or not. Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logStackTrace": { + "displayName": "Log Stack Trace", + "description": "Sets whether stack traces should be logged. Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logRetryStackTrace": { + "displayName": "Log Retry Stack Trace", + "description": "Sets whether stack traces should be logged when an retry attempt failed. Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logHandled": { + "displayName": "Log Handled", + "description": "Sets whether handled exceptions should be logged or not. Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logNewException": { + "displayName": "Log New Exception", + "description": "Sets whether new exceptions should be logged or not. Can be used to include or reduce verbose. A new exception is an exception that was thrown while handling a previous exception. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logContinued": { + "displayName": "Log Continued", + "description": "Sets whether continued exceptions should be logged or not. Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logExhausted": { + "displayName": "Log Exhausted", + "description": "Sets whether exhausted exceptions should be logged or not. Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logExhaustedMessageHistory": { + "displayName": "Log Exhausted Message History", + "description": "Sets whether exhausted exceptions should be logged including message history or not (supports property placeholders). Can be used to include or reduce verbose. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "logExhaustedMessageBody": { + "displayName": "Log Exhausted Message Body", + "description": "Sets whether exhausted message body should be logged including message history or not (supports property placeholders). Can be used to include or reduce verbose. Requires logExhaustedMessageHistory to be enabled. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "disableRedelivery": { + "displayName": "Disable Redelivery", + "description": "Disables redelivery (same as setting maximum redeliveries to 0). For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": false, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "delayPattern": { + "displayName": "Delay Pattern", + "description": "Sets the delay pattern with delay intervals. For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": "", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + }, + "allowRedeliveryWhileStopping": { + "displayName": "Allow Redelivery While Stopping", + "description": "Controls whether to allow redelivery while stopping/shutting down a route that uses error handling. For more details see Entaxy docs and Camel docs", + "type": "boolean", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": true, + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.Boolean", + "deprecated": false, + "defaultValue": false + } + }, + "exchangeFormatterRef": { + "displayName": "Exchange Formatter Ref", + "description": "Sets the reference of the instance of org.apache.camel.spi.ExchangeFormatter to generate the log message from exchange. For more details see Entaxy docs and Camel docs", + "type": "string", + "kind": "attribute", + "group": "redelivery policy", + "required": false, + "hidden": false, + "defaultValue": "", + "##origin": "camel", + "##camelDiff": { + "javaType": "java.lang.String", + "deprecated": false + } + } + }, + "##camel": { + "settings": { + "import": { + "factory": { + "attributes": { + "name": [ + "id", + "camelOriginComponent" + ], + "label": { + "target": "label", + "replaceIfEmpty": true + }, + "description": { + "target": "description", + "policy": "firstOnly", + "replaceIfEmpty": true + }, + "artifactId": "camelOrigin", + "javaType": "camelOriginJavaType" + } + }, + "fileds": { + "attributes": { + "displayName": "displayName", + "description": { + "target": "description", + "policy": "firstOnly" + }, + "label": "label", + "type": { + "target": "type", + "map": { + "integer": "number" + } + }, + "kind": { + "target": "kind", + "policy": "both" + }, + "required": "required", + "secret": "hidden", + "defaultValue": { + "target": "defaultValue", + "convertTo": "@type" + }, + "group": "group", + "enum": { + "target": "@TYPEINFO/values", + "targetObject": { + "@TYPEINFO": { + "type": "enum" + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "property" + ] + } + ] + } + } + ] + } + }, + "path": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "path" + ] + } + ] + } + } + ] + } + }, + "consumer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "producer" + ] + } + ] + } + } + ] + } + }, + "producer": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "camel_", + "filter": { + "contains": [ + { + "attribute": "kind", + "values": [ + "parameter" + ] + }, + { + "attribute": "label", + "inverse": true, + "values": [ + "consumer" + ] + } + ] + } + } + ] + } + }, + "__objects": { + "fields": { + "@IMPORT": [ + { + "sourceFactoryId": "#", + "location": "fields", + "prefix": "", + "filter": { + "contains": [ + { + "attribute": "type", + "values": [ + "Object", + "object" + ] + } + ] + } + } + ] + } + } + } + } + }, + "origin": { + "component": { + "kind": "model", + "name": "redeliveryPolicy", + "title": "Redelivery Policy", + "description": "To configure re-delivery for error handling", + "deprecated": false, + "label": "configuration", + "javaType": "org.apache.camel.model.RedeliveryPolicyDefinition", + "artifactId": "camel-core-engine", + "input": false, + "output": false + }, + "componentProperties": {}, + "properties": { + "maximumRedeliveries": { + "kind": "attribute", + "displayName": "Maximum Redeliveries", + "required": false, + "type": "integer", + "javaType": "java.lang.Integer", + "deprecated": false, + "secret": false, + "description": "Sets the maximum redeliveries x \u003d redeliver at most x times 0 \u003d no redeliveries -1 \u003d redeliver forever" + }, + "redeliveryDelay": { + "kind": "attribute", + "displayName": "Redelivery Delay", + "required": false, + "type": "duration", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the initial redelivery delay" + }, + "asyncDelayedRedelivery": { + "kind": "attribute", + "displayName": "Async Delayed Redelivery", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Allow asynchronous delayed redelivery. The route, in particular the consumer\u0027s component, must support the Asynchronous Routing Engine (e.g. seda)." + }, + "backOffMultiplier": { + "kind": "attribute", + "displayName": "Back Off Multiplier", + "required": false, + "type": "number", + "javaType": "java.lang.Double", + "deprecated": false, + "secret": false, + "description": "Sets the back off multiplier" + }, + "useExponentialBackOff": { + "kind": "attribute", + "displayName": "Use Exponential Back Off", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Turn on exponential backk off" + }, + "collisionAvoidanceFactor": { + "kind": "attribute", + "displayName": "Collision Avoidance Factor", + "required": false, + "type": "number", + "javaType": "java.lang.Double", + "deprecated": false, + "secret": false, + "description": "Sets the collision avoidance factor" + }, + "useCollisionAvoidance": { + "kind": "attribute", + "displayName": "Use Collision Avoidance", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Turn on collision avoidance." + }, + "maximumRedeliveryDelay": { + "kind": "attribute", + "displayName": "Maximum Redelivery Delay", + "required": false, + "type": "duration", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the maximum delay between redelivery" + }, + "retriesExhaustedLogLevel": { + "kind": "attribute", + "displayName": "Retries Exhausted Log Level", + "required": false, + "type": "object", + "javaType": "org.apache.camel.LoggingLevel", + "deprecated": false, + "secret": false, + "description": "Sets the logging level to use when retries has exhausted" + }, + "retryAttemptedLogLevel": { + "kind": "attribute", + "displayName": "Retry Attempted Log Level", + "required": false, + "type": "object", + "javaType": "org.apache.camel.LoggingLevel", + "deprecated": false, + "secret": false, + "description": "Sets the logging level to use for logging retry attempts" + }, + "retryAttemptedLogInterval": { + "kind": "attribute", + "displayName": "Retry Attempted Log Interval", + "required": false, + "type": "integer", + "javaType": "java.lang.Integer", + "deprecated": false, + "secret": false, + "description": "Sets the interval to use for logging retry attempts" + }, + "logRetryAttempted": { + "kind": "attribute", + "displayName": "Log Retry Attempted", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether retry attempts should be logged or not. Can be used to include or reduce verbose." + }, + "logStackTrace": { + "kind": "attribute", + "displayName": "Log Stack Trace", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether stack traces should be logged. Can be used to include or reduce verbose." + }, + "logRetryStackTrace": { + "kind": "attribute", + "displayName": "Log Retry Stack Trace", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether stack traces should be logged when an retry attempt failed. Can be used to include or reduce verbose." + }, + "logHandled": { + "kind": "attribute", + "displayName": "Log Handled", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether handled exceptions should be logged or not. Can be used to include or reduce verbose." + }, + "logNewException": { + "kind": "attribute", + "displayName": "Log New Exception", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether new exceptions should be logged or not. Can be used to include or reduce verbose. A new exception is an exception that was thrown while handling a previous exception." + }, + "logContinued": { + "kind": "attribute", + "displayName": "Log Continued", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether continued exceptions should be logged or not. Can be used to include or reduce verbose." + }, + "logExhausted": { + "kind": "attribute", + "displayName": "Log Exhausted", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether exhausted exceptions should be logged or not. Can be used to include or reduce verbose." + }, + "logExhaustedMessageHistory": { + "kind": "attribute", + "displayName": "Log Exhausted Message History", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether exhausted exceptions should be logged including message history or not (supports property placeholders). Can be used to include or reduce verbose." + }, + "logExhaustedMessageBody": { + "kind": "attribute", + "displayName": "Log Exhausted Message Body", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Sets whether exhausted message body should be logged including message history or not (supports property placeholders). Can be used to include or reduce verbose. Requires logExhaustedMessageHistory to be enabled." + }, + "disableRedelivery": { + "kind": "attribute", + "displayName": "Disable Redelivery", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Disables redelivery (same as setting maximum redeliveries to 0)" + }, + "delayPattern": { + "kind": "attribute", + "displayName": "Delay Pattern", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the delay pattern with delay intervals." + }, + "allowRedeliveryWhileStopping": { + "kind": "attribute", + "displayName": "Allow Redelivery While Stopping", + "required": false, + "type": "boolean", + "javaType": "java.lang.Boolean", + "deprecated": false, + "secret": false, + "defaultValue": false, + "description": "Controls whether to allow redelivery while stopping/shutting down a route that uses error handling." + }, + "exchangeFormatterRef": { + "kind": "attribute", + "displayName": "Exchange Formatter Ref", + "required": false, + "type": "string", + "javaType": "java.lang.String", + "deprecated": false, + "secret": false, + "description": "Sets the reference of the instance of org.apache.camel.spi.ExchangeFormatter to generate the log message from exchange." + } + } + } + }, + "outputs": {} +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-component.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-component.json new file mode 100644 index 00000000..399f7dfb --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-component.json @@ -0,0 +1,25 @@ +{ + "factory": { + "id": "abstract-route-component", + "type": "entaxy.runtime.route.component", + "description": "", + "isAbstract": true, + "parent": "base-object", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component": {}, + "fields": {}, + "outputs": { + "init": { + "fields": { + "objectId": { + "isHidden": true + }, + "displayName": { + "isHidden": true + } + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-container-object.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-container-object.json new file mode 100644 index 00000000..0230f947 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-container-object.json @@ -0,0 +1,26 @@ +{ + "factory": { + "id": "abstract-route-container-object", + "type": "entaxy.runtime.route-container", + "description": "Factory route-library of entaxy.runtime.route-container", + "isAbstract": true, + "parent": "abstract-route-container" + }, + "entaxy.runtime.route-container": {}, + "fields": { + "routes": { + "itemFactory": { + "filter": "(&(type=entaxy.runtime.route)(isAbstract=false)(|(typeinfo.targetRouteContainerType=ANY)(typeinfo.targetRouteContainerType=OBJECT)))" + } + } + + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-container.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-container.json new file mode 100644 index 00000000..aa9fdad1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route-container.json @@ -0,0 +1,390 @@ +{ + "factory": { + "id": "abstract-route-container", + "type": "entaxy.runtime.route-container", + "description": "Factory abstract-route-container of entaxy.runtime.route-container" + }, + "entaxy.runtime.route-container": { + "routeContainerType": "OBJECT" + }, + "fields": { + "routes": { + "@PUBLISH_UNRESOLVED": "object", + "type": "list", + "group": "routes", + "itemType": "entaxy.runtime.route", + "itemFactory": { + "filter": "(type=entaxy.runtime.route)" + }, + "itemScope": "private", + "immutable": true, + "@TYPEINFO": { + "excludeLabel": true, + "enablePrivateObjectCreation": true, + "privateObjectTypes": [ + { + "name": "entaxy.runtime.route", + "displayName": "Route" + } + ], + "itemTitle": { + "fields": [ + "routeId" + ], + "delimiter": "." + }, + "useAsIdentifier": "routeId", + "validation": { + "rules": { + "checkUniqueness": { + "fields": [ + "routeId" + ] + } + } + } + }, + "@UI": { + "fieldExtraInfo": { + "type": "info", + "message": "To create or edit route find associated node in tree", + "displayOnMode": "Edit" + } + } + }, + "__globalOptions": { + "type": "entaxy.runtime.route-container", + "isRef": true, + "required": true, + "isHidden": true, + "isRefByValueOnly": true, + "@INTERNAL": true, + "defaultValue": { + "type": "entaxy.runtime.route-container", + "factoryId": "#OWNER#", + "outputType": "globalOptions", + "scope": "private", + "properties": { + "containerId": { + "@CALCULATED": { + "expression": "${#OWNER#.objectId}", + "lazy": true + } + }, + "containerType": { + "@CALCULATED": { + "expression": "${#OWNER#.#FACTORY#.factory.type}", + "lazy": false, + "allowObjects": false + } + } + } + } + }, + "__errorHandler": { + "type": "entaxy.runtime.route-container", + "isRef": true, + "required": true, + "isHidden": true, + "isRefByValueOnly": true, + "@INTERNAL": true, + "refConfig": { + "@INTERNAL": true + }, + "defaultValue": { + "type": "entaxy.runtime.route-container", + "factoryId": "#OWNER#", + "outputType": "errorHandler", + "scope": "private", + "properties": { + "errorHandlerType": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.errorHandlerType}", + "lazy": false + } + }, + "deadLetterUri": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.deadLetterUri}", + "lazy": false + } + }, + "maximumRedeliveries": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.maximumRedeliveries}", + "fallbackObject": null, + "lazy": false + } + }, + "redeliveryDelay": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.redeliveryDelay}", + "fallbackObject": null, + "lazy": false + } + }, + "asyncDelayedRedelivery": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.asyncDelayedRedelivery}", + "fallbackObject": null, + "lazy": false + } + }, + "backOffMultiplier": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.backOffMultiplier}", + "fallbackObject": null, + "lazy": false + } + }, + "useExponentialBackOff": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.useExponentialBackOff}", + "fallbackObject": null, + "lazy": false + } + }, + "collisionAvoidanceFactor": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.collisionAvoidanceFactor}", + "fallbackObject": null, + "lazy": false + } + }, + "useCollisionAvoidance": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.useCollisionAvoidance}", + "fallbackObject": null, + "lazy": false + } + }, + "maximumRedeliveryDelay": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.maximumRedeliveryDelay}", + "fallbackObject": null, + "lazy": false + } + }, + "retriesExhaustedLogLevel": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.retriesExhaustedLogLevel}", + "fallbackObject": null, + "lazy": false + } + }, + "retryAttemptedLogLevel": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.retryAttemptedLogLevel}", + "fallbackObject": null, + "lazy": false + } + }, + "retryAttemptedLogInterval": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.retryAttemptedLogInterval}", + "fallbackObject": null, + "lazy": false + } + }, + "logRetryAttempted": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logRetryAttempted}", + "fallbackObject": null, + "lazy": false + } + }, + "logStackTrace": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logStackTrace}", + "fallbackObject": null, + "lazy": false + } + }, + "logRetryStackTrace": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logRetryStackTrace}", + "fallbackObject": null, + "lazy": false + } + }, + "logHandled": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logHandled}", + "fallbackObject": null, + "lazy": false + } + }, + "logNewException": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logNewException}", + "fallbackObject": null, + "lazy": false + } + }, + "logContinued": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logContinued}", + "fallbackObject": null, + "lazy": false + } + }, + "logExhausted": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logExhausted}", + "fallbackObject": null, + "lazy": false + } + }, + "logExhaustedMessageHistory": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logExhaustedMessageHistory}", + "fallbackObject": null, + "lazy": false + } + }, + "logExhaustedMessageBody": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.logExhaustedMessageBody}", + "fallbackObject": null, + "lazy": false + } + }, + "disableRedelivery": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.disableRedelivery}", + "fallbackObject": null, + "lazy": false + } + }, + "delayPattern": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.delayPattern}", + "fallbackObject": null, + "lazy": false + } + }, + "allowRedeliveryWhileStopping": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.allowRedeliveryWhileStopping}", + "fallbackObject": null, + "lazy": false + } + }, + "exchangeFormatterRef": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.exchangeFormatterRef}", + "fallbackObject": null, + "lazy": false + } + } + } + } + }, + "errorHandlerType": { + "displayName": "Error Handler", + "description": "The type of the error handler. Default value: DefaultErrorHandler. For more details see Entaxy docs and Camel docs", + "type": "String", + "@TYPEINFO": { + "type": "enum", + "values": [ + "DefaultErrorHandler", + "DeadLetterChannel", + "NoErrorHandler" + ] + }, + "defaultValue": "DefaultErrorHandler", + "required": true, + "group": "redelivery policy" + }, + "deadLetterUri": { + "displayName": "Dead Letter URI", + "description": "The dead letter endpoint uri for the Dead Letter error handler. For more details see Entaxy docs and Camel docs", + "type": "String", + "defaultValue": "log:myLog", + "required": true, + "group": "redelivery policy" + }, + "##publish": { + "defaultValue": { + "isRouteContainer": true, + "routeContainerType": { + "@CALCULATED": { + "expression": "${#FACTORY#.#TYPEINFO#.routeContainerType}", + "lazy": false + } + } + } + }, + "@IMPORT": [ + { + "sourceFactoryId": "redelivery-policy", + "location": "fields", + "prefix": "" + } + ] + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "routes": { + }, + "__globalOptions": { + }, + "__errorHandler": { + }, + "errorHandlerType": { + }, + "deadLetterUri": { + }, + "@IMPORT": [ + { + "sourceFactoryId": "redelivery-policy", + "location": "fields", + "prefix": "" + } + ] + }, + "config": { + "configurable": false + } + }, + "globalOptions": { + "fields": { + }, + "scopes": [ + "private" + ], + "config": { + "@SKIP_PUBLISH": { + }, + "@SKIP_VAULTS_LOOKUP": {}, + "configurable": false + } + }, + "errorHandler": { + "fields": { + "errorHandlerType": { + }, + "deadLetterUri": { + }, + "@IMPORT": [ + { + "sourceFactoryId": "redelivery-policy", + "location": "fields", + "prefix": "" + } + ] + }, + "scopes": [ + "private" + ], + "config": { + "@SKIP_PUBLISH": { + }, + "@SKIP_VAULTS_LOOKUP": {}, + "configurable": false + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route.json new file mode 100644 index 00000000..4f219da6 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/abstract-route.json @@ -0,0 +1,182 @@ +{ + "factory": { + "id": "abstract-route", + "type": "entaxy.runtime.route", + "description": "Factory abstract-route of entaxy.runtime.route" + }, + "entaxy.runtime.route": { + "targetRouteContainerType": "ANY", + "routeType": "CUSTOM", + "routePattern": "ABSTRACT", + "routeIsCallable": false + }, + "fields": { + "objectId": { + "isHidden": true + }, + "routeId": { + "type": "String", + "displayName": "Route ID", + "description": "Unique identifier assigned to each route", + "isHidden": false, + "required": true, + "@UNIQUE": { + "filterByParentFieldValues": true + }, + "@TYPEINFO": { + "validation": { + "rules": { + "length": { + "min": 3 + }, + "content": { + "regex": "^[a-zA-Z][a-zA-Z0-9-]*$", + "errorMessage": "Value can contain only latin letters, numbers and hyphen and should start with a letter" + } + } + } + } + }, + "__objectId": { + "type": "String", + "isHidden": true, + "required": true, + "@INTERNAL": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${#OWNER#.objectId}__${properties.routeId}", + "targetPath": "$.objectId", + "removeResolved": true, + "resultType": "string", + "lazy": false, + "blacklistContent": ["TEMP-*", "GEN-*"] + } + } + }, + "routeProperties": { + "type": "Map", + "description": "Optional metadata", + "displayName": "Route properties" + }, + "routeContent": { + "displayName": "Route", + "type": "xml:route", + "description": "Set of processing steps that are applied to a message as it travels from a source to a destination. A route typically consists of a series of processing steps that are connected in a linear sequence. For more details see Camel docs", + "required": true, + "@RESOURCE": { + "endType": "String", + "format": "base64", + "location": { + "@CALCULATED": { + "lazy": true, + "expression": "${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.#FACTORY#.factory.type}.${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.objectId}/${#OWNER#.#FACTORY#.factory.type}.${#OWNER#.properties.routeId}/routeContent.xml" + } + }, + "postprocess": [ + { + "processor": "component-library" + } + ] + }, + "defaultValue": { + "@RESOURCE": { + "provider": "entaxy-file-internal", + "location": "factories/abstract-route/routeContent.xml", + "endType": "String", + "format": "base64" + } + } + }, + "__routeOwner": { + "type": "String", + "isHidden": true, + "required": true, + "note": "for the case when we need explicitly set route container id, e.g in xslt", + "@INTERNAL": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.objectId}:${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.#FACTORY#.factory.type}", + "lazy": false + } + } + }, + "displayName": { + "required": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${properties.routeId}", + "lazy": false + } + } + }, + "##publish": { + "type": "Map", + "required": true, + "isHidden": true, + "defaultValue":{ + "relation": [ + { + "@CALCULATED": { + "expression": "${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.objectId}:${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.#FACTORY#.factory.type}:subroute:-composition:routes", + "lazy": true + } + } + ], + "owner": { + "@CALCULATED": { + "expression": "${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.objectId}:${#OWNER_OF_TYPE:+entaxy.runtime.route-container#.#FACTORY#.factory.type}", + "lazy": true + } + }, + "routeId": { + "@CALCULATED": { + "expression": "${properties.routeId}", + "lazy": false + } + }, + "routeType": { + "@CALCULATED": { + "expression": "${#FACTORY#.#TYPEINFO#.routeType}", + "lazy": false + } + }, + "routePattern": { + "@CALCULATED": { + "expression": "${#FACTORY#.#TYPEINFO#.routePattern}", + "lazy": false + } + }, + "routeIsCallable": { + "@CALCULATED": { + "expression": "${#FACTORY#.#TYPEINFO#.routeIsCallable}", + "lazy": false, + "resultType": "string" + } + }, + "routeGlobalCallMode": "NONE", + "routeLocalCallMode": "NONE", + "name": { + "@CALCULATED": { + "expression": "${properties.routeId}" + } + } + } + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "__objectId": {}, + "__routeOwner": {}, + "routeId": {}, + "routeContent": {}, + "routeProperties": {} + }, + "scopes": ["private"], + "config": { + "configurable": false + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-repository.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-repository.json new file mode 100644 index 00000000..6d70a576 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-repository.json @@ -0,0 +1,61 @@ +{ + "factory": { + "id": "abstract-aggregation-repository", + "type": "entaxy.runtime.route.component.aggregation.repository", + "description": "", + "isAbstract": true, + "parent": "abstract-route-component", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.repository": {}, + "fields": { + "ownerId": { + "type": "String", + "group": "hidden", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${#OWNER#.objectId}" + } + } + }, + "className": { + "type": "String", + "group": "hidden", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${#FACTORY#.#TYPEINFO#.className}", + "lazy": false + } + } + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "ownerId": {}, + "className": {} + }, + "config": { + "configurable": false, + "@SKIP_PUBLISH": {}, + "@SKIP_VAULTS_LOOKUP": "" + }, + "scopes": ["private"] + }, + "bean": { + "isDefault": false, + "fields": {}, + "config": { + "configurable": false, + "@SKIP_PUBLISH": {}, + "@SKIP_PROVIDE": {} + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-strategy-camel-simple.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-strategy-camel-simple.json new file mode 100644 index 00000000..c4149c49 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-strategy-camel-simple.json @@ -0,0 +1,64 @@ +{ + "factory": { + "id": "abstract-aggregation-strategy-camel-simple", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "description": "", + "isAbstract": true, + "parent": "abstract-aggregation-strategy", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": {}, + "fields": { + "ownerId": { + "type": "String", + "group": "hidden", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${#OWNER#.objectId}" + } + } + }, + "className": { + "type": "String", + "group": "hidden", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${#FACTORY#.#TYPEINFO#.className}", + "lazy": false + } + } + }, + "beanId": { + "type": "String", + "group": "hidden", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "aggregation-strategy-${#FACTORY#.#TYPEINFO#.beanId}", + "lazy": false + } + } + } + }, + "outputs": { + "init": { + "fields": { + "ownerId": {}, + "className": {}, + "beanId": {} + }, + "config": { + "configurable": false, + "@SKIP_PUBLISH": {} + }, + "scopes": ["private"] + + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-strategy.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-strategy.json new file mode 100644 index 00000000..0ac76040 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/abstract-aggregation-strategy.json @@ -0,0 +1,28 @@ +{ + "factory": { + "id": "abstract-aggregation-strategy", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "description": "", + "isAbstract": true, + "parent": "abstract-route-component", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": {}, + "fields": { + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + }, + "config": { + "configurable": false, + "@SKIP_PUBLISH": {}, + "@SKIP_VAULTS_LOOKUP": "" + }, + "scopes": ["private"] + } + + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-camel-memory.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-camel-memory.json new file mode 100644 index 00000000..ef9b87f4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-camel-memory.json @@ -0,0 +1,20 @@ +{ + "factory": { + "id": "aggregation-repository-camel-memory", + "type": "entaxy.runtime.route.component.aggregation.repository", + "displayName": "CAMEL :: MEMORY", + "description": "A memory based AggregationRepository which stores Exchanges in memory only. Supports both optimistic locking and non-optimistic locking modes. Defaults to non-optimistic locking mode.", + "isAbstract": false, + "parent": "abstract-aggregation-repository", + "label": "", + "category": "", + "shortName": "MemoryAggregationRepository", + "@SEE": "camel-base" + }, + "entaxy.runtime.route.component.aggregation.repository": { + "className": "org.apache.camel.processor.aggregate.MemoryAggregationRepository" + }, + "fields": { + }, + "outputs": {} +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-ignite.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-ignite.json new file mode 100644 index 00000000..7c9b4add --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-ignite.json @@ -0,0 +1,40 @@ +{ + "factory": { + "id": "aggregation-repository-entaxy-ignite", + "type": "entaxy.runtime.route.component.aggregation.repository", + "displayName": "ENTAXY :: IGNITE", + "description": "A memory based AggregationRepository which stores Exchanges in ignite cache only.", + "isAbstract": false, + "parent": "abstract-aggregation-repository", + "label": "", + "category": "", + "shortName": "MemoryAggregationRepository", + "@SEE": "camel-base" + }, + "entaxy.runtime.route.component.aggregation.repository": { + "className": "ru.entaxy.esb.system.common.aggregation.repo.IgniteAggregationRepository" + }, + "fields": { + "maximumRedeliveries": { + "displayName": "Maximum Redeliveries", + "description": "Sets the maximum redeliveries x \u003d redeliver at most x times 0 \u003d no redeliveries -1 \u003d redeliver forever. For more details see Entaxy docs and Camel docs", + "type": "number", + "required": true, + "defaultValue": 10 + }, + "deadLetterUri": { + "displayName": "Dead Letter Uri", + "type": "String", + "required": true, + "defaultValue": "mock:none" + } + }, + "outputs": { + "init": { + "fields": { + "maximumRedeliveries": {}, + "deadLetterUri": {} + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-jdbc.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-jdbc.json new file mode 100644 index 00000000..e8a6a1e8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-jdbc.json @@ -0,0 +1,73 @@ +{ + "factory": { + "id": "aggregation-repository-entaxy-jdbc", + "type": "entaxy.runtime.route.component.aggregation.repository", + "displayName": "ENTAXY :: JDBC", + "description": "JDBC based AggregationRepository JdbcAggregationRepository will only preserve any Serializable compatible data types. If a data type is not such a type its dropped and a WARN is logged. And it only persists the Message body and the Message headers. The Exchange properties are not persisted. For more details see Apache Camel components", + "isAbstract": false, + "parent": "abstract-aggregation-repository", + "label": "", + "category": "", + "shortName": "entaxy-jdbc" + }, + "entaxy.runtime.route.component.aggregation.repository": { + "className": "ru.entaxy.esb.system.common.aggregation.repo.JdbcAggregationRepository" + }, + "fields": { + "dataSource": { + "displayName": "Data Source", + "type": "String", + "group": "", + "required": false, + "@TYPEINFO": { + "type": "list", + "source": { + "@SEARCH": { + "type": "service", + "filter": "(objectClass=javax.sql.DataSource)", + "displayProperty": "dataSourceName", + "valueProperty": "dataSourceName" + } + } + } + }, + "repositoryName": { + "displayName": "Repository Name", + "type": "String", + "required": true + }, + "maximumRedeliveries": { + "displayName": "Maximum Redeliveries", + "description": "Sets the maximum redeliveries x \u003d redeliver at most x times 0 \u003d no redeliveries -1 \u003d redeliver forever. For more details see Entaxy docs and Camel docs", + "type": "number", + "required": true, + "defaultValue": 3 + }, + "deadLetterUri": { + "displayName": "Dead Letter Uri", + "type": "String", + "required": true, + "defaultValue": "mock:none" + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "dataSource": { + }, + "repositoryName": { + }, + "maximumRedeliveries": { + }, + "deadLetterUri": { + } + }, + "config": { + "configurable": false, + "@SKIP_PUBLISH": { + } + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-postgre.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-postgre.json new file mode 100644 index 00000000..e68d82ef --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-repository-entaxy-postgre.json @@ -0,0 +1,19 @@ +{ + "factory": { + "id": "aggregation-repository-entaxy-postgre", + "type": "entaxy.runtime.route.component.aggregation.repository", + "displayName": "ENTAXY :: POSTGRE", + "description": "", + "isAbstract": false, + "parent": "aggregation-repository-entaxy-jdbc", + "label": "", + "category": "", + "shortName": "entaxy-jdbc" + }, + "entaxy.runtime.route.component.aggregation.repository": { + "className": "ru.entaxy.esb.system.common.aggregation.repo.PostgresAggregationRepository" + }, + "fields": { + }, + "outputs": {} +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-body.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-body.json new file mode 100644 index 00000000..ec92fa62 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-body.json @@ -0,0 +1,20 @@ +{ + "factory": { + "id": "aggregation-strategy-camel-grouped-body", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "displayName": "GROUPED :: BODY", + "description": "Aggregate body of input Message into a single combined Exchange holding all the aggregated bodies in a List of type Object as the message body.", + "isAbstract": false, + "parent": "abstract-aggregation-strategy-camel-simple", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": { + "className": "org.apache.camel.processor.aggregate.GroupedBodyAggregationStrategy", + "beanId": "grouped-body" + }, + "fields": { + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-exchange.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-exchange.json new file mode 100644 index 00000000..9765d112 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-exchange.json @@ -0,0 +1,20 @@ +{ + "factory": { + "id": "aggregation-strategy-camel-grouped-exchange", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "displayName": "GROUPED :: EXCHANGE", + "description": "Aggregate all exchanges into a single combined Exchange holding all the aggregated exchanges in a List of Exchange as the message body.", + "isAbstract": true, + "parent": "abstract-aggregation-strategy-camel-simple", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": { + "className": "org.apache.camel.processor.aggregate.GroupedExchangeAggregationStrategy", + "beanId": "grouped-exchange" + }, + "fields": { + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-message.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-message.json new file mode 100644 index 00000000..90e2ada9 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-grouped-message.json @@ -0,0 +1,20 @@ +{ + "factory": { + "id": "aggregation-strategy-camel-grouped-message", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "displayName": "GROUPED :: MESSAGE", + "description": "Aggregate all Message into a single combined Exchange holding all the aggregated messages in a List of Message as the message body.", + "isAbstract": true, + "parent": "abstract-aggregation-strategy-camel-simple", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": { + "className": "org.apache.camel.processor.aggregate.GroupedMessageAggregationStrategy", + "beanId": "grouped-message" + }, + "fields": { + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-string.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-string.json new file mode 100644 index 00000000..b68817b1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-string.json @@ -0,0 +1,31 @@ +{ + "factory": { + "id": "aggregation-strategy-camel-string", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "displayName": "STRING", + "description": "Aggregate result of pick expression into a single combined Exchange holding all the aggregated bodies in a String as the message body.", + "isAbstract": false, + "parent": "abstract-aggregation-strategy-camel-simple", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": { + "className": "org.apache.camel.processor.aggregate.EntaxyStringAggregationStrategy", + "beanId": "aggregation-strategy-string" + }, + "fields": { + "delimiter": { + "displayName": "Delimiter", + "type": "String", + "description": "Set delimiter used for joining aggregated. The delimiter to join with. Default empty String", + "required": false + } + }, + "outputs": { + "init": { + "fields": { + "delimiter": {} + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-use-latest.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-use-latest.json new file mode 100644 index 00000000..1f361e82 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-use-latest.json @@ -0,0 +1,20 @@ +{ + "factory": { + "id": "aggregation-strategy-camel-use-latest", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "displayName": "USE LATEST", + "description": "An AggregationStrategy which just uses the latest exchange which is useful for status messages where old status messages have no real value. Another example is things like market data prices, where old stock prices are not that relevant, only the current price is.", + "isAbstract": true, + "parent": "abstract-aggregation-strategy-camel-simple", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": { + "className": "org.apache.camel.processor.aggregate.UseLatestAggregationStrategy", + "beanId": "use-latest" + }, + "fields": { + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-use-original.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-use-original.json new file mode 100644 index 00000000..c47245f1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/aggregate/aggregation-strategy-camel-use-original.json @@ -0,0 +1,20 @@ +{ + "factory": { + "id": "aggregation-strategy-camel-use-original", + "type": "entaxy.runtime.route.component.aggregation.strategy", + "displayName": "USE ORIGINAL", + "description": "An AggregationStrategy which just uses the original exchange which can be needed when you want to preserve the original Exchange. For example when splitting an Exchange and then you may want to keep routing using the original Exchange.", + "isAbstract": true, + "parent": "abstract-aggregation-strategy-camel-simple", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.aggregation.strategy": { + "className": "org.apache.camel.processor.aggregate.UseOriginalAggregationStrategy", + "beanId": "use-original" + }, + "fields": { + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/expression/abstract-expression.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/expression/abstract-expression.json new file mode 100644 index 00000000..2587de84 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/expression/abstract-expression.json @@ -0,0 +1,26 @@ +{ + "factory": { + "id": "abstract-expression", + "type": "entaxy.runtime.route.component.expression", + "description": "", + "isAbstract": true, + "parent": "abstract-route-component", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.expression": {}, + "fields": {}, + "outputs": { + "init": { + "isDefault": false, + "generator": "", + "config": { + "configurable": false, + "@SKIP_PUBLISH": {} + }, + "scopes": [ + "private" + ] + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/expression/common-expression.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/expression/common-expression.json new file mode 100644 index 00000000..300501b9 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/expression/common-expression.json @@ -0,0 +1,53 @@ +{ + "factory": { + "id": "common-expression", + "type": "entaxy.runtime.route.component.expression", + "displayName": "COMMON EXPRESSION", + "description": "", + "isAbstract": false, + "parent": "abstract-expression", + "label": "", + "category": "" + }, + "entaxy.runtime.route.component.expression": {}, + "fields": { + "expressionLanguage": { + "displayName": "Expression Language", + "group": "general", + "required": true, + "type": "string", + "@TYPEINFO": { + "type": "enum", + "values": [ + "constant", + "simple", + "jsonpath", + "xpath", + "header" + ], + "isEmptyIncluded": false + } + }, + "expression": { + "displayName": "Expression", + "type": "String", + "group": "general", + "required": true + } + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false, + "@SKIP_PUBLISH": true, + "@SKIP_VAULTS_LOOKUP": "" + }, + "scopes": ["private"], + "fields": { + "expression": {}, + "expressionLanguage": {} + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/route-timer.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/route-timer.json new file mode 100644 index 00000000..c229d54f --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/components/route-timer.json @@ -0,0 +1,38 @@ +{ + "factory": { + "id": "route-timer", + "type": "entaxy.runtime.route", + "parent": "route-scheduled", + "isAbstract": false, + "displayName": "TIMER", + "description": "Factory route-timer of entaxy.runtime.route" + }, + "entaxy.runtime.route": { + "routePattern": "TIMER" + }, + "fields": { + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + }, + "fields": { + "routeContent": { + "displayName": "Route content" + }, + "timerName": { + "group": "general" + }, + "@IMPORT": [ + { + "sourceFactoryId": "model-timer", + "location": "outputs.init.fields", + "prefix": "" + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-aggregator-in-object.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-aggregator-in-object.json new file mode 100644 index 00000000..ac5e9010 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-aggregator-in-object.json @@ -0,0 +1,37 @@ +{ + "factory": { + "id": "route-aggregator-in-object", + "type": "entaxy.runtime.route", + "parent": "route-aggregator", + "isAbstract": false, + "displayName": "AGGREGATOR", + "description": "The Aggregator from the EIP patterns allows you to combine a number of messages together into a single message. For more details see Entaxy docs and Camel docs" + }, + "entaxy.runtime.route": { + "targetRouteContainerType": "OBJECT" + }, + "fields": { + "globalCallMode": { + "@TYPEINFO": { + "values": [ + "NONE" + ] + }, + "isHidden": true, + "defaultValue": "NONE" + }, + "localCallMode": { + "@TYPEINFO": { + "type": "enum", + "values": [ + "SYNC", + "ASYNC", + "BOTH" + ] + }, + "defaultValue": "SYNC" + } + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-aggregator.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-aggregator.json new file mode 100644 index 00000000..7aced294 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-aggregator.json @@ -0,0 +1,78 @@ +{ + "factory": { + "id": "route-aggregator", + "type": "entaxy.runtime.route", + "parent": "route-callable", + "isAbstract": false, + "displayName": "AGGREGATOR", + "description": "The Aggregator from the EIP patterns allows you to combine a number of messages together into a single message. For more details see Entaxy docs and Camel docs" + }, + "entaxy.runtime.route": { + "targetRouteContainerType": "LIBRARY", + "routePattern": "AGGREGATOR", + "routeIsCallable": true + }, + "fields": { + "aggregatorId": { + "type": "String", + "required": true, + "isHidden": true, + "defaultValue": { + "@CALCULATED": { + "expression": "${objectId}-aggregator", + "lazy": false, + "resultType": "String" + } + } + } + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + }, + "fields": { + "aggregatorId": {}, + "routeContent": { + "displayName": "On-complete route", + "description": "A route configuration that executes after the aggregation process is finalized. The router that connects the system to other entities in the Entaxy architecture. By default, the message is routed to an entity of the system type. For more details see Camel docs" + }, + "camel_completionTimeout": { + "group": "completion" + }, + "camel_completionTimeoutExpression": { + "group": "completion" + }, + "camel_completionInterval": { + "group": "completion" + }, + "camel_completionSize": { + "group": "completion" + }, + "camel_completionSizeExpression": { + "group": "completion" + }, + "camel_completionPredicate": { + "group": "completion" + }, + "camel_completionFromBatchConsumer": { + "group": "completion" + }, + "camel_forceCompletionOnStop": { + "group": "completion" + }, + "camel_aggregateControllerRef": { + "group": "completion" + }, + "@IMPORT": [ + { + "sourceFactoryId": "model-aggregate", + "location": "outputs.init.fields", + "prefix": "" + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-callable-in-object.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-callable-in-object.json new file mode 100644 index 00000000..14976d58 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-callable-in-object.json @@ -0,0 +1,37 @@ +{ + "factory": { + "id": "route-callable-in-object", + "type": "entaxy.runtime.route", + "parent": "route-callable", + "isAbstract": false, + "displayName": "ROUTE :: CALLABLE", + "description": "Dynamically created routes that can be called programmatically. For more details see Entaxy docs" + }, + "entaxy.runtime.route": { + "targetRouteContainerType": "OBJECT" + }, + "fields": { + "globalCallMode": { + "@TYPEINFO": { + "values": [ + "NONE" + ] + }, + "isHidden": true, + "defaultValue": "NONE" + }, + "localCallMode": { + "@TYPEINFO": { + "type": "enum", + "values": [ + "SYNC", + "ASYNC", + "BOTH" + ] + }, + "defaultValue": "SYNC" + } + }, + "outputs": { + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-callable.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-callable.json new file mode 100644 index 00000000..92dcc0e2 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-callable.json @@ -0,0 +1,79 @@ +{ + "factory": { + "id": "route-callable", + "type": "entaxy.runtime.route", + "parent": "abstract-route", + "isAbstract": false, + "displayName": "ROUTE :: CALLABLE", + "description": "Dynamically created routes that can be called programmatically. For more details see Entaxy docs" + }, + "entaxy.runtime.route": { + "targetRouteContainerType": "LIBRARY", + "routeType": "CALLABLE", + "routeIsCallable": true + }, + "fields": { + "globalCallMode": { + "displayName": "Global call mode", + "description": "Defines how to call the route from all Entaxy entities", + "type": "String", + "required": true, + "group": "main", + "@TYPEINFO": { + "type": "enum", + "values": [ + "NONE", + "SYNC", + "ASYNC", + "BOTH" + ] + }, + "defaultValue": "SYNC" + }, + "localCallMode": { + "displayName": "Local call mode", + "type": "String", + "description": "Defines how to call the route from the current Entaxy entity", + "required": true, + "group": "main", + "@TYPEINFO": { + "type": "enum", + "values": [ + "NONE", + "SYNC", + "ASYNC", + "BOTH" + ] + }, + "defaultValue": "NONE" + }, + "##publish": { + "defaultValue": { + "routeGlobalCallMode": { + "@CALCULATED": { + "expression": "${properties.globalCallMode}", + "lazy": false + } + }, + "routeLocalCallMode": { + "@CALCULATED": { + "expression": "${properties.localCallMode}", + "lazy": false + } + } + } + } + }, + "outputs": { + "init": { + "isDefault": true, + "fields": { + "localCallMode": {}, + "globalCallMode": {} + }, + "config": { + "configurable": false + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-library.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-library.json new file mode 100644 index 00000000..392b9680 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-library.json @@ -0,0 +1,28 @@ +{ + "factory": { + "id": "route-library", + "type": "entaxy.runtime.route-library", + "description": "Factory route-library of entaxy.runtime.route-container", + "isAbstract": false, + "parent": "abstract-route-container" + }, + "entaxy.runtime.route-library": { + "routeContainerType": "LIBRARY" + }, + "fields": { + "routes": { + "itemFactory": { + "filter": "(&(type=entaxy.runtime.route)(isAbstract=false)(|(typeinfo.targetRouteContainerType=ANY)(typeinfo.targetRouteContainerType=LIBRARY)))" + } + } + + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + } + } + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-quartz.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-quartz.json new file mode 100644 index 00000000..0f80dd7d --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-quartz.json @@ -0,0 +1,41 @@ +{ + "factory": { + "id": "route-quartz", + "type": "entaxy.runtime.route", + "parent": "route-scheduled", + "isAbstract": false, + "displayName": "QUARTZ", + "description": "Schedule sending of messages using the Quartz 2.x scheduler. For more details see Entaxy docs and Camel docs" + }, + "entaxy.runtime.route": { + "routePattern": "QUARTZ" + }, + "fields": { +//don't work on two nodes at the same time +//"runExclusive": { +// "displayName": "Run Exclusive", +// "type": "Boolean", +// "immutable": true, +// "required": true, +// "defaultValue": true +// } + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + }, + "fields": { +// "runExclusive": {}, + "@IMPORT": [ + { + "sourceFactoryId": "model-quartz", + "location": "outputs.init.fields", + "prefix": "" + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-scheduled.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-scheduled.json new file mode 100644 index 00000000..ad215250 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-scheduled.json @@ -0,0 +1,16 @@ +{ + "factory": { + "id": "route-scheduled", + "type": "entaxy.runtime.route", + "parent": "route-self-started", + "isAbstract": true, + "description": "Factory route-scheduled of entaxy.runtime.route" + }, + "entaxy.runtime.route": { + "routeType": "SCHEDULED" + }, + "fields": { + }, + "outputs": { + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-self-started.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-self-started.json new file mode 100644 index 00000000..e8a077d4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-self-started.json @@ -0,0 +1,17 @@ +{ + "factory": { + "id": "route-self-started", + "type": "entaxy.runtime.route", + "parent": "abstract-route", + "isAbstract": true, + "description": "Factory route-self-started of entaxy.runtime.route" + }, + "entaxy.runtime.route": { + "targetRouteContainerType": "ANY", + "routeType": "SELF-STARTED" + }, + "fields": { + }, + "outputs": { + } +} \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-timer.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-timer.json new file mode 100644 index 00000000..c3558cc9 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/routes/route-timer.json @@ -0,0 +1,79 @@ +{ + "factory": { + "id": "route-timer", + "type": "entaxy.runtime.route", + "parent": "route-scheduled", + "isAbstract": false, + "displayName": "TIMER", + "description": "The Timer component is used to generate message exchanges when a timer fires. You can only consume events from this endpoint. For more details see Entaxy docs and Camel docs" + }, + "entaxy.runtime.route": { + "routePattern": "TIMER" + }, + "fields": { + "runExclusive": { + "displayName": "Run Exclusive", + "description": "Run only on one node of cluster. For more details see Camel docs", + "type": "Boolean", + "immutable": true, + "defaultValue": true, + "required": true, + "@VARIANTS": { + "property": "exclusiveMode", + "values": { + "BOTH": { + "defaultValue": false + }, + "EXCLUSIVE_ONLY": { + "isHidden": true, + "fixedValue": true, + "defaultValue": true + }, + "NON_EXCLUSIVE_ONLY": { + "isHidden": true, + "fixedValue": false, + "defaultValue": false + } + } + } + }, + "exclusivePrefix": { + "type": "String", + "isHidden": true, + "condition": "${runExclusive}", + "@INTERNAL": true, + "required": true, + "defaultValue": { + "@CALCULATED": { + "expression": "master:${objectId}:", + "lazy": true + } + } + } + }, + "outputs": { + "init": { + "isDefault": true, + "config": { + "configurable": false + }, + "fields": { + "runExclusive": {}, + "exclusivePrefix": {}, + "routeContent": { + "displayName": "Route content" + }, + "timerName": { + "group": "general" + }, + "@IMPORT": [ + { + "sourceFactoryId": "model-timer", + "location": "outputs.init.fields", + "prefix": "" + } + ] + } + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/ssl-context-parameters.json b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/ssl-context-parameters.json new file mode 100644 index 00000000..7114db6a --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/factory/ssl-context-parameters.json @@ -0,0 +1,265 @@ +{ + "factory": { + "id": "ssl-context-parameters", + "type": "entaxy.runtime.route.component", + "isAbstract": false, + "parent": "base-object", + "label": "security", + "group": "ssl context parameters" + }, + "entaxy.runtime.route.component": {}, + "fields": { + "camel_sslContextParameters": { + "displayName": "Ssl Context Parameters", + "description": "To configure security using SSLContextParameters. Use the visual configuration option with basic settings or if you need more fine-tuning, create beans and select the custom option. SSLContextParameters creation description in Apache Camel manual", + "label": "security", + "type": "string", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "##origin": "camel", + "kind": [ + "property", + "parameter" + ], + "@TYPEINFO": { + "type": "enum", + "emptyOptionName": "default", + "values": [ + "visual configuration", + "custom" + ] + }, + "@UI": { + "manageDisplayBlocksByValue": true + } + }, + "sslContextParametersReference": { + "displayName": "Reference", + "description": "Reference to custom SSLContextParameters without leading #", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "defaultValue": "sslContextParameters", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["custom"], + "required": true + } + }, + "sslContextParametersKeyManagersPass": { + "displayName": "KeyManagers password", + "description": "The optional password for recovering keys in the key store. Used by the KeyManagerFactory that creates the KeyManagers represented by this object's configuration.", + "label": "advanced", + "type": "password", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "defaultValue": "", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "sslContextParametersKeyManagersKeyStoreResource": { + "displayName": "KeyManagers KeyStore resource path", + "description": "The optional file path, class path resource, or URL of the resource used to load the key store.", + "type": "Url", + "kind": "parameter", + "required": false, + "group": "ssl context parameters", + "@TYPEINFO": { + "resourceProvider": "entaxy-keystore", + "filter": ["*.jks", "*.pkcs12" + ], + "target": "resource" + }, + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "sslContextParametersKeyManagersKeyStoreType": { + "displayName": "KeyManagers KeyStore type", + "description": "The optional type of the key store to load. See Appendix A in the Java Cryptography Architecture Standard Algorithm Name Documentation for more information on standard names.", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "defaultValue": "", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "sslContextParametersKeyManagersKeyStorePass": { + "displayName": "KeyManagers KeyStore password", + "description": "The optional password for reading/opening/verifying the key store.", + "label": "advanced", + "type": "password", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "defaultValue": "", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "sslContextParametersTrustManagersKeyStoreResource": { + "displayName": "TrustManagers KeyStore resource path", + "description": "The optional file path, class path resource, or URL of the resource used to load the key store.", + "type": "Url", + "kind": "parameter", + "required": false, + "group": "ssl context parameters", + "@TYPEINFO": { + "resourceProvider": "entaxy-keystore", + "filter": ["*.jks", "*.pkcs12" + ], + "target": "resource" + }, + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "sslContextParametersTrustManagersKeyStoreType": { + "displayName": "TrustManagers KeyStore type", + "description": "The optional type of the key store to load. See Appendix A in the Java Cryptography Architecture Standard Algorithm Name Documentation for more information on standard names.", + "label": "advanced", + "type": "string", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "defaultValue": "", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "sslContextParametersTrustManagersKeyStorePass": { + "displayName": "TrustManagers KeyStore password", + "description": "The optional password for reading/opening/verifying the key store.", + "label": "advanced", + "type": "password", + "kind": "parameter", + "required": false, + "hidden": false, + "group": "ssl context parameters", + "defaultValue": "", + "@UI": { + "transmitAlways": false, + "displayBlocks": ["visual configuration"], + "required": false + } + }, + "__sslContextParametersTemplate": { + "type": "entaxy.runtime.connector", + "isRef": true, + "required": true, + "isHidden": true, + "isRefByValueOnly": true, + "@INTERNAL": true, + "defaultValue": { + "type": "entaxy.runtime.connector", + "factoryId": "#OWNER#", + "outputType": "ssl-context-parameters", + "scope": "private", + "properties": { + "sslContextParameters": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.camel_sslContextParameters}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersPass": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersPass}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersKeyStoreResource": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersKeyStoreResource}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersKeyStoreType": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersKeyStoreType}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersKeyManagersKeyStorePass": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersKeyManagersKeyStorePass}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersTrustManagersKeyStoreResource": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersTrustManagersKeyStoreResource}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersTrustManagersKeyStoreType": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersTrustManagersKeyStoreType}", + "fallbackObject": null, + "lazy": false + } + }, + "sslContextParametersTrustManagersKeyStorePass": { + "@CALCULATED": { + "expression": "${#OWNER#.properties.sslContextParametersTrustManagersKeyStorePass}", + "fallbackObject": null, + "lazy": false + } + } + } + } + } + }, + "outputs": { + "init": { + "fields": { + "__sslContextParametersTemplate": {} + }, + "scopes": ["private"] + }, + "ssl-context-parameters": { + "fields": { + "sslContextParameters": {}, + "sslContextParametersKeyManagersPass": {}, + "sslContextParametersKeyManagersKeyStoreResource": {}, + "sslContextParametersKeyManagersKeyStoreType": {}, + "sslContextParametersKeyManagersKeyStorePass": {}, + "sslContextParametersTrustManagersKeyStoreResource": {}, + "sslContextParametersTrustManagersKeyStoreType": {}, + "sslContextParametersTrustManagersKeyStorePass": {} + }, + "scopes": ["private"] + } + } +} diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-route/routeContent.xml b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-route/routeContent.xml new file mode 100644 index 00000000..143d44ea --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/resource/entaxy-file-internal/factories/abstract-route/routeContent.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-aggregation-strategy-camel-simple/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-aggregation-strategy-camel-simple/init.ftl new file mode 100644 index 00000000..d8026c2a --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-aggregation-strategy-camel-simple/init.ftl @@ -0,0 +1,3 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-connector/generate-logging-key.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-connector/generate-logging-key.ftl new file mode 100644 index 00000000..643dd658 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-connector/generate-logging-key.ftl @@ -0,0 +1,16 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#if properties.generateLoggingKey?? && properties.generateLoggingKey] + + [=properties.displayName] + + + ${headers.ENTAXY_MessageUUID} + + + ${headers.ENTAXY_Destination} + + + [=profile] + + +[/#if] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-connector/ssl-context-parameters.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-connector/ssl-context-parameters.ftl new file mode 100644 index 00000000..7d8869de --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-connector/ssl-context-parameters.ftl @@ -0,0 +1,57 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#if properties.sslContextParameters?? && properties.sslContextParameters == "visual configuration"] +[#-- + + + + + + + + +--] + [#if properties.sslContextParametersKeyManagersKeyStoreResource?? && properties.sslContextParametersKeyManagersKeyStoreResource?has_content] + + [#if properties.sslContextParametersKeyManagersKeyStoreResource?? && properties.sslContextParametersKeyManagersKeyStoreResource?has_content] + + [/#if] + [#if properties.sslContextParametersKeyManagersKeyStorePass?? && properties.sslContextParametersKeyManagersKeyStorePass?has_content] + + [/#if] + [#if properties.sslContextParametersKeyManagersKeyStoreType?? && properties.sslContextParametersKeyManagersKeyStoreType?has_content] + + [/#if] + + + + [#if properties.sslContextParametersKeyManagersPass?? && properties.sslContextParametersKeyManagersPass?has_content] + + [/#if] + + [/#if] + + [#if properties.sslContextParametersTrustManagersKeyStoreResource?? && properties.sslContextParametersTrustManagersKeyStoreResource?has_content] + + [#if properties.sslContextParametersTrustManagersKeyStoreResource?? && properties.sslContextParametersTrustManagersKeyStoreResource?has_content] + + [/#if] + [#if properties.sslContextParametersTrustManagersKeyStorePass?? && properties.sslContextParametersTrustManagersKeyStorePass?has_content] + + [/#if] + [#if properties.sslContextParametersTrustManagersKeyStoreType?? && properties.sslContextParametersTrustManagersKeyStoreType?has_content] + + [/#if] + + + + + [/#if] + + [#if properties.sslContextParametersKeyManagersKeyStoreResource?? && properties.sslContextParametersKeyManagersKeyStoreResource?has_content] + + [/#if] + [#if properties.sslContextParametersTrustManagersKeyStoreResource?? && properties.sslContextParametersTrustManagersKeyStoreResource?has_content] + + [/#if] + +[/#if] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/errorHandler.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/errorHandler.ftl new file mode 100644 index 00000000..f1750fb4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/errorHandler.ftl @@ -0,0 +1,31 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[=properties.errorHandlerType] + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/globalOptions.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/globalOptions.ftl new file mode 100644 index 00000000..8fbec1ca --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/globalOptions.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/init.ftl new file mode 100644 index 00000000..1edddc4b --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route-container/init.ftl @@ -0,0 +1,30 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#-- + + ~~~~~~licensing~~~~~~ + factory-provider-archetype + ========== + 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~~~~~~ + +--] + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route/init.ftl new file mode 100644 index 00000000..94c094ed --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/abstract-route/init.ftl @@ -0,0 +1,8 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + [#if properties.routeProperties??] + [#list properties.routeProperties as key, value] + + [/#list] + [/#if] + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-camel-memory/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-camel-memory/init.ftl new file mode 100644 index 00000000..08dcdb2a --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-camel-memory/init.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#-- empty, because it is default value --] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-ignite/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-ignite/init.ftl new file mode 100644 index 00000000..f7a76c8f --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-ignite/init.ftl @@ -0,0 +1,8 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + + + + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-jdbc/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-jdbc/init.ftl new file mode 100644 index 00000000..743a2f36 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-jdbc/init.ftl @@ -0,0 +1,15 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + + + + + + + + + + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-postgre/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-postgre/init.ftl new file mode 100644 index 00000000..c4f20283 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-repository-entaxy-postgre/init.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#include "templates:aggregation-repository-entaxy-jdbc/init.ftl"] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-strategy-camel-string/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-strategy-camel-string/init.ftl new file mode 100644 index 00000000..bd67008d --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/aggregation-strategy-camel-string/init.ftl @@ -0,0 +1,4 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/common-expression/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/common-expression/init.ftl new file mode 100644 index 00000000..46b0f4a4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/common-expression/init.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +<[=properties.expressionLanguage] xmlns="http://camel.apache.org/schema/blueprint">[=properties.expression] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-aggregate/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-aggregate/init.ftl new file mode 100644 index 00000000..523ba185 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-aggregate/init.ftl @@ -0,0 +1,34 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + [=properties.camel_correlationExpression] + + [#if properties.camel_completionPredicate??] + + [=properties.camel_completionPredicate] + + [/#if] + [#if properties.camel_completionTimeoutExpression??] + + [=properties.camel_completionTimeoutExpression] + + [/#if] + [#if properties.camel_completionSizeExpression??] + + [=properties.camel_completionSizeExpression] + + [/#if] + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-quartz/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-quartz/init.ftl new file mode 100644 index 00000000..f3792209 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-quartz/init.ftl @@ -0,0 +1,2 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-timer/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-timer/init.ftl new file mode 100644 index 00000000..5c4e8b24 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/model-timer/init.ftl @@ -0,0 +1,7 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + +[#if properties.runExclusive?? && properties.runExclusive && properties.exclusivePrefix??] + [#assign finalExclusivePrefix = properties.exclusivePrefix] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-aggregator/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-aggregator/init.ftl new file mode 100644 index 00000000..35ebb521 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-aggregator/init.ftl @@ -0,0 +1,9 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + [#include "templates:model-aggregate/init.ftl"] + [#if properties.routeProperties??] + [#list properties.routeProperties as key, value] + + [/#list] + [/#if] + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-callable/__init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-callable/__init.ftl new file mode 100644 index 00000000..4b5ad2a4 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-callable/__init.ftl @@ -0,0 +1,30 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#-- + + ~~~~~~licensing~~~~~~ + factory-provider-archetype + ========== + 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~~~~~~ + +--] + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-library/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-library/init.ftl new file mode 100644 index 00000000..0d66f34b --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-library/init.ftl @@ -0,0 +1,10 @@ +[#ftl attributes={"generated.type":"blueprint"}] + + + + + + + \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-quartz/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-quartz/init.ftl new file mode 100644 index 00000000..5489e5ec --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-quartz/init.ftl @@ -0,0 +1,58 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#import "templates:object-commons/common-utils.ftl" as utils] + + + + + + + + + + + + + [=objectId] + AUTO + + true + false + false + false + true + + org.quartz.impl.jdbcjobstore.PostgreSQLDelegate + true + + [#-- don't work on two nodes at the same time --] +[#-- [#if properties.runExclusive?? && properties.runExclusive]--] +[#-- true--] +[#-- [#else]--] +[#-- false--] +[#-- [/#if]--] + + 5000 + org.quartz.impl.jdbcjobstore.JobStoreTX + cache + osgi:service/entaxy.esb.cache + + org.quartz.simpl.SimpleThreadPool + 10 + 5 + true + + 60000 + + + +[#--кластер--] + + + [#include "templates:model-quartz/init.ftl"] + [#if properties.routeProperties??] + [#list properties.routeProperties as key, value] + + [/#list] + [/#if] + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-timer/init.ftl b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-timer/init.ftl new file mode 100644 index 00000000..23b32237 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-producing/src/main/resources/ru/entaxy/templates/route-timer/init.ftl @@ -0,0 +1,18 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] +[#import "templates:object-commons/common-utils.ftl" as utils] + + + + + + + + + [#include "templates:model-timer/init.ftl"] + [#if properties.routeProperties??] + [#list properties.routeProperties as key, value] + + [/#list] + [/#if] + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-runtime/LICENSE.txt b/platform/runtime/core/objects-implementations/route-implementation/route-runtime/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-runtime/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-runtime/pom.xml b/platform/runtime/core/objects-implementations/route-implementation/route-runtime/pom.xml new file mode 100644 index 00000000..9572f962 --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-runtime/pom.xml @@ -0,0 +1,30 @@ + + + 4.0.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations + route-implementation + 1.10.0 + + ru.entaxy.esb.platform.runtime.core.objects-implementations.route-implementation + route-runtime + bundle + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: ROUTE :: RUNTIME + ENTAXY :: PLATFORM :: CORE :: OBJECTS IMPLEMENTATIONS :: ROUTE :: RUNTIME + + + + org.apache.felix + maven-bundle-plugin + true + + + true + true + + + + + + diff --git a/platform/runtime/core/objects-implementations/route-implementation/route-runtime/src/main/resources/OSGI-INF/blueprint/log-context.xml b/platform/runtime/core/objects-implementations/route-implementation/route-runtime/src/main/resources/OSGI-INF/blueprint/log-context.xml new file mode 100644 index 00000000..12ccfcdd --- /dev/null +++ b/platform/runtime/core/objects-implementations/route-implementation/route-runtime/src/main/resources/OSGI-INF/blueprint/log-context.xml @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + ${exchangeProperty.requestId} == null || ${exchangeProperty.requestId.length()} == 0 + + ${bean:uuidGenerator.toString} + + + + + ${body} + + + {} + + + + + + + + + + + + ${exchangeProperty.requestId}#${body}# + + + + ${exchangeProperty.loggingKey} + + + + ${exchangeProperty.bodyHolder} + + + + + + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-components/generateLoggingKey.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-components/generateLoggingKey.ftl new file mode 100644 index 00000000..d462fc43 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-components/generateLoggingKey.ftl @@ -0,0 +1,19 @@ +[#ftl attributes={"generated.type":"blueprint"}] + [#if properties.generateLoggingKey?? && properties.generateLoggingKey] + + [=objectId] + + + ${headers.CamelHttpMethod} + + + ${headers.ENTAXY_MessageUUID} + + + ${headers.ENTAXY_Destination} + + + ${headers.X-User} + + +[/#if] \ No newline at end of file diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterConnector.bak.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterConnector.bak.ftl new file mode 100644 index 00000000..c9ced9c8 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterConnector.bak.ftl @@ -0,0 +1,21 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + +[#if properties.service??] + [#if properties.service.operations??] + [#list properties.service.operations as path, operationData] + [#list operationData as verb, operation] + + + + + [/#list] + [/#list] + + + + [/#if] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterProtected.bak.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterProtected.bak.ftl new file mode 100644 index 00000000..3f0f4c48 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterProtected.bak.ftl @@ -0,0 +1,23 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + +[#if properties.service??] + [#if properties.service.operations??] + [#list properties.service.operations as path, operationData] + [#list operationData as verb, operation] + + + + + + [/#list] + [/#list] + + + + [/#if] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterPublic.bak.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterPublic.bak.ftl new file mode 100644 index 00000000..b65984f6 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-openapi/operationRouterPublic.bak.ftl @@ -0,0 +1,22 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + +[#if properties.service??] + [#if properties.service.operations??] + [#list properties.service.operations as path, operationData] + [#list operationData as verb, operation] + + + + + [/#list] + [/#list] + + + + [/#if] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterConnector.bak.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterConnector.bak.ftl new file mode 100644 index 00000000..50fc6e7f --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterConnector.bak.ftl @@ -0,0 +1,18 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + +[#if properties.service??] + [#if properties.service.port??] + [#list properties.service.port.operations as operation] + + + + [/#list] + + + + [/#if] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterProtected.bak.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterProtected.bak.ftl new file mode 100644 index 00000000..e0b08837 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterProtected.bak.ftl @@ -0,0 +1,20 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + +[#if properties.service??] + [#if properties.service.port??] + [#list properties.service.port.operations as operation] + + + + + [/#list] + + + + [/#if] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterPublic.bak.ftl b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterPublic.bak.ftl new file mode 100644 index 00000000..01ada84f --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-producing/src/main/resources/ru/entaxy/templates/service-resources-soap/operationRouterPublic.bak.ftl @@ -0,0 +1,19 @@ +[#ftl attributes={"generated.type":"blueprint.fragment"}] + + + + +[#if properties.service??] + [#if properties.service.port??] + [#list properties.service.port.operations as operation] + + + + [/#list] + + + + [/#if] +[/#if] + + diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/DisableWSDLGetInterceptor.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/DisableWSDLGetInterceptor.java new file mode 100644 index 00000000..804c228a --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/DisableWSDLGetInterceptor.java @@ -0,0 +1,63 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-runtime + * ========== + * 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~~~~~~ + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + */ + +package ru.entaxy.platform.services.runtime.interceptor; + +import org.apache.cxf.frontend.WSDLGetInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; + +public class DisableWSDLGetInterceptor extends AbstractPhaseInterceptor { + public static final DisableWSDLGetInterceptor INSTANCE = new DisableWSDLGetInterceptor(); + public static final String DOCUMENT_HOLDER = DisableWSDLGetInterceptor.class.getName() + ".documentHolder"; + + public DisableWSDLGetInterceptor() { + super(Phase.READ); + getBefore().remove(WSDLGetInterceptor.class.getName()); + getAfter().remove(WSDLGetInterceptor.class.getName()); + } + + public void handleMessage(Message message) throws Fault { + message.getInterceptorChain().remove(WSDLGetInterceptor.INSTANCE); + return; + } +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/PostAuthWSDLGetInterceptor.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/PostAuthWSDLGetInterceptor.java new file mode 100644 index 00000000..40d4c45d --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/PostAuthWSDLGetInterceptor.java @@ -0,0 +1,162 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-runtime + * ========== + * 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~~~~~~ + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + */ + +package ru.entaxy.platform.services.runtime.interceptor; + +import java.util.Iterator; +import java.util.Map; + +import org.apache.cxf.binding.soap.interceptor.EndpointSelectionInterceptor; +import org.apache.cxf.common.util.StringUtils; +import org.apache.cxf.common.util.UrlUtils; +import org.apache.cxf.endpoint.Endpoint; +import org.apache.cxf.frontend.WSDLGetInterceptor; +import org.apache.cxf.frontend.WSDLGetOutInterceptor; +import org.apache.cxf.frontend.WSDLGetUtils; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.interceptor.Interceptor; +import org.apache.cxf.interceptor.MessageSenderInterceptor; +import org.apache.cxf.interceptor.OutgoingChainInterceptor; +import org.apache.cxf.interceptor.StaxOutInterceptor; +import org.apache.cxf.message.Message; +import org.apache.cxf.message.MessageImpl; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.transport.common.gzip.GZIPOutInterceptor; +import org.w3c.dom.Document; + +public class PostAuthWSDLGetInterceptor extends AbstractPhaseInterceptor { + public static final PostAuthWSDLGetInterceptor INSTANCE = new PostAuthWSDLGetInterceptor(); + public static final String DOCUMENT_HOLDER = WSDLGetInterceptor.class.getName() + ".documentHolder"; + private static final String TRANSFORM_SKIP = "transform.skip"; + private Interceptor wsdlGetOutInterceptor = WSDLGetOutInterceptor.INSTANCE; + + public PostAuthWSDLGetInterceptor() { + super(Phase.UNMARSHAL); + getBefore().remove(WSDLGetInterceptor.class.getName()); + getAfter().add(EndpointSelectionInterceptor.class.getName()); + } + + public PostAuthWSDLGetInterceptor(Interceptor outInterceptor) { + this(); + // Let people override the wsdlGetOutInterceptor + wsdlGetOutInterceptor = outInterceptor; + } + + public void handleMessage(Message message) throws Fault { + String method = (String) message.get(Message.HTTP_REQUEST_METHOD); + String query = (String) message.get(Message.QUERY_STRING); + + if (!"GET".equals(method) || StringUtils.isEmpty(query)) { + return; + } + + String baseUri = (String) message.get(Message.REQUEST_URL); + String ctx = (String) message.get(Message.PATH_INFO); + + WSDLGetUtils utils = (WSDLGetUtils) message.getContextualProperty(WSDLGetUtils.class.getName()); + if (utils == null) { + utils = new WSDLGetUtils(); + message.put(WSDLGetUtils.class, utils); + } + Map map = UrlUtils.parseQueryString(query); + if (isRecognizedQuery(map)) { + Document doc = getDocument(utils, message, baseUri, map, ctx); + + Endpoint e = message.getExchange().getEndpoint(); + Message mout = new MessageImpl(); + mout.setExchange(message.getExchange()); + mout = e.getBinding().createMessage(mout); + mout.setInterceptorChain(OutgoingChainInterceptor.getOutInterceptorChain(message.getExchange())); + message.getExchange().setOutMessage(mout); + + mout.put(DOCUMENT_HOLDER, doc); + mout.put(Message.CONTENT_TYPE, "text/xml"); + + // just remove the interceptor which should not be used + cleanUpOutInterceptors(mout); + + // notice this is being added after the purge above, don't swap the order! + mout.getInterceptorChain().add(wsdlGetOutInterceptor); + + message.getExchange().put(TRANSFORM_SKIP, Boolean.TRUE); + // skip the service executor and goto the end of the chain. + message.getInterceptorChain().doInterceptStartingAt( + message, + OutgoingChainInterceptor.class.getName()); + } + } + + protected void cleanUpOutInterceptors(Message outMessage) { + // TODO - how can I improve this to provide a specific interceptor chain that just has the + // stax, gzip and message sender components, while also ensuring that GZIP is only provided + // if its already configured for the endpoint. + Iterator> iterator = outMessage.getInterceptorChain().iterator(); + while (iterator.hasNext()) { + Interceptor inInterceptor = iterator.next(); + if (!inInterceptor.getClass().equals(StaxOutInterceptor.class) + && !inInterceptor.getClass().equals(GZIPOutInterceptor.class) + && !inInterceptor.getClass().equals(MessageSenderInterceptor.class)) { + outMessage.getInterceptorChain().remove(inInterceptor); + } + } + + } + + private Document getDocument(WSDLGetUtils utils, + Message message, String base, + Map params, String ctxUri) { + // cannot have two wsdl's being generated for the same endpoint at the same + // time as the addresses may get mixed up + // For WSDL's the WSDLWriter does not share any state between documents. + // For XSD's, the WSDLGetUtils makes a copy of any XSD schema documents before updating + // any addresses and returning them, so for both WSDL and XSD this is the only part that + // needs + // to be synchronized. + synchronized (message.getExchange().getEndpoint()) { + return utils.getDocument(message, base, params, ctxUri, + message.getExchange().getEndpoint().getEndpointInfo()); + } + } + + private boolean isRecognizedQuery(Map map) { + return map.containsKey("wsdl") || map.containsKey("xsd"); + } +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/PublicOpenApiSchemaInterceptor.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/PublicOpenApiSchemaInterceptor.java new file mode 100644 index 00000000..86ae0d90 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/PublicOpenApiSchemaInterceptor.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-runtime + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.services.runtime.interceptor; + +import java.net.URL; +import java.security.Principal; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.security.SecurityContext; +import org.apache.cxf.transport.http.Headers; +import ru.entaxy.platform.core.support.runtime.cxf.security.AnonymousSecurityContext; + +public class PublicOpenApiSchemaInterceptor extends AbstractPhaseInterceptor { + + private static final Log LOG = LogFactory.getLog(PublicOpenApiSchemaInterceptor.class); + + public static final List SERVICE_SCHEMA_QUERY = new ArrayList<>(); + public static final List SERVICE_SCHEMA_FILE = new ArrayList<>(); + + static { + // SERVICE_SCHEMA_QUERY.add("wsdl"); + SERVICE_SCHEMA_QUERY.add("wadl"); + SERVICE_SCHEMA_QUERY.add("swagger.json"); + SERVICE_SCHEMA_QUERY.add("open-api.json"); + SERVICE_SCHEMA_QUERY.add("open-api.yaml"); + + SERVICE_SCHEMA_FILE.add(".*\\/openapi\\.json"); + SERVICE_SCHEMA_FILE.add(".*\\/openapi\\.yaml"); + SERVICE_SCHEMA_FILE.add(".*\\/favicon.*\\.png"); + SERVICE_SCHEMA_FILE.add(".*api-docs"); + SERVICE_SCHEMA_FILE.add(".*\\/swagger-ui[^.]*\\.\\w*"); + } + + public PublicOpenApiSchemaInterceptor() { + super(Phase.RECEIVE); + } + + @Override + public void handleMessage(Message message) throws Fault { + Map> headers = Headers.getSetProtocolHeaders(message); + + boolean isAllowedSchemaRequest = checkOnSchema(message); + + if (isAllowedSchemaRequest) { + // we create simple SecurityContext with anonymous user + message.put(SecurityContext.class, new AnonymousSecurityContext()); + } + + headers.put(AnonymousSecurityContext.HEADER_IS_DISPLAY_SERVICE_SERVICE, + Collections.singletonList(String.valueOf(isAllowedSchemaRequest))); + } + + private boolean checkOnSchema(Message message) { + + Object params = message.get(Message.QUERY_STRING); + + for (String schema : SERVICE_SCHEMA_QUERY) { + if (params != null && Pattern.matches(schema, params.toString())) + return true; + } + + params = message.get(Message.REQUEST_URL); + try { + URL requestUrl = new URL(params.toString()); + for (String schema : SERVICE_SCHEMA_FILE) { + if (Pattern.matches(schema, requestUrl.getFile())) + return true; + } + } catch (Exception e) { + + } + + return false; + } +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/ResolveLoginInterceptor.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/ResolveLoginInterceptor.java new file mode 100644 index 00000000..4c6ec8c1 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/ResolveLoginInterceptor.java @@ -0,0 +1,60 @@ +/*- + * ~~~~~~licensing~~~~~~ + * basic-auth-impl + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.services.runtime.interceptor; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.security.LoginSecurityContext; +import org.apache.cxf.security.SecurityContext; +import org.apache.cxf.transport.http.Headers; + +public class ResolveLoginInterceptor extends AbstractPhaseInterceptor { + + public static final String HEADER_USER = "X-User"; + + public ResolveLoginInterceptor() { + super(Phase.POST_UNMARSHAL); + } + + public void handleMessage(Message message) throws Fault { + SecurityContext sc = message.get(SecurityContext.class); + if ((sc != null) && (sc instanceof LoginSecurityContext)) { + LoginSecurityContext lsc = (LoginSecurityContext) sc; + String login = lsc.getUserPrincipal().getName(); + + Map> headers = Headers.getSetProtocolHeaders(message); + headers.put(HEADER_USER, Collections.singletonList(login)); + } + return; + } + +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/ResolveProfileNameInterceptor.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/ResolveProfileNameInterceptor.java new file mode 100644 index 00000000..27bca023 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/ResolveProfileNameInterceptor.java @@ -0,0 +1,92 @@ +/*- + * ~~~~~~licensing~~~~~~ + * service-runtime + * ========== + * 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~~~~~~ + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more contributor license + * agreements. See the NOTICE file distributed with this work for additional information regarding + * copyright ownership. The ASF licenses this file to you 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. + */ + +package ru.entaxy.platform.services.runtime.interceptor; + +import java.security.Principal; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.message.Message; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.security.LoginSecurityContext; +import org.apache.cxf.security.SecurityContext; +import org.apache.cxf.transport.http.Headers; + +import javax.ws.rs.ForbiddenException; + +public class ResolveProfileNameInterceptor extends AbstractPhaseInterceptor { + + public static final String SYSTEM_ROLE_PREFIX = "PROFILE_"; + + public static final String HEADER_SYSTEM_NAME = "X-SystemName"; + public static final String HEADER_SYSTEM_UUID = "X-SystemUuid"; + public static final String HEADER_SYSTEM_ID = "X-SystemId"; + + public ResolveProfileNameInterceptor() { + super(Phase.UNMARSHAL); + } + + public void handleMessage(Message message) throws Fault { + SecurityContext sc = message.get(SecurityContext.class); + if ((sc != null) && (sc instanceof LoginSecurityContext)) { + LoginSecurityContext lsc = (LoginSecurityContext) sc; + boolean found = false; + for (Principal p : lsc.getUserRoles()) { + if (p.getName().startsWith(SYSTEM_ROLE_PREFIX)) { + Map> headers = Headers.getSetProtocolHeaders(message); + String systemName = p.getName().substring(SYSTEM_ROLE_PREFIX.length()); + headers.put(HEADER_SYSTEM_ID, Collections.singletonList(systemName)); + headers.put(HEADER_SYSTEM_UUID, Collections.singletonList(systemName)); + headers.put(HEADER_SYSTEM_NAME, Collections.singletonList(systemName)); + found = true; + break; + } + } + if (!found) { + throw new Fault(new ForbiddenException("Associated profile not found")); + } + } + return; + } +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/SOAPValidateInterceptor.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/SOAPValidateInterceptor.java new file mode 100644 index 00000000..084609a5 --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/SOAPValidateInterceptor.java @@ -0,0 +1,130 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.services.runtime.interceptor; + +import java.io.IOException; +import java.util.List; + +import javax.xml.soap.SOAPMessage; +import javax.xml.stream.XMLStreamException; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; +import javax.xml.xpath.XPathExpressionException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.cxf.binding.soap.SoapMessage; +import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor; +import org.apache.cxf.interceptor.Fault; +import org.apache.cxf.phase.AbstractPhaseInterceptor; +import org.apache.cxf.phase.Phase; +import org.apache.cxf.service.Service; +import org.apache.cxf.service.model.ServiceModelUtil; +import org.apache.cxf.ws.addressing.EndpointReferenceUtils; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +import ru.entaxy.platform.services.runtime.utils.XmlParser; + +public class SOAPValidateInterceptor extends AbstractPhaseInterceptor { + + private static final Log LOG = LogFactory.getLog(SOAPValidateInterceptor.class); + + private final SAAJInInterceptor saajIn; + private final XmlParser xmlParser; + private boolean schemaValidationEnabled; + + public SOAPValidateInterceptor() { + super(Phase.PRE_PROTOCOL); + saajIn = new SAAJInInterceptor(); + xmlParser = new XmlParser(); + + getAfter().add(SAAJInInterceptor.class.getName()); + } + + @Override + public void handleMessage(SoapMessage message) throws Fault { + if (isGET(message)) { + return; + } + try { + Node body = getMessageBody((DOMSource) getSOAPMessage(message).getSOAPPart().getContent()); + if (body != null) + validate(body, message); + else + throw new XMLStreamException("Can't find the tag \"Body\""); + } catch (RuntimeException re) { + throw re; + } catch (Exception e) { + throw new Fault(e); + } + } + + private Node getMessageBody(DOMSource source) throws XPathExpressionException { + Node node = source.getNode().cloneNode(true); + List nodeList = xmlParser.getNodes(node.getLastChild(), "Body"); + return !nodeList.isEmpty() ? nodeList.get(0) : null; + } + + private void validate(Node node, SoapMessage soapMessage) + throws IOException, SAXException, XPathExpressionException { + Validator validator = getValidator(soapMessage); + validator.validate(new DOMSource(getNodeForValidate(node))); + } + + private Node getNodeForValidate(Node node) throws XPathExpressionException { + if (schemaValidationEnabled && node.getLocalName().contains("packets")) { + Element element = (Element) node; + for (Node content : xmlParser.getNodes(element, "content")) { + content.getParentNode().removeChild(content); + } + return element; + } + return node; + } + + private Validator getValidator(SoapMessage soapMessage) { + Service service = ServiceModelUtil.getService(soapMessage.getExchange()); + Schema schema = + EndpointReferenceUtils.getSchema(service.getServiceInfos().get(0), soapMessage.getExchange().getBus()); + return schema.newValidator(); + } + + private SOAPMessage getSOAPMessage(SoapMessage smsg) { + SOAPMessage soapMessage = smsg.getContent(SOAPMessage.class); + if (soapMessage == null) { + saajIn.handleMessage(smsg); + soapMessage = smsg.getContent(SOAPMessage.class); + } + return soapMessage; + } + + public void setSchemaValidationEnabled(boolean schemaValidationEnabled) { + this.schemaValidationEnabled = schemaValidationEnabled; + } +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/SystemHeadersConstants.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/SystemHeadersConstants.java new file mode 100644 index 00000000..e6e1648c --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/interceptor/SystemHeadersConstants.java @@ -0,0 +1,41 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.services.runtime.interceptor; + +/** + * @Deprecated copied from legacy 'system-commons' for backward compatibility + */ +@Deprecated(since = "1.10", forRemoval = true) +public class SystemHeadersConstants { + public static final String HEADER_USER_LOGIN = "X-ForwardedUser"; + public static final String HEADER_USER_ID = "X-ForwardedUserId"; + public static final String HEADER_SYSTEM_NAME = "X-SystemName"; + public static final String HEADER_SYSTEM_UUID = "X-SystemUuid"; + public static final String HEADER_SYSTEM_ID = "X-SystemId"; + public static final String HEADER_IS_DISPLAY_SERVICE_SERVICE = "NTX_IsDisplayServiceSchema"; + + private SystemHeadersConstants() {} +} diff --git a/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/utils/XmlParser.java b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/utils/XmlParser.java new file mode 100644 index 00000000..252b5eaa --- /dev/null +++ b/platform/runtime/core/objects-implementations/service-implementation/service-runtime/src/main/java/ru/entaxy/platform/services/runtime/utils/XmlParser.java @@ -0,0 +1,56 @@ +/*- + * ~~~~~~licensing~~~~~~ + * system-commons + * ========== + * 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~~~~~~ + */ +package ru.entaxy.platform.services.runtime.utils; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import javax.xml.xpath.*; +import java.util.ArrayList; +import java.util.List; + +public class XmlParser { + + public List getNodes(Node node, String elementName) throws XPathExpressionException { + XPath xpath = XPathFactory.newInstance().newXPath(); + + XPathExpression expr = xpath.compile("//*[local-name()='" + elementName + "']/child::node()"); + NodeList nodeList = (NodeList) expr.evaluate(node.getOwnerDocument(), XPathConstants.NODESET); + + return getNotNullNodes(nodeList); + } + + private List getNotNullNodes(NodeList nodeList) { + List result = new ArrayList<>(); + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + if (node.getLocalName() != null) { + result.add(node); + } + } + return result; + } +} diff --git a/platform/runtime/modules/atlasmap/LICENSE.txt b/platform/runtime/modules/atlasmap/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/modules/atlasmap/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/pom.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/pom.xml new file mode 100644 index 00000000..c50872f3 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/pom.xml @@ -0,0 +1,304 @@ + + + 4.0.0 + + io.atlasmap + atlas-parent + 2.2.3 + + + camel3-atlasmap-entaxy + bundle + 2.5.2 + camel3-atlasmap + Camel component to perform AtlasMap data mapping as a part of Camel route + + + 1.10.0 + org.apache.camel.component.atlasmap + org.apache.camel.spi.ComponentResolver;component=atlas + 3.4.5 + 2.5.2 + true + 2.12.3 + + + + The Apache Software License, Version 2.0 + http://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + + + org.apache.camel + camel-core + ${camel3.version} + + + org.apache.camel + camel-support + ${camel3.version} + + + ru.entaxy.esb.platform.runtime.modules.atlasmap + atlasmap-entaxy-libs + ${entaxy.version} + + + + io.atlasmap + atlas-java-test-model + ${atlas.version} + test + + + io.atlasmap + atlas-xml-test-model + ${atlas.version} + test + + + io.atlasmap + atlas-xml-core + ${atlas.version} + test + + + junit + junit + test + + + org.apache.camel + camel-test-spring + ${camel3.version} + test + + + org.apache.camel + camel-core-xml + ${camel3.version} + test + + + org.apache.camel + camel-spring-javaconfig + ${camel3.version} + test + + + org.apache.logging.log4j + log4j-api + test + + + org.apache.logging.log4j + log4j-core + test + + + org.apache.logging.log4j + log4j-slf4j-impl + test + + + org.codehaus.woodstox + woodstox-core-asl + test + + + org.mockito + mockito-core + test + + + org.springframework + spring-test + ${camel3-spring.version} + test + + + org.twitter4j + twitter4j-core + test + + + org.xmlunit + xmlunit-assertj + test + + + org.xmlunit + xmlunit-matchers + test + + + + + jacoco + + java + + + + + org.apache.maven.plugins + maven-surefire-plugin + + ${argLine} + + + + org.jacoco + jacoco-maven-plugin + + + prepare-agent + + prepare-agent + + + + report + verify + + report + + + + **/*.class + + + + + + + + + + + public-deploy + + false + + + + entaxy-public-entaxy + entaxy-public-entaxy + false + default + + https://nexus.entaxy.ru/nexus/repository/entaxy-public-entaxy/ + + + + + + + + + + src/main/resources + true + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.camel + camel-package-maven-plugin + [2.19.0.fuse-000035,) + + prepare-components + + + + + + + + + + + + + + + org.apache.maven.plugins + maven-resources-plugin + + + filter + generate-resources + + resources + + + + + + maven-javadoc-plugin + 3.0.0 + + + false + + + + + + + + + entaxy-private-releases + entaxy-private-releases + https://nexus.entaxy.ru/nexus/repository/entaxy-private-releases/ + + false + + + + + entaxy-private-snapshots + entaxy-private-snapshots + https://nexus.entaxy.ru/nexus/repository/entaxy-private-snapshots/ + + true + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasComponent.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasComponent.java new file mode 100644 index 00000000..f2fc73c1 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasComponent.java @@ -0,0 +1,75 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ + +package org.apache.camel.component.atlasmap; + +import java.util.Map; + +import org.apache.camel.Endpoint; +import org.apache.camel.component.atlasmap.AtlasEndpoint.TargetMapMode; +import org.apache.camel.spi.Metadata; +import org.apache.camel.support.DefaultComponent; +import org.apache.camel.support.ResourceHelper; + +import io.atlasmap.api.AtlasContextFactory; + +/** + * @version + */ +public class AtlasComponent extends DefaultComponent { + + @Metadata(label = "advanced") + private AtlasContextFactory atlasContextFactory; + + public AtlasContextFactory getAtlasContextFactory() { + return atlasContextFactory; + } + + /** + * To use the {@link AtlasContextFactory} otherwise a new engine is created. + * @param atlasContextFactory {@link AtlasContextFactory} + */ + public void setAtlasContextFactory(AtlasContextFactory atlasContextFactory) { + this.atlasContextFactory = atlasContextFactory; + } + + protected Endpoint createEndpoint(String uri, String remaining, Map parameters) throws Exception { + boolean cache = getAndRemoveParameter(parameters, "contentCache", Boolean.class, Boolean.TRUE); + String sourceMapName = getAndRemoveParameter(parameters, "sourceMapName", String.class); + String targetMapName = getAndRemoveParameter(parameters, "targetMapName", String.class); + TargetMapMode targetMapMode = getAndRemoveParameter(parameters, "targetMapMode", TargetMapMode.class); + + AtlasEndpoint endpoint = new AtlasEndpoint(uri, this, remaining); + setProperties(endpoint, parameters); + endpoint.setContentCache(cache); + endpoint.setSourceMapName(sourceMapName); + endpoint.setTargetMapName(targetMapName); + endpoint.setAtlasContextFactory(getAtlasContextFactory()); + if (targetMapMode != null) { + endpoint.setTargetMapMode(targetMapMode); + } + + // if its a http resource then append any remaining parameters and update the + // resource uri + if (ResourceHelper.isHttpUri(remaining)) { + String remainingAndParameters = ResourceHelper.appendParameters(remaining, parameters); + endpoint.setResourceUri(remainingAndParameters); + } + + return endpoint; + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasConstants.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasConstants.java new file mode 100644 index 00000000..62936229 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasConstants.java @@ -0,0 +1,32 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.camel.component.atlasmap; + +/** + * Atlas Constants. + */ +public final class AtlasConstants { + + public static final String ATLAS_RESOURCE_URI = "CamelAtlasResourceUri"; + public static final String ATLAS_MAPPING = "CamelAtlasMapping"; + public static final String ATLAS_SOURCE_MAP = "CamelAtlasSourceMap"; + public static final String ATLAS_TARGET_MAP = "CamelAtlasTargetMap"; + + private AtlasConstants() { + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasEndpoint.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasEndpoint.java new file mode 100644 index 00000000..7a39ee4d --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/AtlasEndpoint.java @@ -0,0 +1,460 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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. + */ +package org.apache.camel.component.atlasmap; + +import static io.atlasmap.api.AtlasContextFactory.Format.ADM; +import static io.atlasmap.api.AtlasContextFactory.Format.JSON; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import org.apache.camel.Exchange; +import org.apache.camel.ExchangePattern; +import org.apache.camel.Message; +import org.apache.camel.component.ResourceEndpoint; +import org.apache.camel.spi.UriEndpoint; +import org.apache.camel.spi.UriParam; +import org.apache.camel.support.MessageHelper; +import org.apache.camel.support.ResourceHelper; +import org.apache.camel.util.IOHelper; +import org.apache.camel.util.ObjectHelper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.atlasmap.api.AtlasContext; +import io.atlasmap.api.AtlasContextFactory; +import io.atlasmap.api.AtlasException; +import io.atlasmap.api.AtlasSession; +import io.atlasmap.core.DefaultAtlasContextFactory; +import io.atlasmap.v2.Audit; +import io.atlasmap.v2.DataSource; +import io.atlasmap.v2.DataSourceType; + +/** + * Transforms the message using an AtlasMap transformation. + */ +@UriEndpoint(firstVersion = "2.19.0", scheme = "atlas", title = "AtlasMap", syntax = "atlas:resourceUri", producerOnly = true, label = "transformation") +public class AtlasEndpoint extends ResourceEndpoint { + + public static final String CONTENT_TYPE_JSON = "application/json"; + public static final String CONTENT_TYPE_XML = "application/xml"; + + private static final Logger LOG = LoggerFactory.getLogger(AtlasEndpoint.class); + private AtlasContextFactory atlasContextFactory; + private AtlasContext atlasContext; + + @UriParam(defaultValue = "true") + private boolean loaderCache = true; + @UriParam + private String encoding; + @UriParam + private String propertiesFile; + @UriParam + private String sourceMapName; + @UriParam + private String targetMapName; + @UriParam(defaultValue = "MAP") + private TargetMapMode targetMapMode = TargetMapMode.MAP; + + public enum TargetMapMode { + MAP, MESSAGE_HEADER, EXCHANGE_PROPERTY; + } + + public AtlasEndpoint(String uri, AtlasComponent component, String resourceUri) { + super(uri, component, resourceUri); + } + + @Override + public boolean isSingleton() { + return true; + } + + @Override + public ExchangePattern getExchangePattern() { + return ExchangePattern.InOut; + } + + @Override + protected String createEndpointUri() { + return "atlas:" + getResourceUri(); + } + + public AtlasContextFactory getAtlasContextFactory() { + return this.atlasContextFactory; + } + + public void setAtlasContextFactory(AtlasContextFactory atlasContextFactory) { + this.atlasContextFactory = atlasContextFactory; + } + + public AtlasContext getAtlasContext() { + return this.atlasContext; + } + + public void setAtlasContext(AtlasContext atlasContext) { + this.atlasContext = atlasContext; + } + + public boolean isLoaderCache() { + return loaderCache; + } + + /** + * Enables / disables the atlas map resource loader cache which is enabled by + * default. + * @param loaderCache true to enable loader cache + */ + public void setLoaderCache(boolean loaderCache) { + this.loaderCache = loaderCache; + } + + /** + * Character encoding of the resource content. + * @param encoding encoding + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + public String getEncoding() { + return encoding; + } + + /** + * The URI of the properties file which is used for AtlasContextFactory + * initialization. + * @param file property file path + */ + public void setPropertiesFile(String file) { + propertiesFile = file; + } + + public String getPropertiesFile() { + return propertiesFile; + } + + /** + * The Exchange property name for a source message map which hold + * java.util.Map<String, Message> where the key is AtlasMap Document ID. + * AtlasMap consumes Message bodies as source documents. + * @param name Exchange property name for source map + */ + public void setSourceMapName(String name) { + this.sourceMapName = name; + } + + public String getSourceMapName() { + return this.sourceMapName; + } + + /** + * The Exchange property name for a target document map which hold + * java.util.Map<String, Object> where the key is AtlasMap Document ID. + * AtlasMap populates multiple target documents into this map. + * @param name Exchange property name for target map + */ + public void setTargetMapName(String name) { + this.targetMapName = name; + } + + public String getTargetMapName() { + return this.targetMapName; + } + + /** + * {@link TargetMapMode} enum value to specify how multiple documents are delivered. + * @param mode {@link TargetMapMode} + */ + public void setTargetMapMode(TargetMapMode mode) { + this.targetMapMode = mode; + } + + public TargetMapMode getTargetMapMode() { + return this.targetMapMode; + } + + public AtlasEndpoint findOrCreateEndpoint(String uri, String newResourceUri) { + String newUri = uri.replace(getResourceUri(), newResourceUri); + log.debug("Getting endpoint with URI: {}", newUri); + return getCamelContext().getEndpoint(newUri, AtlasEndpoint.class); + } + + @Override + protected void onExchange(Exchange exchange) throws Exception { + Message incomingMessage = exchange.getIn(); + String newResourceUri = incomingMessage.getHeader(AtlasConstants.ATLAS_RESOURCE_URI, String.class); + if (newResourceUri != null) { + incomingMessage.removeHeader(AtlasConstants.ATLAS_RESOURCE_URI); + + log.debug("{} set to {} creating new endpoint to handle exchange", AtlasConstants.ATLAS_RESOURCE_URI, + newResourceUri); + AtlasEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri); + newEndpoint.onExchange(exchange); + return; + } + + AtlasSession atlasSession = getOrCreateAtlasContext(incomingMessage).createSession(); + populateSourceDocuments(exchange, atlasSession); + atlasSession.getAtlasContext().process(atlasSession); + + List errors = new ArrayList<>(); + for (Audit audit : atlasSession.getAudits().getAudit()) { + switch (audit.getStatus()) { + case ERROR: + errors.add(audit); + break; + case WARN: + LOG.warn("{}: Document='{}(ID:{})', path='{}'", + audit.getMessage(), audit.getDocName(), audit.getDocId(), audit.getPath()); + break; + default: + LOG.info("{}: Document='{}(ID:{})', path='{}'", + audit.getMessage(), audit.getDocName(), audit.getDocId(), audit.getPath()); + } + } + if (!errors.isEmpty()) { + StringBuilder buf = new StringBuilder("Errors: "); + errors.stream().forEach(a -> buf.append( + String.format("[%s: Document='%s(ID:%s)', path='%s'], ", + a.getMessage(), a.getDocName(), a.getDocId(), a.getPath()))); + throw new AtlasException(buf.toString()); + } + + populateTargetDocuments(atlasSession, exchange); + } + + private AtlasContext getOrCreateAtlasContext(Message incomingMessage) throws Exception { + String path = getResourceUri(); + ObjectHelper.notNull(path, "mappingUri"); + + String content = incomingMessage.getHeader(AtlasConstants.ATLAS_MAPPING, String.class); + if (content != null) { + // use content from header + InputStream is = new ByteArrayInputStream(content.getBytes()); + if (log.isDebugEnabled()) { + log.debug("Atlas mapping content read from header {} for endpoint {}", AtlasConstants.ATLAS_MAPPING, + getEndpointUri()); + } + // remove the header to avoid it being propagated in the routing + incomingMessage.removeHeader(AtlasConstants.ATLAS_MAPPING); + return getOrCreateAtlasContextFactory().createContext(JSON, is); + } else if (getAtlasContext() != null) { + // no mapping specified in header, and found an existing context + return getAtlasContext(); + } + + // No mapping in header, and no existing context. Create new one from resourceUri + if (log.isDebugEnabled()) { + log.debug("Atlas mapping content read from resourceUri: {} for endpoint {}", + new Object[] { path, getEndpointUri() }); + } + atlasContext = getOrCreateAtlasContextFactory().createContext( + path.toLowerCase().endsWith("adm") ? ADM : JSON, getResourceAsInputStream()); + return atlasContext; + } + + private synchronized AtlasContextFactory getOrCreateAtlasContextFactory() throws Exception { + if (atlasContextFactory != null) { + return atlasContextFactory; + } + + atlasContextFactory = DefaultAtlasContextFactory.getInstance(); + atlasContextFactory.addClassLoader(getCamelContext().getApplicationContextClassLoader()); + // load the properties from property file which may overrides the default ones + if (ObjectHelper.isNotEmpty(getPropertiesFile())) { + Properties properties = new Properties(); + InputStream reader = ResourceHelper.resolveMandatoryResourceAsInputStream(getCamelContext(), + getPropertiesFile()); + try { + properties.load(reader); + log.info("Loaded the Atlas properties file " + getPropertiesFile()); + } finally { + IOHelper.close(reader, getPropertiesFile(), log); + } + log.debug("Initializing AtlasContextFactory with properties {}", properties); + atlasContextFactory.setProperties(properties); + } + return atlasContextFactory; + } + + private void populateSourceDocuments(Exchange exchange, AtlasSession session) { + if (session.getMapping().getDataSource() == null) { + return; + } + + Message inMessage = exchange.getIn(); + CamelAtlasPropertyStrategy propertyStrategy = new CamelAtlasPropertyStrategy(); + propertyStrategy.setCurrentSourceMessage(inMessage); + propertyStrategy.setTargetMessage(exchange.getMessage()); + propertyStrategy.setExchange(exchange); + session.setAtlasPropertyStrategy(propertyStrategy); + + DataSource[] sourceDataSources = session.getMapping().getDataSource().stream() + .filter(ds -> ds.getDataSourceType() == DataSourceType.SOURCE) + .toArray(DataSource[]::new); + if (sourceDataSources.length == 0) { + session.setDefaultSourceDocument(inMessage.getBody()); + return; + } + + if (sourceDataSources.length == 1) { + String docId = sourceDataSources[0].getId(); + Object payload = extractPayload(sourceDataSources[0], inMessage); + if (docId == null || docId.isEmpty()) { + session.setDefaultSourceDocument(payload); + } else { + session.setSourceDocument(docId, payload); + propertyStrategy.setSourceMessage(docId, inMessage); + } + return; + } + + Map sourceMessages = null; + Map sourceDocuments = null; + if (sourceMapName != null) { + sourceMessages = exchange.getProperty(sourceMapName, Map.class); + } + if (sourceMessages == null) { + Object body = inMessage.getBody(); + if (body instanceof Map) { + sourceDocuments = (Map)body; + } else { + session.setDefaultSourceDocument(body); + } + } + for (DataSource ds : sourceDataSources) { + String docId = ds.getId(); + if (docId == null || docId.isEmpty()) { + Object payload = extractPayload(ds, inMessage); + session.setDefaultSourceDocument(payload); + } else if (sourceMessages != null) { + Object payload = extractPayload(ds, sourceMessages.get(docId)); + session.setSourceDocument(docId, payload); + propertyStrategy.setSourceMessage(docId, sourceMessages.get(docId)); + } else if (sourceDocuments != null) { + Object payload = sourceDocuments.get(docId); + session.setSourceDocument(docId, payload); + } else if (inMessage.getHeaders().containsKey(docId)) { + Object payload = inMessage.getHeader(docId); + session.setSourceDocument(docId, payload); + } else if (exchange.getProperties().containsKey(docId)) { + Object payload = exchange.getProperty(docId); + session.setSourceDocument(docId, payload); + } else { + LOG.warn("Ignoring missing source document: '{}(ID:{})'", ds.getName(), ds.getId()); + } + } + } + + private Object extractPayload(final DataSource dataSource, Message message) { + if (dataSource == null || message == null) { + return null; + } + Object body = null; + + if (dataSource != null && dataSource.getUri() != null + && !(dataSource.getUri().startsWith("atlas:core") + || dataSource.getUri().startsWith("atlas:java"))) { + body = message.getBody(String.class); + } else { + body = message.getBody(); + } + + //Just in case, prepare for future calls + MessageHelper.resetStreamCache(message); + + + return body; + } + + private void populateTargetDocuments(AtlasSession session, Exchange exchange) { + Message message = exchange.getMessage(); + + if (session.getMapping().getDataSource() == null) { + return; + } + DataSource[] targetDataSources = session.getMapping().getDataSource().stream() + .filter(ds -> ds.getDataSourceType() == DataSourceType.TARGET) + .toArray(DataSource[]::new); + + if (targetDataSources.length == 0) { + Object newBody = session.getDefaultTargetDocument(); + message.setBody(newBody); + return; + } + + if (targetDataSources.length == 1) { + String docId = targetDataSources[0].getId(); + if (docId == null || docId.isEmpty()) { + Object newBody = session.getDefaultTargetDocument(); + message.setBody(newBody); + } else { + Object newBody = session.getTargetDocument(docId); + message.setBody(newBody); + } + setContentType(targetDataSources[0], message); + return; + } + + Map targetDocuments = new HashMap<>(); + for (DataSource ds : targetDataSources) { + String docId = ds.getId(); + if (docId == null || docId.isEmpty()) { + targetDocuments.put(io.atlasmap.api.AtlasConstants.DEFAULT_TARGET_DOCUMENT_ID, + session.getDefaultTargetDocument()); + Object newBody = session.getDefaultTargetDocument(); + message.setBody(newBody); + setContentType(ds, message); + } else { + targetDocuments.put(docId, session.getTargetDocument(docId)); + } + } + switch (targetMapMode) { + case MAP: + if (targetMapName != null) { + exchange.setProperty(targetMapName, targetDocuments); + } else { + message.setBody(targetDocuments); + } + break; + case MESSAGE_HEADER: + targetDocuments.remove(io.atlasmap.api.AtlasConstants.DEFAULT_TARGET_DOCUMENT_ID); + message.getHeaders().putAll(targetDocuments); + break; + case EXCHANGE_PROPERTY: + targetDocuments.remove(io.atlasmap.api.AtlasConstants.DEFAULT_TARGET_DOCUMENT_ID); + exchange.getProperties().putAll(targetDocuments); + break; + } + } + + private void setContentType(DataSource ds, Message message) { + if (ds.getUri() == null) { + return; + } + if (ds.getUri().startsWith("atlas:json")) { + message.setHeader(Exchange.CONTENT_TYPE, CONTENT_TYPE_JSON); + } else if (ds.getUri().startsWith("atlas:xml")) { + message.setHeader(Exchange.CONTENT_TYPE, CONTENT_TYPE_XML); + } + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/CamelAtlasPropertyStrategy.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/CamelAtlasPropertyStrategy.java new file mode 100644 index 00000000..eb1fc56c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/java/org/apache/camel/component/atlasmap/CamelAtlasPropertyStrategy.java @@ -0,0 +1,93 @@ +/** + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package org.apache.camel.component.atlasmap; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.api.AtlasSession; +import io.atlasmap.api.AtlasUnsupportedException; +import io.atlasmap.core.DefaultAtlasPropertyStrategy; +import io.atlasmap.v2.PropertyField; + +/** + * AtlasMap property strategy to map Camel message headers and exchange properties to/from + * AtlasMap properties. + * + */ +public class CamelAtlasPropertyStrategy extends DefaultAtlasPropertyStrategy { + + public static final String SCOPE_EXCHANGE_PROPERTY = "camelExchangeProperty"; + public static final String SCOPE_CURRENT_MESSAGE_HEADER = "current"; + + private Exchange camelExchange; + private Map sourceMessageMap = new HashMap<>(); + private Message camelTargetMessage; + + @Override + public void readProperty(AtlasSession session, PropertyField propertyField) + throws AtlasUnsupportedException, AtlasConversionException { + + String scope = propertyField.getScope(); + String key = propertyField.getName(); + Map target = null; + if (scope == null && sourceMessageMap.containsKey(SCOPE_CURRENT_MESSAGE_HEADER)) { + target = sourceMessageMap.get(SCOPE_CURRENT_MESSAGE_HEADER).getHeaders(); + } else if (SCOPE_EXCHANGE_PROPERTY.equals(scope)) { + target = this.camelExchange.getProperties(); + } else if (sourceMessageMap.containsKey(scope)) { + target = sourceMessageMap.get(scope).getHeaders(); + } + if (target != null && target.containsKey(key)) { + propertyField.setValue(target.get(key)); + } else { + super.readProperty(session, propertyField); + } + } + + @Override + public void writeProperty(AtlasSession session, PropertyField propertyField) { + String scope = propertyField.getScope(); + String key = propertyField.getName(); + Object value = propertyField.getValue(); + if (SCOPE_EXCHANGE_PROPERTY.equals(scope)) { + this.camelExchange.setProperty(key, value); + } else { + this.camelTargetMessage.setHeader(key, value); + } + } + + public void setExchange(Exchange ex) { + this.camelExchange = ex; + } + + public void setSourceMessage(String documentId, Message msg) { + sourceMessageMap.put(documentId, msg); + } + + public void setCurrentSourceMessage(Message msg) { + sourceMessageMap.put(SCOPE_CURRENT_MESSAGE_HEADER, msg); + } + + public void setTargetMessage(Message msg) { + this.camelTargetMessage = msg; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/resources/META-INF/NOTICE.txt b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/resources/META-INF/NOTICE.txt new file mode 100644 index 00000000..470210a4 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/resources/META-INF/NOTICE.txt @@ -0,0 +1,11 @@ + ========================================================================= + == NOTICE file corresponding to the section 4 d of == + == the Apache License, Version 2.0, == + == in this case for the Apache Camel distribution. == + ========================================================================= + + This product includes software developed by + The Apache Software Foundation (http://www.apache.org/). + + Please read the different LICENSE files present in the licenses directory of + this distribution. diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/resources/META-INF/services/org/apache/camel/component/atlas b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/resources/META-INF/services/org/apache/camel/component/atlas new file mode 100644 index 00000000..1a9821c2 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/main/resources/META-INF/services/org/apache/camel/component/atlas @@ -0,0 +1,18 @@ +# +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# + +class=org.apache.camel.component.atlasmap.AtlasComponent diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasEndpointTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasEndpointTest.java new file mode 100644 index 00000000..5c2879ec --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasEndpointTest.java @@ -0,0 +1,175 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.junit.ComparisonFailure; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.atlasmap.api.AtlasContext; +import io.atlasmap.api.AtlasSession; +import io.atlasmap.v2.AtlasMapping; +import io.atlasmap.v2.Audits; +import io.atlasmap.v2.DataSource; +import io.atlasmap.v2.DataSourceType; + +public class AtlasEndpointTest { + private static final Logger LOG = LoggerFactory.getLogger(AtlasEndpointTest.class); + + @Test + public void testNoDataSource() throws Exception { + perform(new ArrayList<>(), null, null, false); + } + + @Test + public void testDocId() throws Exception { + List ds = new ArrayList<>(); + DataSource source = new DataSource(); + source.setDataSourceType(DataSourceType.SOURCE); + source.setId("my-source-doc"); + ds.add(source); + DataSource target = new DataSource(); + target.setDataSourceType(DataSourceType.TARGET); + target.setId("my-target-doc"); + ds.add(target); + perform(ds, "my-source-doc", "my-target-doc", false); + } + + @Test(expected = ComparisonFailure.class) + public void noConversionIfNoDataSource() throws Exception { + perform(new ArrayList<>(), null, null, true); + } + + @Test(expected = ComparisonFailure.class) + public void noConversionIfJavaDataSource() throws Exception { + final List dataSources = new ArrayList<>(); + final DataSource dataSource = new DataSource(); + dataSource.setDataSourceType(DataSourceType.SOURCE); + dataSource.setUri("atlas:java:some.Type"); + dataSources.add(dataSource); + perform(dataSources, null, null, true); + } + + @Test + public void doConversionIfJsonDataSource() throws Exception { + final List dataSources = new ArrayList<>(); + final DataSource dataSource = new DataSource(); + dataSource.setDataSourceType(DataSourceType.SOURCE); + dataSource.setUri("atlas:json:SomeType"); + dataSources.add(dataSource); + perform(dataSources, null, null, true); + } + + @Test(expected = ComparisonFailure.class) + public void noConversionIfJsonTargetDataSource() throws Exception { + final List dataSources = new ArrayList<>(); + final DataSource dataSource = new DataSource(); + dataSource.setDataSourceType(DataSourceType.TARGET); + dataSource.setUri("atlas:json:SomeType"); + dataSources.add(dataSource); + perform(dataSources, null, null, true); + } + + @Test + public void doConversionIfXmlDataSource() throws Exception { + final List dataSources = new ArrayList<>(); + final DataSource dataSource = new DataSource(); + dataSource.setDataSourceType(DataSourceType.SOURCE); + dataSource.setUri("atlas:xml:SomeType"); + dataSources.add(dataSource); + perform(dataSources, null, null, true); + } + + @Test(expected = ComparisonFailure.class) + public void noConversionIfXmlTargetDataSource() throws Exception { + final List dataSources = new ArrayList<>(); + final DataSource dataSource = new DataSource(); + dataSource.setDataSourceType(DataSourceType.TARGET); + dataSource.setUri("atlas:xml:SomeType"); + dataSources.add(dataSource); + perform(dataSources, null, null, true); + } + + private void perform(List dataSources, String sourceDocId, String targetDocId, boolean fromStream) throws Exception { + final AtlasMapping mapping = new AtlasMapping(); + mapping.getDataSource().addAll(dataSources); + final AtlasContext context = spy(AtlasContext.class); + final AtlasSession session = spy(AtlasSession.class); + when(context.createSession()).thenReturn(session); + when(session.getAtlasContext()).thenReturn(context); + when(session.getMapping()).thenReturn(mapping); + when(session.getAudits()).thenReturn(new Audits()); + final AtlasEndpoint endpoint = new AtlasEndpoint("atlas:test.xml", new AtlasComponent(), "test.xml"); + endpoint.setAtlasContext(context); + final Exchange exchange = spy(Exchange.class); + final Message inMessage = spy(Message.class); + when(inMessage.getBody()).thenReturn(fromStream ? new ByteArrayInputStream("{test}".getBytes()) : "{test}"); + when(inMessage.getBody(String.class)).thenReturn("{test}"); + when(exchange.getIn()).thenReturn(inMessage); + if (sourceDocId == null) { + doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocation) { + LOG.debug("setDefaultSourceDocument({})", invocation.getArgument(0).toString()); + assertEquals("{test}", invocation.getArgument(0).toString()); + return null; + } + }).when(session).setDefaultSourceDocument(any()); + } else { + doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocation) { + LOG.debug("setSourceDocument({}, {})", invocation.getArgument(0), invocation.getArgument(1)); + assertEquals(sourceDocId, invocation.getArgument(0)); + assertEquals("{test}", invocation.getArgument(1)); + return null; + } + }).when(session).setSourceDocument(any(), any()); + } + final Message outMessage = spy(Message.class); + doAnswer(new Answer() { + @Override + public Void answer(InvocationOnMock invocation) { + LOG.debug("setBody({})", invocation.getArgument(0).toString()); + assertEquals("", invocation.getArgument(0)); + return null; + } + }).when(outMessage).setBody(any()); + doNothing().when(outMessage).setHeaders(any()); + if (targetDocId == null) { + when(session.getDefaultTargetDocument()).thenAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + LOG.debug("getDefaultTargetDocument()"); + return ""; + } + }); + } else { + when(session.getTargetDocument(any())).thenAnswer(new Answer() { + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + LOG.debug("getTargetDocument({})", invocation.getArgument(0).toString()); + assertEquals(targetDocId, invocation.getArgument(0)); + return ""; + } + }); + } + when(exchange.getMessage()).thenReturn(outMessage); + endpoint.onExchange(exchange); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJavaToJsonTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJavaToJsonTest.java new file mode 100644 index 00000000..129b5e63 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJavaToJsonTest.java @@ -0,0 +1,70 @@ +/** + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapComponentJavaToJsonTest { + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @Ignore + @DirtiesContext + public void testMocksAreValid() throws Exception { + result.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", Util.generateMockTwitterStatus()); + + MockEndpoint.assertIsSatisfied(camelContext); + Message msg = result.getExchanges().get(0).getIn(); + assertEquals("application/json", msg.getHeader(Exchange.CONTENT_TYPE)); + Object body = msg.getBody(); + assertEquals(String.class, body.getClass()); + ObjectMapper mapper = new ObjectMapper(); + JsonNode sfJson = mapper.readTree((String)body); + assertNotNull(sfJson.get("TwitterScreenName__c")); + assertEquals("bobvila1982", sfJson.get("TwitterScreenName__c").asText()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJsonTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJsonTest.java new file mode 100644 index 00000000..898edc0c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJsonTest.java @@ -0,0 +1,52 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapComponentJsonTest { + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @Ignore + @DirtiesContext + public void testMocksAreValid() throws Exception { + result.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", Util.generateMockTwitterStatus()); + + MockEndpoint.assertIsSatisfied(camelContext); + Object body = result.getExchanges().get(0).getIn().getBody(); + assertEquals(String.class, body.getClass()); + ObjectMapper mapper = new ObjectMapper(); + JsonNode outJson = mapper.readTree((String)body); + assertEquals("Bob", outJson.get("FirstName").asText()); + assertEquals("Vila", outJson.get("LastName").asText()); + assertEquals("bobvila1982", outJson.get("Title").asText()); + assertEquals("Let's build a house!", outJson.get("Description").asText()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJsonToJavaTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJsonToJavaTest.java new file mode 100644 index 00000000..f40cea3e --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentJsonToJavaTest.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapComponentJsonToJavaTest { + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @Ignore + @DirtiesContext + public void testMocksAreValid() throws Exception { + result.setExpectedCount(1); + + final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", new ByteArrayInputStream("{\"field1\":\"value1\"}".getBytes())); + + MockEndpoint.assertIsSatisfied(camelContext); + final Object body = result.getExchanges().get(0).getIn().getBody(); + assertEquals(Pojo.class, body.getClass()); + assertEquals("value1", ((Pojo) body).getField1()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentTest.java new file mode 100644 index 00000000..e24d791a --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentTest.java @@ -0,0 +1,78 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import twitter4j.Status; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapComponentTest { + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @Ignore + @DirtiesContext + public void testMocksAreValid() throws Exception { + result.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", Util.generateMockTwitterStatus()); + + MockEndpoint.assertIsSatisfied(camelContext); + Object body = result.getExchanges().get(0).getIn().getBody(); + assertEquals(String.class, body.getClass()); + ObjectMapper mapper = new ObjectMapper(); + JsonNode outJson = mapper.readTree((String)body); + assertEquals("Bob", outJson.get("FirstName").asText()); + assertEquals("Vila", outJson.get("LastName").asText()); + assertEquals("bobvila1982", outJson.get("Title").asText()); + assertEquals("Let's build a house!", outJson.get("Description").asText()); + assertEquals("const foobar", outJson.get("Constant").asText()); + } + + @Test + @Ignore + @DirtiesContext + public void testSeparateNotSucceed() throws Exception { + result.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + Status s = Util.generateMockTwitterStatus(); + when(s.getUser().getName()).thenReturn("BobVila"); + producerTemplate.sendBody("direct:start", s); + + MockEndpoint.assertIsSatisfied(camelContext); + Object body = result.getExchanges().get(0).getIn().getBody(); + assertEquals(String.class, body.getClass()); + ObjectMapper mapper = new ObjectMapper(); + JsonNode outJson = mapper.readTree((String)body); + assertEquals("BobVila", outJson.get("FirstName").asText()); + assertNull(outJson.get("LastName")); + assertEquals("bobvila1982", outJson.get("Title").asText()); + assertEquals("Let's build a house!", outJson.get("Description").asText()); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlDefaultNsTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlDefaultNsTest.java new file mode 100644 index 00000000..43572b84 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlDefaultNsTest.java @@ -0,0 +1,70 @@ +/** + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package org.apache.camel.component.atlasmap; + +import java.io.ByteArrayInputStream; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; +import org.xmlunit.builder.DiffBuilder; +import org.xmlunit.builder.Input; +import org.xmlunit.diff.Diff; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration(value = {"AtlasMapComponentXmlToXmlTest-context.xml"}) +public class AtlasMapComponentXmlToXmlDefaultNsTest { + + private static final String XML_EXPECTED = ""; + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @DirtiesContext + public void testMocksAreValid() throws Exception { + result.setExpectedCount(1); + + final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", new ByteArrayInputStream("".getBytes())); + + MockEndpoint.assertIsSatisfied(camelContext); + final String body = result.getExchanges().get(0).getIn().getBody(String.class); + + Assert.assertNotNull(body); + + Diff d = DiffBuilder.compare(Input.fromString(XML_EXPECTED).build()) + .withTest(Input.fromString(body).build()) + .ignoreWhitespace().build(); + Assert.assertFalse(d.toString() + ": " + body, d.hasDifferences()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlTest.java new file mode 100644 index 00000000..b137f120 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlTest.java @@ -0,0 +1,69 @@ +/** + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package org.apache.camel.component.atlasmap; + +import java.io.ByteArrayInputStream; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Assert; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; +import org.xmlunit.builder.DiffBuilder; +import org.xmlunit.builder.Input; +import org.xmlunit.diff.Diff; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapComponentXmlToXmlTest { + + private static final String XML_EXPECTED = ""; + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @DirtiesContext + public void testMocksAreValid() throws Exception { + result.setExpectedCount(1); + + final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", new ByteArrayInputStream("".getBytes())); + + MockEndpoint.assertIsSatisfied(camelContext); + final String body = result.getExchanges().get(0).getIn().getBody(String.class); + + Assert.assertNotNull(body); + + Diff d = DiffBuilder.compare(Input.fromString(XML_EXPECTED).build()) + .withTest(Input.fromString(body).build()) + .ignoreWhitespace().build(); + Assert.assertFalse(d.toString() + ": " + body, d.hasDifferences()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapExtractMappingsTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapExtractMappingsTest.java new file mode 100644 index 00000000..212a930c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapExtractMappingsTest.java @@ -0,0 +1,65 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapExtractMappingsTest { + + private static final String EXPECTED_BODY = "{\"order\":{\"orderId\":\"A123\"}}"; + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @EndpointInject(uri = "mock:result-n") + protected MockEndpoint resultN; + + @Test + @DirtiesContext + public void testXMLMappingsExtraction() throws Exception { + result.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", + new ByteArrayInputStream("{ \"order\": { \"orderId\": \"A123\" }}".getBytes())); + + MockEndpoint.assertIsSatisfied(camelContext); + + final Object body = result.getExchanges().get(0).getIn().getBody(); + assertEquals(EXPECTED_BODY, body); + } + + @Test + @DirtiesContext + public void testXMLMappingsExtractionNumberedMappingFile() throws Exception { + resultN.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start-n", + new ByteArrayInputStream("{ \"order\": { \"orderId\": \"A123\" }}".getBytes())); + + MockEndpoint.assertIsSatisfied(camelContext); + + final Object body = resultN.getExchanges().get(0).getIn().getBody(); + assertEquals(EXPECTED_BODY, body); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapJsonToXmlSchemaTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapJsonToXmlSchemaTest.java new file mode 100644 index 00000000..1822faf6 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapJsonToXmlSchemaTest.java @@ -0,0 +1,68 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertNotNull; + +import java.io.InputStream; +import java.io.StringReader; + +import javax.xml.transform.stream.StreamSource; +import javax.xml.validation.Validator; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import io.atlasmap.xml.core.schema.AtlasXmlSchemaSetParser; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapJsonToXmlSchemaTest { + private static final Logger LOG = LoggerFactory.getLogger(AtlasMapJsonToXmlSchemaTest.class); + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @After + public void after() { + result.reset(); + } + + @Test + @DirtiesContext + public void test() throws Exception { + result.setExpectedCount(1); + + final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + ClassLoader tccl = Thread.currentThread().getContextClassLoader(); + InputStream payloadIs = tccl.getResourceAsStream("json-source.json"); + producerTemplate.sendBody("direct:start", payloadIs); + + MockEndpoint.assertIsSatisfied(camelContext); + final String body = result.getExchanges().get(0).getIn().getBody(String.class); + assertNotNull(body); + LOG.debug(">>>>> {}", body); + + InputStream schemaIs = tccl.getResourceAsStream("xml-target-schemaset.xml"); + AtlasXmlSchemaSetParser schemaParser = new AtlasXmlSchemaSetParser(tccl); + Validator validator = schemaParser.createSchema(schemaIs).newValidator(); + StreamSource source = new StreamSource(new StringReader(body)); + validator.validate(source); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapMultiDocsTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapMultiDocsTest.java new file mode 100644 index 00000000..80dd8b15 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapMultiDocsTest.java @@ -0,0 +1,201 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; +import static org.xmlunit.assertj.XmlAssert.assertThat; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.Endpoint; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.support.DefaultMessage; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.After; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import io.atlasmap.java.test.SourceContact; +import io.atlasmap.java.test.TargetContact; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapMultiDocsTest { + + private static final String JSON_SOURCE = + "{" + + "\"firstName\": \"JsonFirstName\"," + + "\"lastName\": \"JsonLastName\"," + + "\"phoneNumber\": \"JsonPhoneNumber\"," + + "\"zipCode\": \"JsonZipCode\"" + + "}"; + + private static final String XML_SOURCE = + "\n" + + "\n"; + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @EndpointInject(uri = "mock:result-body") + protected MockEndpoint resultBody; + + @After + public void after() { + result.reset(); + resultBody.reset(); + } + + @Test + @Ignore + @DirtiesContext + public void test() throws Exception { + result.setExpectedCount(1); + + Map sourceMap = new HashMap<>(); + SourceContact javaSource = new SourceContact(); + javaSource.setFirstName("JavaFirstName"); + javaSource.setLastName("JavaLastName"); + javaSource.setPhoneNumber("JavaPhoneNumber"); + javaSource.setZipCode("JavaZipCode"); + Message msg = new DefaultMessage(camelContext); + msg.setBody(javaSource); + msg.setHeader("testProp", "java-source-header"); + sourceMap.put("DOCID-JAVA-CONTACT-S", msg); + msg = new DefaultMessage(camelContext); + msg.setBody(JSON_SOURCE); + msg.setHeader("testProp", "json-source-header"); + sourceMap.put("DOCID-JSON-CONTACT-S", msg); + msg = new DefaultMessage(camelContext); + msg.setBody(XML_SOURCE); + msg.setHeader("testProp", "xml-source-header"); + sourceMap.put("DOCID-XML-CONTACT-S", msg); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBodyAndProperty("direct:start", null, "CAPTURED_OUT_MESSAGES_MAP", sourceMap); + + MockEndpoint.assertIsSatisfied(camelContext); + Exchange exchange = result.getExchanges().get(0); + Map targetMap = exchange.getProperty("TARGET_MESSAGES_MAP", Map.class); + + verifyTargetDocs(targetMap); + + assertEquals("java-source-header", exchange.getProperty("target-exchange")); + assertEquals("json-source-header", exchange.getProperty("testProp")); + assertEquals("xml-source-header", exchange.getIn().getHeader("testProp")); + assertEquals("java-source-headerjson-source-headerxml-source-header" + , exchange.getIn().getHeader("testPropExpression")); + } + + @Test + @Ignore + public void testBody() throws Exception { + resultBody.setExpectedCount(1); + + Map sourceMap = new HashMap<>(); + SourceContact javaSource = new SourceContact(); + javaSource.setFirstName("JavaFirstName"); + javaSource.setLastName("JavaLastName"); + javaSource.setPhoneNumber("JavaPhoneNumber"); + javaSource.setZipCode("JavaZipCode"); + sourceMap.put("DOCID-JAVA-CONTACT-S", javaSource); + sourceMap.put("DOCID-JSON-CONTACT-S", JSON_SOURCE); + sourceMap.put("DOCID-XML-CONTACT-S", XML_SOURCE); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start-body", sourceMap); + + MockEndpoint.assertIsSatisfied(camelContext); + Exchange exchange = resultBody.getExchanges().get(0); + Map targetMap = exchange.getIn().getBody(Map.class); + + verifyTargetDocs(targetMap); + } + + @Test + @Ignore + public void testHeaderDocs() throws Exception { + resultBody.setExpectedCount(1); + + Map sourceMap = new HashMap<>(); + SourceContact javaSource = new SourceContact(); + javaSource.setFirstName("JavaFirstName"); + javaSource.setLastName("JavaLastName"); + javaSource.setPhoneNumber("JavaPhoneNumber"); + javaSource.setZipCode("JavaZipCode"); + sourceMap.put("DOCID-JAVA-CONTACT-S", javaSource); + sourceMap.put("DOCID-JSON-CONTACT-S", JSON_SOURCE); + sourceMap.put("DOCID-XML-CONTACT-S", XML_SOURCE); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBodyAndHeaders("direct:start-header", null, sourceMap); + + MockEndpoint.assertIsSatisfied(camelContext); + Exchange exchange = resultBody.getExchanges().get(0); + verifyTargetDocs(exchange.getIn().getHeaders()); + } + + @Test + @Ignore + public void testExchangePropertyDocs() throws Exception { + resultBody.setExpectedCount(1); + + Map sourceMap = new HashMap<>(); + SourceContact javaSource = new SourceContact(); + javaSource.setFirstName("JavaFirstName"); + javaSource.setLastName("JavaLastName"); + javaSource.setPhoneNumber("JavaPhoneNumber"); + javaSource.setZipCode("JavaZipCode"); + sourceMap.put("DOCID-JAVA-CONTACT-S", javaSource); + sourceMap.put("DOCID-JSON-CONTACT-S", JSON_SOURCE); + sourceMap.put("DOCID-XML-CONTACT-S", XML_SOURCE); + + Endpoint ep = camelContext.getEndpoint("direct:start-exchange-property"); + Exchange ex = ep.createExchange(); + ex.getProperties().putAll(sourceMap); + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.send(ep, ex); + + MockEndpoint.assertIsSatisfied(camelContext); + Exchange exchange = resultBody.getExchanges().get(0); + verifyTargetDocs(exchange.getProperties()); + } + + private void verifyTargetDocs(Map targetMap) throws Exception { + String jsonTarget = (String) targetMap.get("DOCID-JSON-CONTACT-T"); + ObjectMapper mapper = new ObjectMapper(); + JsonNode jsonTargetNode = mapper.readTree(jsonTarget); + assertEquals("JsonFirstName", jsonTargetNode.get("firstName").asText()); + assertEquals("JavaLastName", jsonTargetNode.get("lastName").asText()); + assertEquals("XmlPhoneNumber", jsonTargetNode.get("phoneNumber").asText()); + + String xmlTarget = (String) targetMap.get("DOCID-XML-CONTACT-T"); + HashMap ns = new HashMap<>(); + ns.put("ns", "http://atlasmap.io/xml/test/v2"); + assertThat(xmlTarget).withNamespaceContext(ns).valueByXPath("/Contact/@firstName").isEqualTo("XmlFirstName"); + assertThat(xmlTarget).withNamespaceContext(ns).valueByXPath("/Contact/@lastName").isEqualTo("JsonLastName"); + assertThat(xmlTarget).withNamespaceContext(ns).valueByXPath("/Contact/@phoneNumber").isEqualTo("JavaPhoneNumber"); + + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapMultiNSTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapMultiNSTest.java new file mode 100644 index 00000000..5c44271b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/AtlasMapMultiNSTest.java @@ -0,0 +1,68 @@ +package org.apache.camel.component.atlasmap; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; +import org.xmlunit.builder.DiffBuilder; +import org.xmlunit.builder.Input; +import org.xmlunit.diff.Diff; + +import io.atlasmap.java.test.SourceContact; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapMultiNSTest { + + private static final String XML_EXPECTED = + "\n" + + "\n" + + " \n" + + " \n" + + " Jackson\n" + + " \n" + + " \n" + + ""; + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + @Test + @Ignore + @DirtiesContext + public void test() throws Exception { + result.setExpectedCount(1); + + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + SourceContact c = new SourceContact(); + c.setFirstName("Jackson"); + producerTemplate.sendBody("direct:start", c); + + MockEndpoint.assertIsSatisfied(camelContext); + Message message = result.getExchanges().get(0).getIn(); + Assert.assertEquals("application/xml", message.getHeader(Exchange.CONTENT_TYPE)); + String out = message.getBody(String.class); + Assert.assertNotNull(out); + Diff d = DiffBuilder.compare(Input.fromString(XML_EXPECTED).build()) + .withTest(Input.fromString(out).build()) + .ignoreWhitespace().build(); + Assert.assertFalse(d.toString() + ": " + out, d.hasDifferences()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/CamelAtlasPropertyStrategyTest.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/CamelAtlasPropertyStrategyTest.java new file mode 100644 index 00000000..eb62d85f --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/CamelAtlasPropertyStrategyTest.java @@ -0,0 +1,75 @@ +package org.apache.camel.component.atlasmap; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.apache.camel.impl.DefaultCamelContext; +import org.apache.camel.support.DefaultExchange; +import org.apache.camel.support.DefaultMessage; +import org.junit.Test; + +import io.atlasmap.api.AtlasSession; +import io.atlasmap.core.DefaultAtlasSession; +import io.atlasmap.v2.PropertyField; + +public class CamelAtlasPropertyStrategyTest { + + @Test + public void testRead() throws Exception { + CamelAtlasPropertyStrategy strategy = new CamelAtlasPropertyStrategy(); + DefaultCamelContext context = new DefaultCamelContext(); + DefaultExchange exchange = new DefaultExchange(context); + exchange.setProperty("testProp", "testProp-exchangeProperty"); + strategy.setExchange(exchange); + DefaultMessage currentMessage = new DefaultMessage(exchange); + currentMessage.setHeader("testProp", "testProp-currentMessage"); + strategy.setCurrentSourceMessage(currentMessage); + DefaultMessage message1 = new DefaultMessage(exchange); + message1.setHeader("testProp", "testProp-message1"); + strategy.setSourceMessage("Doc1", message1); + DefaultMessage message2 = new DefaultMessage(exchange); + message2.setHeader("testProp", "testProp-message2"); + strategy.setSourceMessage("Doc2", message2); + AtlasSession session = mock(AtlasSession.class); + when(session.getAtlasPropertyStrategy()).thenReturn(strategy); + PropertyField propertyField = new PropertyField(); + propertyField.setName("testProp"); + strategy.readProperty(session, propertyField); + assertEquals("testProp-currentMessage", propertyField.getValue()); + propertyField.setScope(CamelAtlasPropertyStrategy.SCOPE_EXCHANGE_PROPERTY); + strategy.readProperty(session, propertyField); + assertEquals("testProp-exchangeProperty", propertyField.getValue()); + propertyField.setScope("Doc1"); + strategy.readProperty(session, propertyField); + assertEquals("testProp-message1", propertyField.getValue()); + propertyField.setScope("Doc2"); + strategy.readProperty(session, propertyField); + assertEquals("testProp-message2", propertyField.getValue()); + } + + @Test + public void testWrite() throws Exception { + CamelAtlasPropertyStrategy strategy = new CamelAtlasPropertyStrategy(); + DefaultCamelContext context = new DefaultCamelContext(); + DefaultExchange exchange = new DefaultExchange(context); + strategy.setExchange(exchange); + DefaultMessage message = new DefaultMessage(exchange); + strategy.setTargetMessage(message); + PropertyField propertyField = new PropertyField(); + propertyField.setName("testProp-message"); + propertyField.setValue("testValue"); + AtlasSession session = mock(DefaultAtlasSession.class); + when(session.getAtlasPropertyStrategy()).thenReturn(strategy); + strategy.writeProperty(session, propertyField); + propertyField.setName("testProp-exchange"); + propertyField.setScope(CamelAtlasPropertyStrategy.SCOPE_EXCHANGE_PROPERTY); + strategy.writeProperty(session, propertyField); + assertEquals("testValue", message.getHeader("testProp-message")); + assertNull(message.getHeader("testProp-exchange")); + assertNull(exchange.getProperty("testProp-message")); + assertEquals("testValue", exchange.getProperty("testProp-exchange")); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/Pojo.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/Pojo.java new file mode 100644 index 00000000..1fed4bad --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/Pojo.java @@ -0,0 +1,30 @@ +/** + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package org.apache.camel.component.atlasmap; + +public class Pojo { + + private String field1; + + public String getField1() { + return field1; + } + + public void setField1(final String field1) { + this.field1 = field1; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/Util.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/Util.java new file mode 100644 index 00000000..03d9b855 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/Util.java @@ -0,0 +1,21 @@ +package org.apache.camel.component.atlasmap; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import twitter4j.Status; +import twitter4j.User; + +public class Util { + + public static Status generateMockTwitterStatus() { + Status status = mock(Status.class); + User user = mock(User.class); + when(user.getName()).thenReturn("Bob Vila"); + when(user.getScreenName()).thenReturn("bobvila1982"); + when(status.getUser()).thenReturn(user); + when(status.getText()).thenReturn("Let's build a house!"); + return status; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/issue/AtlasMapIssue2552Test.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/issue/AtlasMapIssue2552Test.java new file mode 100644 index 00000000..54b4f7b9 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/issue/AtlasMapIssue2552Test.java @@ -0,0 +1,92 @@ +package org.apache.camel.component.atlasmap.issue; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapIssue2552Test { + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result-old") + protected MockEndpoint resultOld; + + @EndpointInject(uri = "mock:result-new") + protected MockEndpoint resultNew; + + + @Test + public void testOld() throws Exception { + String jsonSource = new String(Files.readAllBytes(Paths.get( + this.getClass().getClassLoader().getResource( + "org/apache/camel/component/atlasmap/issue/2552-input.json").toURI()))); + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start-old", jsonSource); + + MockEndpoint.assertIsSatisfied(camelContext); + ObjectMapper om = new ObjectMapper(); + Exchange exchange = resultOld.getExchanges().get(0); + String target = exchange.getIn().getBody(String.class); + JsonNode targetJsonOld = om.readTree(target); + assertTarget(targetJsonOld); + + + } + + @Test + public void testNew() throws Exception { + String jsonSource = new String(Files.readAllBytes(Paths.get( + this.getClass().getClassLoader().getResource( + "org/apache/camel/component/atlasmap/issue/2552-input.json").toURI()))); + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start-new", jsonSource); + + MockEndpoint.assertIsSatisfied(camelContext); + ObjectMapper om = new ObjectMapper(); + Exchange exchange = resultNew.getExchanges().get(0); + String target = exchange.getIn().getBody(String.class); + JsonNode targetJsonNew = om.readTree(target); + assertTarget(targetJsonNew); + } + + private void assertTarget(JsonNode root) { + ArrayNode bodyArray = (ArrayNode) root.get("body"); + assertEquals(3, bodyArray.size()); + ObjectNode body1 = (ObjectNode) bodyArray.get(0); + ObjectNode body2 = (ObjectNode) bodyArray.get(1); + ObjectNode body3 = (ObjectNode) bodyArray.get(2); + assertEquals(1111, body1.get("id").asInt()); + assertEquals(1, body1.get("completed").asInt()); + assertEquals("task1", body1.get("task").asText()); + assertEquals(2222, body2.get("id").asInt()); + assertTrue(body2.get("completed").isNull()); + assertEquals("task2", body2.get("task").asText()); + assertEquals(3333, body3.get("id").asInt()); + assertEquals(3, body3.get("completed").asInt()); + assertEquals("task3", body3.get("task").asText()); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/issue/AtlasMapIssue729Test.java b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/issue/AtlasMapIssue729Test.java new file mode 100644 index 00000000..ab58a849 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/java/org/apache/camel/component/atlasmap/issue/AtlasMapIssue729Test.java @@ -0,0 +1,54 @@ +package org.apache.camel.component.atlasmap.issue; + +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.EndpointInject; +import org.apache.camel.Exchange; +import org.apache.camel.ProducerTemplate; +import org.apache.camel.component.mock.MockEndpoint; +import org.apache.camel.test.spring.CamelSpringRunner; +import org.apache.camel.test.spring.CamelTestContextBootstrapper; +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.BootstrapWith; +import org.springframework.test.context.ContextConfiguration; + +import io.atlasmap.java.test.SourceContact; +import io.atlasmap.java.test.TargetContact; + +@RunWith(CamelSpringRunner.class) +@BootstrapWith(CamelTestContextBootstrapper.class) +@ContextConfiguration +public class AtlasMapIssue729Test { + + @Autowired + protected CamelContext camelContext; + + @EndpointInject(uri = "mock:result") + protected MockEndpoint result; + + + @Test + @Ignore + public void test() throws Exception { + SourceContact javaSource = new SourceContact(); + javaSource.setFirstName("JavaFirstName"); + javaSource.setLastName("JavaLastName"); + javaSource.setPhoneNumber("JavaPhoneNumber"); + javaSource.setZipCode("JavaZipCode"); + ProducerTemplate producerTemplate = camelContext.createProducerTemplate(); + producerTemplate.sendBody("direct:start", javaSource); + + MockEndpoint.assertIsSatisfied(camelContext); + Exchange exchange = result.getExchanges().get(0); + Map targetMap = exchange.getIn().getBody(Map.class); + TargetContact javaTarget = (TargetContact) targetMap.get("DOCID:JAVA:CONTACT:T"); + assertEquals("JavaFirstName", javaTarget.getFirstName()); + + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmap-mapping-n.adm b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmap-mapping-n.adm new file mode 100644 index 00000000..e6bf68d1 Binary files /dev/null and b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmap-mapping-n.adm differ diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmap-mapping.adm b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmap-mapping.adm new file mode 100644 index 00000000..0744b9ec Binary files /dev/null and b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmap-mapping.adm differ diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-java-to-json.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-java-to-json.json new file mode 100644 index 00000000..95a327cd --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-java-to-json.json @@ -0,0 +1,56 @@ +{ + "AtlasMapping": { + "jsonType": "io.atlasmap.v2.AtlasMapping", + "dataSource": [ + { + "jsonType": "io.atlasmap.v2.DataSource", + "id": "twitter4j.Status", + "uri": "atlas:java?className=twitter4j.Status", + "dataSourceType": "SOURCE" + }, + { + "jsonType": "io.atlasmap.json.v2.JsonDataSource", + "id": "Contact", + "uri": "atlas:json:Contact", + "dataSourceType": "TARGET", + "template": null + } + ], + "mappings": { + "mapping": [ + { + "jsonType": "io.atlasmap.v2.Mapping", + "mappingType": "MAP", + "inputField": [ + { + "jsonType": "io.atlasmap.java.v2.JavaField", + "name": "screenName", + "path": "/user/screenName", + "fieldType": "STRING", + "docId": "twitter4j.Status" + } + ], + "outputField": [ + { + "jsonType": "io.atlasmap.json.v2.JsonComplexType", + "name": "TwitterScreenName__c", + "path": "/TwitterScreenName__c", + "fieldType": "STRING", + "docId": "Contact", + "userCreated": false + } + ] + } + ] + }, + "name": "UI.246440", + "lookupTables": { + "lookupTable": [ + ] + }, + "properties": { + "property": [ + ] + } + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-json-to-java.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-json-to-java.json new file mode 100644 index 00000000..c688af55 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-json-to-java.json @@ -0,0 +1,56 @@ +{ + "AtlasMapping": { + "jsonType": "io.atlasmap.v2.AtlasMapping", + "dataSource": [ + { + "jsonType": "io.atlasmap.json.v2.JsonDataSource", + "id": "Contact", + "uri": "atlas:json:Json", + "dataSourceType": "SOURCE", + "template": null + }, + { + "jsonType": "io.atlasmap.v2.DataSource", + "id": "twitter4j.Status", + "uri": "atlas:java?className=org.apache.camel.component.atlasmap.Pojo", + "dataSourceType": "TARGET" + } + ], + "mappings": { + "mapping": [ + { + "jsonType": "io.atlasmap.v2.Mapping", + "mappingType": "MAP", + "inputField": [ + { + "jsonType": "io.atlasmap.json.v2.JsonComplexType", + "name": "field1", + "path": "/field1", + "fieldType": "STRING", + "docId": "Contact", + "userCreated": false + } + ], + "outputField": [ + { + "jsonType": "io.atlasmap.java.v2.JavaField", + "name": "field1", + "path": "/field1", + "fieldType": "STRING", + "docId": "twitter4j.Status" + } + ] + } + ] + }, + "name": "UI.246440", + "lookupTables": { + "lookupTable": [ + ] + }, + "properties": { + "property": [ + ] + } + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-multidocs.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-multidocs.json new file mode 100644 index 00000000..0673b7e6 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-multidocs.json @@ -0,0 +1,289 @@ +{ + "AtlasMapping" : { + "jsonType" : "io.atlasmap.v2.AtlasMapping", + "dataSource" : [ { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID-JAVA-CONTACT-S", + "uri" : "atlas:java?className=io.atlasmap.java.test.SourceContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID-JSON-CONTACT-S", + "uri" : "atlas:json:JSONContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID-XML-CONTACT-S", + "uri" : "atlas:xml:XMLContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID-JAVA-CONTACT-T", + "uri" : "atlas:java?className=io.atlasmap.java.test.TargetContact", + "dataSourceType" : "TARGET" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID-JSON-CONTACT-T", + "uri" : "atlas:json:JSONContact", + "dataSourceType" : "TARGET" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID-XML-CONTACT-T", + "uri" : "atlas:xml:XMLContact", + "dataSourceType" : "TARGET" + } ], + "mappings" : { + "mapping" : [ { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID-JAVA-CONTACT-S", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName", + "getMethod" : "getFirstName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID-JAVA-CONTACT-T", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName", + "setMethod" : "setFirstName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID-JAVA-CONTACT-S", + "path" : "/lastName", + "fieldType" : "STRING", + "name" : "lastName", + "getMethod" : "getLastName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "docId" : "DOCID-JSON-CONTACT-T", + "path" : "/lastName", + "fieldType" : "STRING", + "name" : "lastName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID-JAVA-CONTACT-S", + "path" : "/phoneNumber", + "fieldType" : "STRING", + "name" : "phoneNumber", + "getMethod" : "getPhoneNumber" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "DOCID-XML-CONTACT-T", + "path" : "/Contact/@phoneNumber", + "fieldType" : "STRING", + "name" : "phoneNumber" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "docId" : "DOCID-JSON-CONTACT-S", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "docId" : "DOCID-JSON-CONTACT-T", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "docId" : "DOCID-JSON-CONTACT-S", + "path" : "/lastName", + "fieldType" : "STRING", + "name" : "lastName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "DOCID-XML-CONTACT-T", + "path" : "/Contact/@lastName", + "fieldType" : "STRING", + "name" : "lastName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "docId" : "DOCID-JSON-CONTACT-S", + "path" : "/phoneNumber", + "fieldType" : "STRING", + "name" : "phoneNumber" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID-JAVA-CONTACT-T", + "path" : "/phoneNumber", + "fieldType" : "STRING", + "name" : "phoneNumber", + "setMethod" : "setPhoneNumber" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "DOCID-XML-CONTACT-S", + "path" : "/Contact/@firstName", + "fieldType" : "STRING", + "name" : "firstName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "DOCID-XML-CONTACT-T", + "path" : "/Contact/@firstName", + "fieldType" : "STRING", + "name" : "firstName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "DOCID-XML-CONTACT-S", + "path" : "/Contact/@lastName", + "fieldType" : "STRING", + "name" : "lastName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID-JAVA-CONTACT-T", + "path" : "/lastName", + "fieldType" : "STRING", + "name" : "lastName", + "setMethod" : "setLastName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "DOCID-XML-CONTACT-S", + "path" : "/Contact/@phoneNumber", + "fieldType" : "STRING", + "name" : "phoneNumber" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "docId" : "DOCID-JSON-CONTACT-T", + "path" : "/phoneNumber", + "fieldType" : "STRING", + "name" : "phoneNumber" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "path" : "/testProp", + "fieldType" : "STRING", + "scope" : "DOCID-JAVA-CONTACT-S", + "name" : "testProp" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "path" : "/target-exchange", + "fieldType" : "STRING", + "scope" : "camelExchangeProperty", + "name" : "target-exchange" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "path" : "/testProp", + "fieldType" : "STRING", + "scope" : "DOCID-JSON-CONTACT-S", + "name" : "testProp" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "path" : "/testProp", + "fieldType" : "STRING", + "scope" : "camelExchangeProperty", + "name" : "testProp" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "path" : "/testProp", + "fieldType" : "STRING", + "scope" : "DOCID-XML-CONTACT-S", + "name" : "testProp" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "path" : "/testProp", + "fieldType" : "STRING", + "name" : "testProp" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "expression" : "${PROP:/DOCID-JAVA-CONTACT-S/testProp} + ${PROP:/DOCID-JSON-CONTACT-S/testProp} + ${PROP:/DOCID-XML-CONTACT-S/testProp}", + "inputFieldGroup" : { + "jsonType" : "io.atlasmap.v2.FieldGroup", + "field" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "docId" : "PROP", + "path" : "/DOCID-JAVA-CONTACT-S/testProp", + "fieldType" : "STRING", + "scope" : "DOCID-JAVA-CONTACT-S", + "name" : "testProp" + }, { + "jsonType" : "io.atlasmap.v2.PropertyField", + "docId" : "PROP", + "path" : "/DOCID-JSON-CONTACT-S/testProp", + "fieldType" : "STRING", + "scope" : "DOCID-JSON-CONTACT-S", + "name" : "testProp" + }, { + "jsonType" : "io.atlasmap.v2.PropertyField", + "docId" : "PROP", + "path" : "/DOCID-XML-CONTACT-S/testProp", + "fieldType" : "STRING", + "scope" : "DOCID-XML-CONTACT-S", + "name" : "testProp" + } ] }, + "outputField" : [ { + "jsonType" : "io.atlasmap.v2.PropertyField", + "docId" : "PROP", + "path" : "/testPropExpression", + "fieldType" : "STRING", + "name" : "testPropExpression" + } ] + } ] + }, + "lookupTables" : { + "lookupTable" : [ ] + }, + "properties" : { + "property" : [ ] + }, + "name" : "mockMapping" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-multins.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-multins.json new file mode 100644 index 00000000..5e02d89c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-multins.json @@ -0,0 +1,52 @@ +{ + "AtlasMapping" : { + "jsonType" : "io.atlasmap.v2.AtlasMapping", + "dataSource" : [ { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "SourceContact", + "uri" : "atlas:java:SourceContact?className=io.atlasmap.java.test.SourceContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.xml.v2.XmlDataSource", + "id" : "XMLSchemaTarget", + "uri" : "atlas:xml:XMLSchemaTarget", + "dataSourceType" : "TARGET", + "xmlNamespaces" : { + "xmlNamespace" : [ { + "alias" : "tns", + "uri" : "http://syndesis.io/v1/swagger-connector-template/request" + } ] + } + } ], + "mappings" : { + "mapping" : [ { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "SourceContact", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName", + "getMethod" : "getFirstName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.xml.v2.XmlField", + "docId" : "XMLSchemaTarget", + "path" : "/tns:request/tns:body/Pet/name", + "fieldType" : "STRING", + "name" : "name", + "userCreated" : false + } ], + "id" : "mapping.222691" + } ] + }, + "lookupTables" : { + "lookupTable" : [ ] + }, + "properties" : { + "property" : [ ] + }, + "name" : "UI.860284" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-xml-to-xml.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-xml-to-xml.json new file mode 100644 index 00000000..a744e951 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping-xml-to-xml.json @@ -0,0 +1,66 @@ +{ + "AtlasMapping": { + "dataSource": [ + { + "dataSourceType": "SOURCE", + "id": "-LO2lWtkzmk816-JEluS", + "jsonType": "io.atlasmap.xml.v2.XmlDataSource", + "uri": "atlas:xml:-LO2lWtkzmk816-JEluS", + "xmlNamespaces": { + "xmlNamespace": [ + { + "alias": "tns", + "uri": "http://hl7.org/fhir" + } + ] + } + }, + { + "dataSourceType": "TARGET", + "id": "-LO2lU-dzmk816-JEluS", + "jsonType": "io.atlasmap.xml.v2.XmlDataSource", + "uri": "atlas:xml:-LO2lU-dzmk816-JEluS", + "xmlNamespaces": { + "xmlNamespace": [ + { + "alias": "tns", + "targetNamespace": true, + "uri": "http://hl7.org/fhir" + } + ] + } + } + ], + "jsonType": "io.atlasmap.v2.AtlasMapping", + "mappings": { + "mapping": [ + { + "id": "mapping.431884", + "inputField": [ + { + "docId": "-LO2lWtkzmk816-JEluS", + "fieldType": "STRING", + "jsonType": "io.atlasmap.xml.v2.XmlField", + "name": "value", + "path": "/tns:Patient/tns:id/@value", + "userCreated": false + } + ], + "jsonType": "io.atlasmap.v2.Mapping", + "mappingType": "MAP", + "outputField": [ + { + "docId": "-LO2lU-dzmk816-JEluS", + "fieldType": "STRING", + "jsonType": "io.atlasmap.xml.v2.XmlField", + "name": "value", + "path": "/tns:Patient/tns:id/@value", + "userCreated": false + } + ] + } + ] + }, + "name": "UI.266964" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping.json new file mode 100644 index 00000000..d938e0c9 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/atlasmapping.json @@ -0,0 +1,95 @@ +{ + "AtlasMapping" : { + "jsonType" : "io.atlasmap.v2.AtlasMapping", + "dataSource" : [ { + "jsonType" : "io.atlasmap.v2.DataSource", + "uri" : "atlas:java?className=twitter4j.Status", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "uri" : "atlas:json:JSONContact", + "dataSourceType" : "TARGET" + } ], + "mappings" : { + "mapping" : [ { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "SEPARATE", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "path" : "/User/name", + "fieldType" : "STRING", + "name" : "Name", + "getMethod" : "getName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "index" : 0, + "path" : "/FirstName", + "fieldType" : "STRING", + "name" : "FirstName" + }, { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "index" : 1, + "path" : "/LastName", + "fieldType" : "STRING", + "name" : "LastName" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "path" : "/Text", + "fieldType" : "STRING", + "name" : "Text", + "getMethod" : "getText" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "path" : "/Description", + "fieldType" : "STRING", + "name" : "Description" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "path" : "/User/screenName", + "fieldType" : "STRING", + "name" : "ScreenName", + "getMethod" : "getScreenName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "path" : "/Title", + "fieldType" : "STRING", + "name" : "Title" + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.v2.ConstantField", + "value" : "const foobar", + "docId" : "DOC.Constants.973849", + "path" : "/foobar", + "fieldType" : "STRING" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.json.v2.JsonField", + "path" : "/Constant", + "fieldType" : "STRING", + "name" : "Constant" + } ] + } ] + }, + "lookupTables" : { + "lookupTable" : [ ] + }, + "properties" : { + "property" : [ ] + }, + "name" : "mockMapping" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/json-schema-source-to-xml-schema-target.adm b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/json-schema-source-to-xml-schema-target.adm new file mode 100644 index 00000000..645094a6 Binary files /dev/null and b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/json-schema-source-to-xml-schema-target.adm differ diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/json-source.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/json-source.json new file mode 100644 index 00000000..40e76ede --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/json-source.json @@ -0,0 +1,47 @@ +{ + "order": { + "address": { + "street": "123 any st", + "city": "Austin", + "state": "TX", + "zip": "78626" + }, + "contact": { + "firstName": "james", + "lastName": "smith", + "phone": "512-123-1234" + }, + "orderId": "123" + }, + "primitives": { + "stringPrimitive": "some value", + "booleanPrimitive": true, + "numberPrimitive": 24 + }, + "addressList": [ + { + "street": "123 any st", + "city": "Austin", + "state": "TX", + "zip": "78626" + }, + { + "street": "123 any st", + "city": "Austin", + "state": "TX", + "zip": "78626" + }, + { + "street": "123 any st", + "city": "Austin", + "state": "TX", + "zip": "78626" + }, + { + "street": "123 any st", + "city": "Austin", + "state": "TX", + "zip": "78626" + } + ] +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/log4j2.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/log4j2.xml new file mode 100644 index 00000000..b4480aea --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/log4j2.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJavaToJsonTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJavaToJsonTest-context.xml new file mode 100644 index 00000000..5366c211 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJavaToJsonTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJsonTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJsonTest-context.xml new file mode 100644 index 00000000..d8ca3648 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJsonTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJsonToJavaTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJsonToJavaTest-context.xml new file mode 100644 index 00000000..e239b39c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentJsonToJavaTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentTest-context.xml new file mode 100644 index 00000000..d8ca3648 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlTest-context.xml new file mode 100644 index 00000000..7a6fe0b4 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapComponentXmlToXmlTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapExtractMappingsTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapExtractMappingsTest-context.xml new file mode 100644 index 00000000..1be3e6b1 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapExtractMappingsTest-context.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapJsonToXmlSchemaTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapJsonToXmlSchemaTest-context.xml new file mode 100644 index 00000000..87fbae26 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapJsonToXmlSchemaTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapMultiDocsTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapMultiDocsTest-context.xml new file mode 100644 index 00000000..d705dcf2 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapMultiDocsTest-context.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapMultiNSTest-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapMultiNSTest-context.xml new file mode 100644 index 00000000..612f91b1 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/AtlasMapMultiNSTest-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/2552-input.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/2552-input.json new file mode 100644 index 00000000..c8d78533 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/2552-input.json @@ -0,0 +1,17 @@ +[ + { + "id" : 1111, + "completed" : 1, + "task" : "task1" + }, + { + "id" : 2222, + "completed" : null, + "task" : "task2" + }, + { + "id" : 3333, + "completed" : 3, + "task" : "task3" + } +] \ No newline at end of file diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/AtlasMapIssue2552Test-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/AtlasMapIssue2552Test-context.xml new file mode 100644 index 00000000..884db2b1 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/AtlasMapIssue2552Test-context.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/AtlasMapIssue729Test-context.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/AtlasMapIssue729Test-context.xml new file mode 100644 index 00000000..12440ec1 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/AtlasMapIssue729Test-context.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-2552-new.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-2552-new.json new file mode 100644 index 00000000..7e50789c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-2552-new.json @@ -0,0 +1,83 @@ +{ + "AtlasMapping" : { + "jsonType" : "io.atlasmap.v2.AtlasMapping", + "dataSource" : [ { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "JsonSource", + "uri" : "atlas:json:JsonSource", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "JsonTarget", + "uri" : "atlas:json:JsonTarget", + "dataSourceType" : "TARGET" + } ], + "mappings" : { + "mapping" : [ { + "jsonType" : "io.atlasmap.v2.Mapping", + "id": "mapping.459765", + "inputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "id", + "path": "/<>/id", + "fieldType": "BIG_INTEGER", + "docId": "JsonSource", + "userCreated": false + } ], + "outputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "id", + "path": "/body<>/id", + "fieldType": "BIG_INTEGER", + "docId": "JsonTarget", + "userCreated": false + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "id": "mapping.352061", + "inputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "completed", + "path": "/<>/completed", + "fieldType": "BIG_INTEGER", + "docId": "JsonSource", + "userCreated": false + } ], + "outputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "completed", + "path": "/body<>/completed", + "fieldType": "BIG_INTEGER", + "docId": "JsonTarget", + "userCreated": false + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "id": "mapping.252216", + "inputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "task", + "path": "/<>/task", + "fieldType": "STRING", + "docId": "JsonSource", + "userCreated": false + } ], + "outputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "completed", + "path": "/body<>/task", + "fieldType": "STRING", + "docId": "JsonTarget", + "userCreated": false + } ] + } ] + }, + "lookupTables" : { + "lookupTable" : [ ] + }, + "properties" : { + "property" : [ ] + }, + "name" : "mockMapping" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-2552-old.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-2552-old.json new file mode 100644 index 00000000..85cdf378 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-2552-old.json @@ -0,0 +1,83 @@ +{ + "AtlasMapping" : { + "jsonType" : "io.atlasmap.v2.AtlasMapping", + "dataSource" : [ { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "JsonSource", + "uri" : "atlas:json:JsonSource", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "JsonTarget", + "uri" : "atlas:json:JsonTarget", + "dataSourceType" : "TARGET" + } ], + "mappings" : { + "mapping" : [ { + "jsonType" : "io.atlasmap.v2.Mapping", + "id": "mapping.459765", + "inputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "id", + "path": "/<>/id", + "fieldType": "INTEGER", + "docId": "JsonSource", + "userCreated": false + } ], + "outputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "id", + "path": "/body<>/id", + "fieldType": "INTEGER", + "docId": "JsonTarget", + "userCreated": false + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "id": "mapping.352061", + "inputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "completed", + "path": "/<>/completed", + "fieldType": "INTEGER", + "docId": "JsonSource", + "userCreated": false + } ], + "outputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "completed", + "path": "/body<>/completed", + "fieldType": "INTEGER", + "docId": "JsonTarget", + "userCreated": false + } ] + }, { + "jsonType" : "io.atlasmap.v2.Mapping", + "id": "mapping.252216", + "inputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "task", + "path": "/<>/task", + "fieldType": "STRING", + "docId": "JsonSource", + "userCreated": false + } ], + "outputField" : [ { + "jsonType": "io.atlasmap.json.v2.JsonField", + "name": "completed", + "path": "/body<>/task", + "fieldType": "STRING", + "docId": "JsonTarget", + "userCreated": false + } ] + } ] + }, + "lookupTables" : { + "lookupTable" : [ ] + }, + "properties" : { + "property" : [ ] + }, + "name" : "mockMapping" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-issue-729.json b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-issue-729.json new file mode 100644 index 00000000..2175e75e --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/org/apache/camel/component/atlasmap/issue/atlasmapping-issue-729.json @@ -0,0 +1,65 @@ +{ + "AtlasMapping" : { + "jsonType" : "io.atlasmap.v2.AtlasMapping", + "dataSource" : [ { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID:JAVA:CONTACT:S", + "uri" : "atlas:java?className=io.atlasmap.java.test.SourceContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID:JSON:CONTACT:S", + "uri" : "atlas:json:JSONContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID:XML:CONTACT:S", + "uri" : "atlas:xml:XMLContact", + "dataSourceType" : "SOURCE" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID:JAVA:CONTACT:T", + "uri" : "atlas:java?className=io.atlasmap.java.test.TargetContact", + "dataSourceType" : "TARGET" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID:JSON:CONTACT:T", + "uri" : "atlas:json:JSONContact", + "dataSourceType" : "TARGET" + }, { + "jsonType" : "io.atlasmap.v2.DataSource", + "id" : "DOCID:XML:CONTACT:T", + "uri" : "atlas:xml:XMLContact", + "dataSourceType" : "TARGET" + } ], + "mappings" : { + "mapping" : [ { + "jsonType" : "io.atlasmap.v2.Mapping", + "mappingType" : "MAP", + "inputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID:JAVA:CONTACT:S", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName", + "getMethod" : "getFirstName" + } ], + "outputField" : [ { + "jsonType" : "io.atlasmap.java.v2.JavaField", + "docId" : "DOCID:JAVA:CONTACT:T", + "path" : "/firstName", + "fieldType" : "STRING", + "name" : "firstName", + "setMethod" : "setFirstName" + } ] + } ] + }, + "lookupTables" : { + "lookupTable" : [ ] + }, + "properties" : { + "property" : [ ] + }, + "name" : "mockMapping" + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/xml-target-schemaset.xml b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/xml-target-schemaset.xml new file mode 100644 index 00000000..c50ceaf4 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-camel3/src/test/resources/xml-target-schemaset.xml @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/LICENSE.txt b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/LICENSE.txt new file mode 100644 index 00000000..4ae94b75 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/LICENSE.txt @@ -0,0 +1,175 @@ + ЛИЦЕНЗИЯ ОГРАНИЧЕННОГО ПРИМЕНЕНИЯ + +Настоящий документ устанавливает для Пользователя условия применения Базовой (некоммерческой) +версии лицензии для пробного использования программного обеспечения ENTAXY, принадлежащего +Правообладателю – Обществу с ограниченной ответственностью "ЕМДЕВ" (ОГРН 1057810026658, ИНН +7813313860, юридический адрес: 197022, Россия, г. Санкт-Петербург, ул. Профессора Попова, +д. 23, литера В, помещение 3Н), расположенной в сети Интернет по адресу +https://www.emdev.ru/about (далее - Компания). + +Используя или получая доступ к Программному обеспечению, или нажав «Я согласен с Условиями» +(или аналогичную кнопку или флажок) после загрузки или установки Программного обеспечения, +Пользователь выражает свое согласие на обязательность условий и ограничений, изложенных в +настоящем документе, в противном случае, он должен не использовать или не получать доступ +к Программному обеспечению. + + 1. ТЕРМИНЫ И ОПРЕДЕЛЕНИЯ + +a) ПО – Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) в любой ее версии +или редакции, исключительные права на которую принадлежат Правообладателю. +b) Правообладатель (Компания) – ООО «ЕМДЕВ», ОГРН 1057810026658, ИНН 7813313860, исключительные +права которого подтверждаются Свидетельством о государственной регистрации в Реестре программ +для ЭВМ № 2021610848 от 19.01.2021 года. +c) Пользователь – юридическое или физическое лицо, получившее через скачивание с сайта +https://entaxy.ru или иным образом, дистрибутив ПО, пользующееся ПО. +d) ИС – интеллектуальная собственность – закреплённое законом исключительное право, а также +личные неимущественные права авторов произведений на результат интеллектуальной деятельности. +e) Подписка – это коммерческое предложение Правообладателя, состоящее из Лицензии на использование +ПО и доступа к технической поддержке программного обеспечения на срок Подписки. Подписка +включает предоставление Пользователю неисключительного права использования ПО, в том числе +получение обновлений функционала ПО и безопасности ПО, исправление ошибок ПО и получение +патчей с обновлениями и исправлениями программного обеспечения. Подписка приобретается +Пользователем на период времени, указанный в Сертификате. Количество подписок устанавливается +для каждого Пользователя индивидуально в Сертификате. +f) Сертификат – документ, выдаваемый Дистрибъютором или Авторизованным партнёром (Партнёром), +подтверждающий факт приобретения физическим или юридическим лицом Подписки на программное +обеспечение в ограниченном объёме и на определённый период времени. +g) Лицензия (простая (неисключительная) – совокупность ограниченных прав использования ПО, +предоставленных Пользователю согласно условиям Подписки. +h) Библиотека – совокупность подпрограмм и объектов, используемых для разработки программного +обеспечения. +i) Исходный код – текст компьютерной программы на каком-либо языке программирования, состоящий +из одного или нескольких файлов, который может быть прочтён человеком. +j) Объектный код – файл (часть машинного кода) с промежуточным представлением отдельного модуля +программы, полученный в результате обработки исходного кода, еще не связанный в полную программу. +Это машинный код для одной конкретной библиотеки или модуля, который будет составлять готовый +продукт. +k) Некоммерческое использование – индивидуальное личное использование Пользователем программного +обеспечения с целью обучения работе с Программным обеспечением, для оценки или демонстрации +возможностей Программного обеспечения, при котором, Пользователем не извлекается коммерческая +выгода и/или не идёт в доход денежное вознаграждение при использовании Программного обеспечения. + + 2. ДОПУСТИМЫЕ СПОСОБЫ ИСПОЛЬЗОВАНИЯ ПРОГРАММНОГО ОБЕСПЕЧЕНИЯ + +2.1. Правообладатель предоставляет Пользователю ограниченное право использования Программного +обеспечения на условиях простой (неисключительной) лицензии в объёме, ограниченном правом +воспроизведения полной рабочей версии программного обеспечения, новых версий программного обеспечения +в памяти оборудования и его запуска на оборудовании в соответствии со ст. 1280 ГК РФ. +2.2. Право на использование Программного обеспечения, предоставляемое Пользователю, носит +неисключительный характер. +2.3. Пользователю предоставляется всемирная, неисключительная, не подлежащая сублицензированию, +лицензия на ограниченное использование Программного обеспечения. +2.4. Пользователь, имеющий Базовую (некоммерческую) версию лицензии для пробного использования +имеет право приобрести Подписку на программное обеспечение. В этом случае Пользователь обязан +обратиться в службу поддержки Правообладателя по адресу: https://entaxy.ru/ для изменения +вида лицензии с Базовой бесплатной версии на Подписки. +2.5. Срок использования скачанной Пользователем базовой (некоммерческой) версии лицензии для +пробного использования программного обеспечения – не ограничен. +2.6. Использование Пользователем настоящего программного обеспечения в целях разработки, +модификации, обновления другого ПО, принадлежащего третьим лицам, а не Правообладателю, +без разрешения Правообладателя не допускается. + + 3. АВТОРСКОЕ ПРАВО. + +3.1. Все авторские права, все права интеллектуальной собственности на Программное обеспечение +и любые его копии принадлежат Правообладателю. +3.2. Все авторские права, все права интеллектуальной собственности в отношении любого контента, +к которому можно получить доступ с помощью Программного обеспечения, является собственностью +соответствующего владельца контента и защищается применимым законодательством об авторском +праве или другими законами и договорами об интеллектуальной собственности. +3.3. Условия использования Программного обеспечения. +Лицензия, предоставленная Пользователю, действительна только в том случае, если Пользователь +придерживается следующих условий: +3.3.1. Принятие уведомлений об авторских правах. Пользователю запрещается удалять или изменять +какие-либо уведомления об авторских правах или лицензиях, которые появляются при использовании +Программного обеспечения или на нем. +3.3.2. Модификация. Пользователю запрещается модифицировать, изменять, декомпилировать, +расшифровывать, дизассемблировать, переводить или реверсировать, перепроектировать +Программное обеспечение. +3.3.3. Распространение. Пользователю запрещается сублицензировать, передавать право использования +ПО или иным образом распространять или предоставлять Программное обеспечение любой третьей стороне. +3.3.4. SaaS. За исключением случаев, когда это разрешено Правообладателем, Пользователю запрещено +использовать Программное обеспечение в коммерческих целях для оказания услуг третьим лицам. + + 4. ОТВЕТСТВЕННОСТЬ ПРАВООБЛАДАТЕЛЯ ПРИ НАРУШЕНИИ ПОЛЬЗОВАТЕЛЕМ ПРАВ «ИС» + +4.1. Правообладатель не несет никаких обязательств в отношении каких-либо претензий к Пользователю +на предмет нарушения последним прав Интеллектуальной собственности, возникших в связи с +использованием Пользователем: +4.1.1. Любых компонентов программного обеспечения с открытым исходным кодом, включенных в +Программное обеспечение; +4.1.2. Любого нарушения правил использования Программного обеспечения, установленного условиями +настоящего соглашения; +4.1.3. Любого использования Программного обеспечения в сочетании с другими ПО, оборудованием, +или данными, не предоставленными Пользователю Правообладателем; +4.1.4. Любого изменения Программного обеспечения любым третьим лицом, а не Правообладателем. + + +5. НАСТОЯЩИМ ПРАВООБЛАДАТЕЛЬ ЗАЯВЛЯЕТ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ ПРЕДОСТАВЛЯЕТСЯ ПОЛЬЗОВАТЕЛЮ +ПО ПРИНЦИПУ «AS IS» - «КАК ЕСТЬ». НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ НЕ ГАРАНТИРУЕТ +И НЕ ОБЕЩАЕТ, ЧТО ПРЕДОСТАВЛЕННОЕ ИМ ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ПОДХОДИТЬ ИЛИ НЕ ПОДХОДИТЬ +ДЛЯ КОНКРЕТНЫХ ЦЕЛЕЙ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ ОТВЕЧАТЬ ВСЕМ КОММЕРЧЕСКИМ +И ЛИЧНЫМ СУБЪЕКТИВНЫМ ОЖИДАНИЯМ ПОЛЬЗОВАТЕЛЯ, ЧТО ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ БУДЕТ РАБОТАТЬ +ИСПРАВНО, БЕЗ ТЕХНИЧЕСКИХ ОШИБОК, БЫСТРО И БЕСПЕРЕБОЙНО. + + 6. ОГРАНИЧЕНИЕ ОТВЕТСТВЕННОСТИ. +НИ ПРИ КАКИХ ОБСТОЯТЕЛЬСТВАХ ПРАВООБЛАДАТЕЛЬ ИЛИ ЕГО АФФИЛЛИРОВАННЫЕ ЛИЦА НЕ НЕСУТ ПЕРЕД ПОЛЬЗОВАТЕЛЕМ +ОТВЕТСТВЕННОСТИ ЗА ЛЮБЫЕ ПРЯМЫЕ ИЛИ КОСВЕННЫЕ УБЫТКИ ПОЛЬЗОВАТЕЛЯ, ЕГО РАСХОДЫ ИЛИ РЕАЛЬНЫЙ УЩЕРБ, +ВКЛЮЧАЯ, ПОМИМО ПРОЧЕГО, ПРОСТОИ; УТРАТУ БИЗНЕСА; УПУЩЕННУЮ ВЫГОДУ; НЕДОПОЛУЧЕННУЮ ПРИБЫЛЬ; +ПОТЕРЮ ИЛИ ПОВРЕЖДЕНИЕ ДАННЫХ, ИМУЩЕСТВА И ИНОЕ. +ОГРАНИЧЕНИЯ ПРИМЕНЯЮТСЯ НЕЗАВИСИМО ОТ ОСНОВАНИЯ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ; В ТОМ ЧИСЛЕ ВСЛЕДСТВИЕ +ДЕЙСТВИЯ ИЛИ БЕЗДЕЙСТВИЯ, НЕБРЕЖНОСТИ, УМЫСЛА, ПРЯМОГО ИЛИ КОСВЕННОГО; НЕОСТОРОЖНОСТИ; ЗАБЛУЖДЕНИЯ; +КЛЕВЕТЫ; НАРУШЕНИЯ КОНФИДЕНЦИАЛЬНОСТИ ИЛИ ПРАВА ИНТЕЛЛЕКТУАЛЬНОЙ СОБСТВЕННОСТИ; ИЛИ ЛЮБОЕ ДРУГОЕ +ОСНОВАНИЕ НАСТУПЛЕНИЯ ОТВЕТСТВЕННОСТИ. + + 7. ОБЯЗАННОСТЬ ПОЛЬЗОВАТЕЛЯ: +Не осуществлять самостоятельно и (или) с привлечением третьих лиц нижеследующие действия +(включая, но не ограничиваясь) по: +-дизассемблированию и (или) декомпилированию (преобразованию объектного кода в исходный код) + Программного обеспечения; +-модификации Программного обеспечения, в том числе вносить изменения в объектный код, исходный +код Программного обеспечения, за исключением тех изменений, которые вносятся средствами, +включёнными в Программное обеспечение и описанными непосредственно в документации к нему; +-созданию условий для использования Программного обеспечения лицами, не имеющими прав на +использование данного Программного обеспечения, включая (но не ограничиваясь) вмешательство +третьих лиц в функционирование Программного обеспечения, предоставление третьим лицам доступа +к исследованию и (или) замене настроек Программного обеспечения, включая его первичную установку; +-распространению Программного обеспечения в целом или в части (включая приложенную к нему документацию). + + 8. БИБЛИОТЕКА ПО. ИСПОЛЬЗУЕМЫЕ ПРОГРАММНЫЕ СРЕДСТВА. + +8.1. Настоящим, Правообладатель заверяет, что Библиотека программного обеспечения состоит из +лицензионных продуктов, используемых на законных основаниях, а +именно https://entaxy.ru/libs/licenses/root-aggregated.deps. +8.2. Любые программные средства, применяемые Пользователем при работе с ПО, должны быть +совместимы с библиотекой ПО, указанной в п.8.1. настоящего соглашения. +8.3. Перечень внешних модулей ПО, указанный в п.8.1 настоящего соглашения, может изменяться +Правообладателем в одностороннем порядке, в зависимости от выпуска релизов программного обеспечения, +содержащих все изменения и дополнения программного обеспечения. + + 9. ВНЕСЕНИЕ ИЗМЕНЕНИЙ В ПРОГРАММНОЕ ОБЕСПЕЧЕНИЕ. + +9.1. Программное обеспечение, интеграционная шина «ЭНТАКСИ» (ENTAXY) является свободно распространяемым +программным обеспечением. +9.2. Пользователь имеет право вносить изменения в исходный код программного обеспечения исключительно +с согласия Правообладателя в порядке предложения изменений/правок/дополнений через механизм +«Pull Requests» в открытом репозитории Правообладателя по адресу: https://git.entaxy.ru/entaxy/entaxy-public. +9.3. Любые изменения программного обеспечения, осуществляемые Пользователем без соблюдения условий +пункта 9.2. настоящего документа, являются нарушением авторских и смежных прав Правообладателя, +прав интеллектуальной собственности Правообладателя и влекут применение к Пользователю мер +ответственности в соответствии с условиями настоящей Лицензии, а также применимого законодательства +Российской Федерации. + + 10. ЗАКЛЮЧИТЕЛЬНЫЕ ПОЛОЖЕНИЯ. + +10.1. В случае нарушения Пользователем любого из условий настоящей Лицензии, Правообладатель имеет +право взыскать с Пользователя любые причинённые таким нарушением убытки, реальный ущерб, +недополученную прибыль, упущенную выгоду, а также в случае нарушения Пользователем условий +пункта 9.2 настоящего соглашения, в том числе, взыскать с Пользователя штраф в размере +2 000 000 (Два миллиона) рублей за каждый установленный случай несанкционированного изменения +исходного или объектного кода Программного обеспечения «Энтакси» (Entaxy). +10.2. В рамках исполнения Пользователем обязательств по настоящей Лицензии, применимое +законодательство – Российской Федерации. +10.3. Если какое-либо положение настоящей Лицензии будет признано судом недействительным, +остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать +исполнять свои обязанности в соответствии с этими положениями. diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/README.md b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/README.md new file mode 100644 index 00000000..02edf1ff --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/README.md @@ -0,0 +1,42 @@ +# ATLASMAP :: ENTAXY :: REST API + +Реализация rest-сервиса для работы AtlasMap UI. Данные проект скомпанован из нескольких отдельных Maven проектов в рамках [AtlasMap 2.5.2](https://github.com/atlasmap/atlasmap/tree/atlasmap-2.5.2/lib). Из перенесённого UI были убраны часть фич для упрощения - например, работа с Java объектами и возможность их подгрузить для конвертации. На текущий момент оставили поддержку xml и json. +Для работы необходимо установить следующие бандлы: +- install mvn:ru.entaxy.esb.temp/atlasmap-entaxy-management/1.9.0-SNAPSHOT +- install mvn:ru.entaxy.esb.ui.hawtio/entaxy-atlasmap-plugin/1.9.0-SNAPSHOT/war +- install mvn:com.fasterxml.jackson.module/jackson-module-jsonSchema/2.9.10 +- install mvn:ru.entaxy.com.sun.xsom/xsom/1.9.0-SNAPSHOT +- install wrap:mvn:relaxngDatatype/relaxngDatatype/20020414 +- install mvn:ru.entaxy.esb.temp/atlasmap-entaxy-services/1.9.0-SNAPSHOT +- install mvn:ru.entaxy.esb.temp/atlasmap-entaxy-ui/1.9.0-SNAPSHOT/war + +После успешной установки: + +590 │ Active │ 80 │ 1.9.0.SNAPSHOT │ ENTAXY :: ATLASMAP :: MANAGEMENT + +593 │ Active │ 80 │ 1.9.0.SNAPSHOT │ ENTAXY :: UI :: HAWTIO :: ENTAXY ATLASMAP + +600 │ Active │ 80 │ 2.9.10 │ jackson-module-jsonSchema + +601 │ Active │ 80 │ 1.9.0.SNAPSHOT │ ENTAXY :: ATLASMAP :: XSOM + +603 │ Active │ 80 │ 0 │ wrap_mvn_relaxngDatatype_relaxngDatatype_20020414 + +608 │ Active │ 80 │ 1.9.0.SNAPSHOT │ ENTAXY :: ATLASMAP :: REST API + +612 │ Active │ 80 │ 1.9.0.SNAPSHOT │ ENTAXY :: ATLASMAP :: UI + + +## Обратить внимание + +1. Список TODO в коде - одна из проблем была с совместимостью Jackson. В Camel 3.4.5 используется старая версия 2.9.х, а в AtlasMap уже 2.12. Они почти совместимы, кроме одной константы - MapperFeature.BLOCK_UNSAFE_POLYMORPHIC_BASE_TYPES - её пришлось закомментировать в коде. + +2. Проект XSOM - был перенесён к нам + +3. В Java есть своя реализация Dependency Injection - java.util.ServiceLoader - при помощи этого механизма подгружаются готовые реализации преобразований полей в io.atlasmap.core.DefaultAtlasFieldActionService. Для работы нужны описания - это файлы в META-INF/services + +4. Подгрузка модулей работы с различными форматами идёт в io.atlasmap.core.DefaultAtlasContextFactory из файла META-INF/services/atlas/atlas.module - пока там JSON и XML + +5. В корне resources нужен файл atlasmap.properties с версией + +6. Из UI был убран двойной content-type при вызове @Path("/fieldActions") - это приводило к ошибке diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/pom.xml b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/pom.xml new file mode 100644 index 00000000..be08d1f4 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/pom.xml @@ -0,0 +1,98 @@ + + + + 4.0.0 + + + ru.entaxy.esb.platform.runtime.modules + atlasmap + 1.10.0 + + + ru.entaxy.esb.platform.runtime.modules.atlasmap + atlasmap-entaxy-libs + bundle + + ENTAXY :: ATLASMAP :: LIBS + ENTAXY :: ATLASMAP :: LIBS + + + 2.5.2 + 2.1.1 + + 2.9.10 + 2.9.10.8 + + io.atlasmap.api, + io.atlasmap.core, + io.atlasmap.spi, + io.atlasmap.v2, + io.atlasmap.json.inspect, + io.atlasmap.json.v2, + io.atlasmap.service, + io.atlasmap.v2, + io.atlasmap.xml.inspect, + io.atlasmap.xml.v2, + io.atlasmap.actions + + + + + + ru.entaxy.esb.platform.runtime.base + base-support + ${project.version} + + + + commons-codec + commons-codec + ${commons-codec.version} + + + org.apache.camel + camel-cxf + + + org.apache.camel.karaf + camel-cxf-blueprint + ${camel.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.databind.version} + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.module + jackson-module-jsonSchema + ${jackson.version} + + + ru.entaxy.com.sun.xsom + xsom + ${project.version} + + + io.swagger.core.v3 + swagger-annotations + ${swagger.v3.version} + + + javax.ws.rs + javax.ws.rs-api + ${javax.ws.rs.version} + + + + diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/CollectionActions.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/CollectionActions.java new file mode 100644 index 00000000..2af24fac --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/CollectionActions.java @@ -0,0 +1,57 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.CopyTo; +import io.atlasmap.v2.FieldType; + +public class CollectionActions implements AtlasFieldAction { + + @AtlasActionProcessor(sourceType = FieldType.ANY) + public static Object[] copyTo(CopyTo action, Object input) { + // This a noop processor. Nevertheless it's signature is important to signal that's a one-to-many action. + // It's behavior is implemented directly into DefaultAtlasContext + return new Object[]{}; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/DateFieldActions.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/DateFieldActions.java new file mode 100644 index 00000000..51fd3947 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/DateFieldActions.java @@ -0,0 +1,115 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import java.time.LocalDate; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; + +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.AddDays; +import io.atlasmap.v2.AddSeconds; +import io.atlasmap.v2.CurrentDate; +import io.atlasmap.v2.CurrentDateTime; +import io.atlasmap.v2.CurrentTime; +import io.atlasmap.v2.DayOfMonth; +import io.atlasmap.v2.DayOfWeek; +import io.atlasmap.v2.DayOfYear; +import io.atlasmap.v2.FieldType; + +public class DateFieldActions implements AtlasFieldAction { + + @AtlasActionProcessor(sourceType = FieldType.ANY_DATE) + public static ZonedDateTime addDays(AddDays addDays, ZonedDateTime input) { + if (addDays == null) { + throw new IllegalArgumentException("AddDays action must be specified"); + } + if (input == null) { + return null; + } + + return input.plusDays(addDays.getDays() == null ? 0L : addDays.getDays()); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY_DATE) + public static ZonedDateTime addSeconds(AddSeconds addSeconds, ZonedDateTime input) { + if (addSeconds == null) { + throw new IllegalArgumentException("AddSeconds action must be specified"); + } + if (input == null) { + return null; + } + + return input.plusSeconds(addSeconds.getSeconds() == null ? 0L : addSeconds.getSeconds()); + } + + @AtlasActionProcessor + public static ZonedDateTime currentDate(CurrentDate action) { + return LocalDate.now().atStartOfDay(ZoneId.systemDefault()); + } + + @AtlasActionProcessor + public static ZonedDateTime currentDateTime(CurrentDateTime action) { + return LocalDate.now().atStartOfDay(ZoneId.systemDefault()); + } + + @AtlasActionProcessor + public static ZonedDateTime currentTime(CurrentTime action) { + return LocalTime.now().atDate(LocalDate.now()).atZone(ZoneId.systemDefault()); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY_DATE) + public static Integer dayOfMonth(DayOfMonth action, ZonedDateTime input) { + return input == null ? null : input.getDayOfMonth(); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY_DATE) + public static Integer dayOfWeek(DayOfWeek action, ZonedDateTime input) { + return input == null ? null : input.getDayOfWeek().getValue(); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY_DATE) + public static Integer dayOfYear(DayOfYear action, ZonedDateTime input) { + return input == null ? null : input.getDayOfYear(); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/ExpressionFieldAction.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/ExpressionFieldAction.java new file mode 100644 index 00000000..5f1bf3d2 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/ExpressionFieldAction.java @@ -0,0 +1,74 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import static io.atlasmap.v2.AtlasModelFactory.unwrapField; +import static io.atlasmap.v2.AtlasModelFactory.wrapWithField; + +import java.util.List; + +import io.atlasmap.core.DefaultAtlasFunctionResolver; +import io.atlasmap.expression.Expression; +import io.atlasmap.expression.ExpressionException; +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.Field; + +public class ExpressionFieldAction implements AtlasFieldAction { + + @AtlasActionProcessor + public static Object process(io.atlasmap.v2.Expression action, List args) throws ExpressionException { + if (action.getExpression() == null || action.getExpression().trim().isEmpty()) { + return null; + } + + Expression parsedExpression = Expression.parse(action.getExpression(), DefaultAtlasFunctionResolver.getInstance()); + Field answer = parsedExpression.evaluate((index) -> { + try { + return wrapWithField(args.get(Integer.parseInt(index))); + } catch (Throwable e) { + throw new ExpressionException("Invalid variable: " + index); + } + }); + return unwrapField(answer); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/NumberFieldActions.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/NumberFieldActions.java new file mode 100644 index 00000000..4964cb1c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/NumberFieldActions.java @@ -0,0 +1,477 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import java.math.BigDecimal; +import java.util.Collections; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.AbsoluteValue; +import io.atlasmap.v2.Add; +import io.atlasmap.v2.AreaUnitType; +import io.atlasmap.v2.Average; +import io.atlasmap.v2.Ceiling; +import io.atlasmap.v2.ConvertAreaUnit; +import io.atlasmap.v2.ConvertDistanceUnit; +import io.atlasmap.v2.ConvertMassUnit; +import io.atlasmap.v2.ConvertVolumeUnit; +import io.atlasmap.v2.DistanceUnitType; +import io.atlasmap.v2.Divide; +import io.atlasmap.v2.Floor; +import io.atlasmap.v2.MassUnitType; +import io.atlasmap.v2.Maximum; +import io.atlasmap.v2.Minimum; +import io.atlasmap.v2.Multiply; +import io.atlasmap.v2.Round; +import io.atlasmap.v2.Subtract; +import io.atlasmap.v2.VolumeUnitType; + +public class NumberFieldActions implements AtlasFieldAction { + private static final Logger LOG = LoggerFactory.getLogger(NumberFieldActions.class); + + // 1D + private static final double KILO_GRAMS_IN_A_POUND = 0.45359237; + private static final double YARDS_IN_A_MILE = 1760.0; + private static final double FEET_IN_A_YARD = 3.0; + private static final double INCHES_IN_A_FOOT = 12.0; + private static final double METERS_IN_A_INCH = 0.0254; + // 2D + private static final double SQUARE_FEET_IN_A_SQUARE_METER = Math.pow(1.0 / METERS_IN_A_INCH / INCHES_IN_A_FOOT, + 2.0); + private static final double SQUARE_METERS_IN_A_SQUARE_MILE = Math + .pow(YARDS_IN_A_MILE * FEET_IN_A_YARD * INCHES_IN_A_FOOT * METERS_IN_A_INCH, 2.0); + private static final double SQUARE_FEET_IN_A_SQUARE_MILE = Math.pow(YARDS_IN_A_MILE * FEET_IN_A_YARD, 2.0); + // 3D + private static final double LITERS_IN_A_CUBIC_METER = 1000.0; + private static final double CUBIC_FEET_IN_A_CUBIC_METER = Math.pow(1.0 / METERS_IN_A_INCH / INCHES_IN_A_FOOT, 3.0); + private static final double GALLONS_US_FLUID_IN_A_CUBIC_METER = 264.17205236; + + private static Map> massConvertionTable; + static { + Map> rootTable = new EnumMap<>(MassUnitType.class); + Map kgRates = new EnumMap<>(MassUnitType.class); + kgRates.put(MassUnitType.KILOGRAM_KG, 1.0); + kgRates.put(MassUnitType.POUND_LB, 1.0 / KILO_GRAMS_IN_A_POUND); + rootTable.put(MassUnitType.KILOGRAM_KG, Collections.unmodifiableMap(kgRates)); + Map lbsRates = new EnumMap<>(MassUnitType.class); + lbsRates.put(MassUnitType.KILOGRAM_KG, KILO_GRAMS_IN_A_POUND); + lbsRates.put(MassUnitType.POUND_LB, 1.0); + rootTable.put(MassUnitType.POUND_LB, Collections.unmodifiableMap(lbsRates)); + massConvertionTable = Collections.unmodifiableMap(rootTable); + } + + private static Map> distanceConvertionTable; + static { + Map> rootTable = new EnumMap<>(DistanceUnitType.class); + Map mRates = new EnumMap<>(DistanceUnitType.class); + mRates.put(DistanceUnitType.METER_M, 1.0); + mRates.put(DistanceUnitType.FOOT_FT, 1.0 / METERS_IN_A_INCH / INCHES_IN_A_FOOT); + mRates.put(DistanceUnitType.YARD_YD, 1.0 / METERS_IN_A_INCH / INCHES_IN_A_FOOT / FEET_IN_A_YARD); + mRates.put(DistanceUnitType.MILE_MI, 1.0 / METERS_IN_A_INCH / INCHES_IN_A_FOOT / FEET_IN_A_YARD / YARDS_IN_A_MILE); + mRates.put(DistanceUnitType.INCH_IN, 1.0 / METERS_IN_A_INCH); + rootTable.put(DistanceUnitType.METER_M, Collections.unmodifiableMap(mRates)); + Map ftRates = new EnumMap<>(DistanceUnitType.class); + ftRates.put(DistanceUnitType.METER_M, INCHES_IN_A_FOOT * METERS_IN_A_INCH); + ftRates.put(DistanceUnitType.FOOT_FT, 1.0); + ftRates.put(DistanceUnitType.YARD_YD, 1.0 / FEET_IN_A_YARD); + ftRates.put(DistanceUnitType.MILE_MI, 1.0 / FEET_IN_A_YARD / YARDS_IN_A_MILE); + ftRates.put(DistanceUnitType.INCH_IN, INCHES_IN_A_FOOT); + rootTable.put(DistanceUnitType.FOOT_FT, Collections.unmodifiableMap(ftRates)); + Map ydRates = new EnumMap<>(DistanceUnitType.class); + ydRates.put(DistanceUnitType.METER_M, FEET_IN_A_YARD * INCHES_IN_A_FOOT * METERS_IN_A_INCH); + ydRates.put(DistanceUnitType.FOOT_FT, FEET_IN_A_YARD); + ydRates.put(DistanceUnitType.YARD_YD, 1.0); + ydRates.put(DistanceUnitType.MILE_MI, 1.0 / YARDS_IN_A_MILE); + ydRates.put(DistanceUnitType.INCH_IN, FEET_IN_A_YARD * INCHES_IN_A_FOOT); + rootTable.put(DistanceUnitType.YARD_YD, Collections.unmodifiableMap(ydRates)); + Map miRates = new EnumMap<>(DistanceUnitType.class); + miRates.put(DistanceUnitType.METER_M, YARDS_IN_A_MILE * FEET_IN_A_YARD * INCHES_IN_A_FOOT * METERS_IN_A_INCH); + miRates.put(DistanceUnitType.FOOT_FT, YARDS_IN_A_MILE * FEET_IN_A_YARD); + miRates.put(DistanceUnitType.YARD_YD, YARDS_IN_A_MILE); + miRates.put(DistanceUnitType.MILE_MI, 1.0); + miRates.put(DistanceUnitType.INCH_IN, YARDS_IN_A_MILE * FEET_IN_A_YARD * INCHES_IN_A_FOOT); + rootTable.put(DistanceUnitType.MILE_MI, Collections.unmodifiableMap(miRates)); + Map inRates = new EnumMap<>(DistanceUnitType.class); + inRates.put(DistanceUnitType.METER_M, METERS_IN_A_INCH); + inRates.put(DistanceUnitType.FOOT_FT, 1.0 / INCHES_IN_A_FOOT); + inRates.put(DistanceUnitType.YARD_YD, 1.0 / INCHES_IN_A_FOOT / FEET_IN_A_YARD); + inRates.put(DistanceUnitType.MILE_MI, 1.0 / INCHES_IN_A_FOOT / FEET_IN_A_YARD / YARDS_IN_A_MILE); + inRates.put(DistanceUnitType.INCH_IN, 1.0); + rootTable.put(DistanceUnitType.INCH_IN, Collections.unmodifiableMap(inRates)); + distanceConvertionTable = Collections.unmodifiableMap(rootTable); + } + + private static Map> areaConvertionTable; + static { + Map> rootTable = new EnumMap<>(AreaUnitType.class); + Map m2Rates = new EnumMap<>(AreaUnitType.class); + m2Rates.put(AreaUnitType.SQUARE_METER, 1.0); + m2Rates.put(AreaUnitType.SQUARE_FOOT, SQUARE_FEET_IN_A_SQUARE_METER); + m2Rates.put(AreaUnitType.SQUARE_MILE, 1.0 / SQUARE_METERS_IN_A_SQUARE_MILE); + rootTable.put(AreaUnitType.SQUARE_METER, Collections.unmodifiableMap(m2Rates)); + Map ft2Rates = new EnumMap<>(AreaUnitType.class); + ft2Rates.put(AreaUnitType.SQUARE_METER, 1.0 / SQUARE_FEET_IN_A_SQUARE_METER); + ft2Rates.put(AreaUnitType.SQUARE_FOOT, 1.0); + ft2Rates.put(AreaUnitType.SQUARE_MILE, 1.0 / SQUARE_FEET_IN_A_SQUARE_MILE); + rootTable.put(AreaUnitType.SQUARE_FOOT, Collections.unmodifiableMap(ft2Rates)); + Map mi2Rates = new EnumMap<>(AreaUnitType.class); + mi2Rates.put(AreaUnitType.SQUARE_METER, SQUARE_METERS_IN_A_SQUARE_MILE); + mi2Rates.put(AreaUnitType.SQUARE_FOOT, SQUARE_FEET_IN_A_SQUARE_MILE); + mi2Rates.put(AreaUnitType.SQUARE_MILE, 1.0); + rootTable.put(AreaUnitType.SQUARE_MILE, Collections.unmodifiableMap(mi2Rates)); + areaConvertionTable = Collections.unmodifiableMap(rootTable); + } + + private static Map> volumeConvertionTable; + static { + Map> rootTable = new EnumMap<>(VolumeUnitType.class); + Map m3Rates = new EnumMap<>(VolumeUnitType.class); + m3Rates.put(VolumeUnitType.CUBIC_METER, 1.0); + m3Rates.put(VolumeUnitType.LITER, LITERS_IN_A_CUBIC_METER); + m3Rates.put(VolumeUnitType.CUBIC_FOOT, CUBIC_FEET_IN_A_CUBIC_METER); + m3Rates.put(VolumeUnitType.GALLON_US_FLUID, GALLONS_US_FLUID_IN_A_CUBIC_METER); + rootTable.put(VolumeUnitType.CUBIC_METER, Collections.unmodifiableMap(m3Rates)); + Map literRates = new EnumMap<>(VolumeUnitType.class); + literRates.put(VolumeUnitType.CUBIC_METER, 1.0 / LITERS_IN_A_CUBIC_METER); + literRates.put(VolumeUnitType.LITER, 1.0); + literRates.put(VolumeUnitType.CUBIC_FOOT, 1.0 / LITERS_IN_A_CUBIC_METER * CUBIC_FEET_IN_A_CUBIC_METER); + literRates.put(VolumeUnitType.GALLON_US_FLUID, + 1.0 / LITERS_IN_A_CUBIC_METER * GALLONS_US_FLUID_IN_A_CUBIC_METER); + rootTable.put(VolumeUnitType.LITER, Collections.unmodifiableMap(literRates)); + Map cftRates = new EnumMap<>(VolumeUnitType.class); + cftRates.put(VolumeUnitType.CUBIC_METER, 1.0 / CUBIC_FEET_IN_A_CUBIC_METER); + cftRates.put(VolumeUnitType.LITER, 1.0 / CUBIC_FEET_IN_A_CUBIC_METER * LITERS_IN_A_CUBIC_METER); + cftRates.put(VolumeUnitType.CUBIC_FOOT, 1.0); + cftRates.put(VolumeUnitType.GALLON_US_FLUID, + 1.0 / CUBIC_FEET_IN_A_CUBIC_METER * GALLONS_US_FLUID_IN_A_CUBIC_METER); + rootTable.put(VolumeUnitType.CUBIC_FOOT, Collections.unmodifiableMap(cftRates)); + Map galUsFluidRates = new EnumMap<>(VolumeUnitType.class); + galUsFluidRates.put(VolumeUnitType.CUBIC_METER, 1.0 / GALLONS_US_FLUID_IN_A_CUBIC_METER); + galUsFluidRates.put(VolumeUnitType.LITER, 1.0 / GALLONS_US_FLUID_IN_A_CUBIC_METER * LITERS_IN_A_CUBIC_METER); + galUsFluidRates.put(VolumeUnitType.CUBIC_FOOT, + 1.0 / GALLONS_US_FLUID_IN_A_CUBIC_METER * CUBIC_FEET_IN_A_CUBIC_METER); + galUsFluidRates.put(VolumeUnitType.GALLON_US_FLUID, 1.0); + rootTable.put(VolumeUnitType.GALLON_US_FLUID, Collections.unmodifiableMap(galUsFluidRates)); + volumeConvertionTable = Collections.unmodifiableMap(rootTable); + } + + @AtlasActionProcessor + public static Number absoluteValue(AbsoluteValue action, Number input) { + if (input == null) { + return 0; + } + if (input instanceof BigDecimal) { + return ((BigDecimal) input).abs(); + } + if (requiresDoubleResult(input)) { + return Math.abs(input.doubleValue()); + } + return Math.abs(input.longValue()); + } + + @AtlasActionProcessor + public static Number add(Add action, List inputs) { + if (inputs == null) { + return 0; + } + + Number sum = 0L; + for (Object entry : inputs) { + if (entry instanceof Number) { + if (sum instanceof BigDecimal) { + sum = ((BigDecimal) sum).add(BigDecimal.valueOf(((Number) entry).doubleValue())); + } else if (entry instanceof BigDecimal) { + sum = BigDecimal.valueOf(sum.doubleValue()).add((BigDecimal) entry); + } else if (requiresDoubleResult(sum) || requiresDoubleResult(entry)) { + sum = sum.doubleValue() + ((Number) entry).doubleValue(); + } else { + sum = sum.longValue() + ((Number) entry).longValue(); + } + } else { + warnIgnoringValue("Add", entry); + } + } + + return sum; + } + + @AtlasActionProcessor + public static Number average(Average action, List inputs) { + if (inputs == null) { + return 0; + } + return add(null, inputs).doubleValue() / inputs.size(); + } + + @AtlasActionProcessor + public static Number ceiling(Ceiling action, Number input) { + return input == null ? 0L : (long)Math.ceil(input.doubleValue()); + } + + @AtlasActionProcessor + public static Number convertMassUnit(ConvertMassUnit convertMassUnit, Number input) { + if (input == null) { + return 0; + } + + if (convertMassUnit == null || convertMassUnit.getFromUnit() == null + || convertMassUnit.getToUnit() == null) { + throw new IllegalArgumentException("ConvertMassUnit must be specified with fromUnit and toUnit"); + } + + MassUnitType fromUnit = convertMassUnit.getFromUnit(); + MassUnitType toUnit = convertMassUnit.getToUnit(); + double rate = massConvertionTable.get(fromUnit).get(toUnit); + return doMultiply(input, rate); + } + + @AtlasActionProcessor + public static Number convertDistanceUnit(ConvertDistanceUnit convertDistanceUnit, Number input) { + if (input == null) { + return 0; + } + + if (convertDistanceUnit == null || convertDistanceUnit.getFromUnit() == null + || convertDistanceUnit.getToUnit() == null) { + throw new IllegalArgumentException("ConvertDistanceUnit must be specified with fromUnit and toUnit"); + } + + DistanceUnitType fromUnit = convertDistanceUnit.getFromUnit(); + DistanceUnitType toUnit = convertDistanceUnit.getToUnit(); + double rate = distanceConvertionTable.get(fromUnit).get(toUnit); + return doMultiply(input, rate); + } + + @AtlasActionProcessor + public static Number convertAreaUnit(ConvertAreaUnit convertAreaUnit, Number input) { + if (input == null) { + return 0; + } + + if (convertAreaUnit == null || convertAreaUnit.getFromUnit() == null + || convertAreaUnit.getToUnit() == null) { + throw new IllegalArgumentException("ConvertAreaUnit must be specified with fromUnit and toUnit"); + } + + AreaUnitType fromUnit = convertAreaUnit.getFromUnit(); + AreaUnitType toUnit = convertAreaUnit.getToUnit(); + double rate = areaConvertionTable.get(fromUnit).get(toUnit); + return doMultiply(input, rate); + } + + @AtlasActionProcessor + public static Number convertVolumeUnit(ConvertVolumeUnit convertVolumeUnit, Number input) { + if (input == null) { + return 0; + } + + if (convertVolumeUnit == null || convertVolumeUnit.getFromUnit() == null + || convertVolumeUnit.getToUnit() == null) { + throw new IllegalArgumentException("ConvertVolumeUnit must be specified with fromUnit and toUnit"); + } + + VolumeUnitType fromUnit = convertVolumeUnit.getFromUnit(); + VolumeUnitType toUnit = convertVolumeUnit.getToUnit(); + double rate = volumeConvertionTable.get(fromUnit).get(toUnit); + return doMultiply(input, rate); + } + + @AtlasActionProcessor + public static Number divide(Divide divide, List inputs) { + if (inputs == null) { + return 0; + } + + Number quotient = null; + for (Object entry : inputs) { + if (entry instanceof Number) { + if (quotient == null) { + quotient = (Number) entry; + } else if (quotient instanceof BigDecimal) { + quotient = ((BigDecimal) quotient).divide(BigDecimal.valueOf(((Number) entry).doubleValue())); + } else if (entry instanceof BigDecimal) { + quotient = BigDecimal.valueOf(quotient.doubleValue()).divide((BigDecimal) entry); + } else { + quotient = quotient.doubleValue() / ((Number) entry).doubleValue(); + } + } else { + warnIgnoringValue("Divide", entry); + } + } + + return quotient; + } + + @AtlasActionProcessor + public static Number floor(Floor floor, Number input) { + return input == null ? 0L : (long)Math.floor(input.doubleValue()); + } + + @AtlasActionProcessor + public static Number maximum(Maximum maximum, List inputs) { + if (inputs == null) { + return 0; + } + + Number max = null; + for (Object entry : inputs) { + if (entry instanceof Number) { + if (max instanceof BigDecimal && entry instanceof BigDecimal) { + max = ((BigDecimal) entry).max((BigDecimal)max); + } else if (max == null || ((Number) entry).doubleValue() > max.doubleValue()) { + max = (Number) entry; + } + } else { + warnIgnoringValue("Maximum", entry); + } + } + + return max; + } + + @AtlasActionProcessor + public static Number minimum(Minimum minimum, List inputs) { + if (inputs == null) { + return 0; + } + + Number min = null; + for (Object entry : inputs) { + if (entry instanceof Number) { + if (min instanceof BigDecimal && entry instanceof BigDecimal) { + min = ((BigDecimal) entry).min((BigDecimal)min); + } else if (min == null || ((Number) entry).doubleValue() < min.doubleValue()) { + min = (Number) entry; + } + } else { + warnIgnoringValue("Minimum", entry); + } + } + + return min; + } + + @AtlasActionProcessor + public static Number multiply(Multiply multiply, List inputs) { + if (inputs == null) { + return 0; + } + + Number product = 1L; + for (Object entry : inputs) { + if (entry instanceof Number) { + if (product instanceof BigDecimal) { + product = ((BigDecimal) product).multiply(BigDecimal.valueOf(((Number) entry).doubleValue())); + } else if (entry instanceof BigDecimal) { + product = BigDecimal.valueOf(product.doubleValue()).multiply((BigDecimal) entry); + } else if (requiresDoubleResult(product) || requiresDoubleResult(entry)) { + product = product.doubleValue() * ((Number) entry).doubleValue(); + } else { + product = product.longValue() * ((Number) entry).longValue(); + } + } else { + warnIgnoringValue("Multiply", entry); + } + } + + return product; + } + + @AtlasActionProcessor + public static Number round(Round action, Number input) { + return input == null ? 0L : Math.round(input.doubleValue()); + } + + @AtlasActionProcessor + public static Number subtract(Subtract subtract, List inputs) { + if (inputs == null) { + return 0; + } + + Number difference = null; + for (Object entry : inputs) { + if (entry instanceof Number) { + if (difference == null) { + difference = (Number) entry; + } else if (difference instanceof BigDecimal) { + difference = ((BigDecimal) difference).subtract(BigDecimal.valueOf(((Number) entry).doubleValue())); + } else if (entry instanceof BigDecimal) { + difference = BigDecimal.valueOf(difference.doubleValue()).subtract((BigDecimal) entry); + } else if (requiresDoubleResult(difference) || requiresDoubleResult(entry)) { + difference = difference.doubleValue() - ((Number) entry).doubleValue(); + } else { + difference = difference.longValue() - ((Number) entry).longValue(); + } + } else { + warnIgnoringValue("Subtract", entry); + } + } + + return difference; + } + + private static Number doMultiply(Number input, double rate) { + if (input instanceof BigDecimal) { + return ((BigDecimal) input).multiply(BigDecimal.valueOf(rate)); + } + return (input.doubleValue() * rate); + } + + private static boolean requiresDoubleResult(Object object) { + return object instanceof Double || object instanceof Float; + } + + /** + * @TODO Add audit via @AtlasSession instead - https://github.com/atlasmap/atlasmap/issues/1269 + * @param value value + */ + private static void warnIgnoringValue(String action, Object value) { + LOG.warn("The source collection/arry/map must only contain numbers for '{}' transformation - ignoring '{}'", + action, value != null ? value : "null"); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/ObjectFieldActions.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/ObjectFieldActions.java new file mode 100644 index 00000000..bcb19873 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/ObjectFieldActions.java @@ -0,0 +1,129 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import java.util.Collection; +import java.util.List; + +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.Contains; +import io.atlasmap.v2.Count; +import io.atlasmap.v2.Equals; +import io.atlasmap.v2.IsNull; +import io.atlasmap.v2.ItemAt; +import io.atlasmap.v2.Length; + +public class ObjectFieldActions implements AtlasFieldAction { + + @AtlasActionProcessor + public static Integer count(Count action, List inputs) { + if (inputs == null) { + return 0; + } + return inputs.size(); + } + + @AtlasActionProcessor + public static Boolean contains(Contains contains, List inputs) { + if (contains == null) { + throw new IllegalArgumentException("Contains action must be specified"); + } + if (inputs == null) { + return contains.getValue() == null; + } + return collectionContains(inputs, contains); + } + + @AtlasActionProcessor + public static Boolean equals(Equals equals, Object input) { + if (equals == null) { + throw new IllegalArgumentException("Equals action must be specified"); + } + if (input == null) { + return equals.getValue() == null; + } + + return input.toString().equals(equals.getValue()); + } + + @AtlasActionProcessor + public static Boolean isNull(IsNull action, Object input) { + return input == null; + } + + @AtlasActionProcessor + public static Object itemAt(ItemAt itemAt, List inputs) { + if (inputs == null) { + return null; + } + + Integer index = itemAt.getIndex() == null ? 0 : itemAt.getIndex(); + Object[] array = inputs.toArray(new Object[0]); + if (array.length > index) { + return array[index]; + } else { + throw new ArrayIndexOutOfBoundsException(String.format( + "Collection '%s' has fewer (%s) than expected (%s)", array, array.length, index)); + } + } + + @AtlasActionProcessor + public static Integer length(Length length, Object input) { + if (input == null) { + return -1; + } + return input.toString().length(); + } + + private static boolean collectionContains(Collection collection, Contains contains) { + for (Object item : collection) { + if (item == null) { + if (contains.getValue() == null) { + return true; + } + } else if (item.toString().equals(contains.getValue())) { + return true; + } + } + return false; + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/StringComplexFieldActions.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/StringComplexFieldActions.java new file mode 100644 index 00000000..28c0da14 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/StringComplexFieldActions.java @@ -0,0 +1,335 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import java.util.List; +import java.util.Locale; +import java.util.UUID; +import java.util.regex.Pattern; + +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.Append; +import io.atlasmap.v2.Concatenate; +import io.atlasmap.v2.EndsWith; +import io.atlasmap.v2.FieldType; +import io.atlasmap.v2.Format; +import io.atlasmap.v2.GenerateUUID; +import io.atlasmap.v2.IndexOf; +import io.atlasmap.v2.LastIndexOf; +import io.atlasmap.v2.PadStringLeft; +import io.atlasmap.v2.PadStringRight; +import io.atlasmap.v2.Prepend; +import io.atlasmap.v2.Repeat; +import io.atlasmap.v2.ReplaceAll; +import io.atlasmap.v2.ReplaceFirst; +import io.atlasmap.v2.Split; +import io.atlasmap.v2.StartsWith; +import io.atlasmap.v2.SubString; +import io.atlasmap.v2.SubStringAfter; +import io.atlasmap.v2.SubStringBefore; + +public class StringComplexFieldActions implements AtlasFieldAction { + + public static final String STRING_SEPARATOR_REGEX = "^\\s+:_+="; + public static final Pattern STRING_SEPARATOR_PATTERN = Pattern.compile(STRING_SEPARATOR_REGEX); + + @AtlasActionProcessor + public static String append(Append append, String input) { + if (append == null) { + throw new IllegalArgumentException("Append must be specified with a string"); + } + String string = append.getString(); + if (input == null && string == null) { + return null; + } + if (string == null) { + return input.toString(); + } + return input == null ? string : input.toString().concat(string); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY) + public static String concatenate(Concatenate concat, List inputs) { + if (concat == null) { + throw new IllegalArgumentException("Concatenate must be specified with a delimiter"); + } + if (inputs == null) { + return null; + } + + String delim = concat.getDelimiter() == null ? "" : concat.getDelimiter(); + boolean delimitingEmptyValues = concat.getDelimitingEmptyValues() == null + ? false + : concat.getDelimitingEmptyValues(); + boolean isFirst = true; + StringBuilder builder = new StringBuilder(); + for (String entry : inputs) { + if (!isFirst && ((entry != null && !entry.isEmpty()) || delimitingEmptyValues)) { + builder.append(delim); + } + if (entry != null) { + builder.append(entry); + } + isFirst = false; + } + + return builder.toString(); + } + + @AtlasActionProcessor + public static Boolean endsWith(EndsWith endsWith, String input) { + if (endsWith == null || endsWith.getString() == null) { + throw new IllegalArgumentException("EndsWith must be specified with a string"); + } + + return input == null ? false : input.endsWith(endsWith.getString()); + } + + @AtlasActionProcessor + public static String format(Format format, List input) { + if (format == null || format.getTemplate() == null) { + throw new IllegalArgumentException("Format must be specified with a template"); + } + + return String.format(Locale.ROOT, format.getTemplate(), input == null ? null : input.toArray(new Object[0])); + } + + @AtlasActionProcessor + public static String genareteUUID(GenerateUUID action) { + return UUID.randomUUID().toString(); + } + + @AtlasActionProcessor + public static Number indexOf(IndexOf indexOf, String input) { + if (indexOf == null || indexOf.getString() == null) { + throw new IllegalArgumentException("IndexOf must be specified with a string"); + } + + return input == null ? -1 : input.indexOf(indexOf.getString()); + } + + @AtlasActionProcessor + public static Number lastIndexOf(LastIndexOf lastIndexOf, String input) { + if (lastIndexOf == null || lastIndexOf.getString() == null) { + throw new IllegalArgumentException("LastIndexOf must be specified with a string"); + } + + return input == null ? -1 : input.lastIndexOf(lastIndexOf.getString()); + } + + @AtlasActionProcessor + public static String padStringRight(PadStringRight padStringRight, String input) { + if (padStringRight == null || padStringRight.getPadCharacter() == null + || padStringRight.getPadCount() == null) { + throw new IllegalArgumentException("PadStringRight must be specified with padCharacter and padCount"); + } + + StringBuilder builder = new StringBuilder(); + if (input != null) { + builder.append(input); + } + for (int i = 0; i < padStringRight.getPadCount(); i++) { + builder.append(padStringRight.getPadCharacter()); + } + + return builder.toString(); + } + + @AtlasActionProcessor + public static String padStringLeft(PadStringLeft padStringLeft, String input) { + if (padStringLeft == null || padStringLeft.getPadCharacter() == null + || padStringLeft.getPadCount() == null) { + throw new IllegalArgumentException("PadStringLeft must be specified with padCharacter and padCount"); + } + + StringBuilder builder = new StringBuilder(); + for (int i = 0; i < padStringLeft.getPadCount(); i++) { + builder.append(padStringLeft.getPadCharacter()); + } + if (input != null) { + builder.append(input); + } + + return builder.toString(); + } + + @AtlasActionProcessor + public static String prepend(Prepend action, String input) { + String string = action.getString(); + if (input == null) { + return string; + } + if (string == null) { + return input; + } + return string.concat(input); + } + + @AtlasActionProcessor + public static String replaceAll(ReplaceAll replaceAll, String input) { + if (replaceAll == null || replaceAll.getMatch() == null || replaceAll.getMatch().isEmpty()) { + throw new IllegalArgumentException("ReplaceAll action must be specified with a non-empty old string"); + } + String match = replaceAll.getMatch(); + String newString = replaceAll.getNewString(); + return input == null ? null : input.replaceAll(match, newString == null ? "" : newString); + } + + @AtlasActionProcessor + public static String replaceFirst(ReplaceFirst replaceFirst, String input) { + if (replaceFirst == null || replaceFirst.getMatch() == null || replaceFirst.getMatch().isEmpty()) { + throw new IllegalArgumentException("ReplaceFirst action must be specified with a non-empty old string"); + } + String match = replaceFirst.getMatch(); + String newString = replaceFirst.getNewString(); + return input == null ? null : input.replaceFirst(match, newString == null ? "" : newString); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY) + public static String[] split(Split split, String input) { + if (split == null || split.getDelimiter() == null) { + throw new IllegalArgumentException("Split must be specified with a delimiter"); + } + String quotedDelimiter = Pattern.quote(split.getDelimiter()); + boolean collapseRepeatingDelimiter = split.getCollapseRepeatingDelimiters() == null + ? false + : split.getCollapseRepeatingDelimiters(); + if (collapseRepeatingDelimiter) { + quotedDelimiter = "(" + quotedDelimiter + ")+"; + } + return input == null ? null : input.toString().split(quotedDelimiter); + } + + @AtlasActionProcessor(sourceType = FieldType.ANY) + public static String[] repeat(Repeat repeat, String input) { + + if (repeat == null) { + throw new IllegalArgumentException("repeat is not defined"); + } + + String[] returnObj = null; + + // Repeat the value based on count + int count = repeat.getCount(); + + returnObj = new String[count]; + for (int i = 0; i < count; i++) { + returnObj[i] = input; + } + + return returnObj; + } + + @AtlasActionProcessor + public static Boolean startsWith(StartsWith startsWith, String input) { + if (startsWith == null || startsWith.getString() == null) { + throw new IllegalArgumentException("StartsWith must be specified with a string"); + } + + return input == null ? false : input.startsWith(startsWith.getString()); + } + + @AtlasActionProcessor + public static String subString(SubString subString, String input) { + if (input == null || input.length() == 0) { + return input; + } + + if (subString == null || subString.getStartIndex() == null || subString.getStartIndex() < 0) { + throw new IllegalArgumentException("SubString action must be specified with a positive startIndex"); + } + + return doSubString(input, subString.getStartIndex(), subString.getEndIndex()); + } + + @AtlasActionProcessor + public static String subStringAfter(SubStringAfter subStringAfter, String input) { + if (input == null || input.length() == 0) { + return input; + } + + if (subStringAfter == null || subStringAfter.getStartIndex() == null + || subStringAfter.getStartIndex() < 0 || subStringAfter.getMatch() == null + || (subStringAfter.getEndIndex() != null + && subStringAfter.getEndIndex() < subStringAfter.getStartIndex())) { + throw new IllegalArgumentException( + "SubStringAfter action must be specified with a positive startIndex and a string to match"); + } + + int idx = input.indexOf(subStringAfter.getMatch()); + if (idx < 0) { + return input; + } + idx = idx + subStringAfter.getMatch().length(); + return doSubString(input.substring(idx), subStringAfter.getStartIndex(), subStringAfter.getEndIndex()); + } + + @AtlasActionProcessor + public static String subStringBefore(SubStringBefore subStringBefore, String input) { + if (input == null || input.length() == 0) { + return input; + } + + if (subStringBefore == null || subStringBefore.getStartIndex() == null + || subStringBefore.getStartIndex() < 0 || subStringBefore.getMatch() == null + || (subStringBefore.getEndIndex() != null + && subStringBefore.getEndIndex() < subStringBefore.getStartIndex())) { + throw new IllegalArgumentException( + "SubStringBefore action must be specified with a positive startIndex and a string to match"); + } + + int idx = input.indexOf(subStringBefore.getMatch()); + if (idx < 0) { + return input; + } + + return doSubString(input.substring(0, idx), subStringBefore.getStartIndex(), subStringBefore.getEndIndex()); + } + + private static String doSubString(String input, Integer startIndex, Integer endIndex) { + if (endIndex == null) { + return input.substring(startIndex); + } + + return input.substring(startIndex, endIndex); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/StringSimpleFieldActions.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/StringSimpleFieldActions.java new file mode 100644 index 00000000..7d8be83c --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/actions/StringSimpleFieldActions.java @@ -0,0 +1,188 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.actions; + +import java.util.regex.Pattern; + +import io.atlasmap.spi.AtlasActionProcessor; +import io.atlasmap.spi.AtlasFieldAction; +import io.atlasmap.v2.Capitalize; +import io.atlasmap.v2.FileExtension; +import io.atlasmap.v2.Lowercase; +import io.atlasmap.v2.LowercaseChar; +import io.atlasmap.v2.Normalize; +import io.atlasmap.v2.RemoveFileExtension; +import io.atlasmap.v2.SeparateByDash; +import io.atlasmap.v2.SeparateByUnderscore; +import io.atlasmap.v2.Trim; +import io.atlasmap.v2.TrimLeft; +import io.atlasmap.v2.TrimRight; +import io.atlasmap.v2.Uppercase; +import io.atlasmap.v2.UppercaseChar; + +public class StringSimpleFieldActions implements AtlasFieldAction { + + public static final String STRING_SEPARATOR_REGEX = "[\\s+\\:\\_\\+\\=\\-]+"; + public static final Pattern STRING_SEPARATOR_PATTERN = Pattern.compile(STRING_SEPARATOR_REGEX); + + @AtlasActionProcessor + public static String capitalize(Capitalize action, String input) { + if (input == null || input.length() == 0) { + return input; + } + if (input.length() == 1) { + return String.valueOf(input.charAt(0)).toUpperCase(); + } + return String.valueOf(input.charAt(0)).toUpperCase() + input.substring(1); + } + + @AtlasActionProcessor + public static String fileExtension(FileExtension action, String input) { + if (input == null) { + return null; + } + + int ndx = input.lastIndexOf('.'); + return ndx < 0 ? null : input.substring(ndx + 1); + } + + @AtlasActionProcessor + public static String lowercase(Lowercase action, String input) { + if (input == null) { + return null; + } + + return input.toLowerCase(); + } + + @AtlasActionProcessor + public static Character lowercaseChar(LowercaseChar action, Character input) { + if (input == null) { + return null; + } + + return String.valueOf(input).toLowerCase().charAt(0); + } + + @AtlasActionProcessor + public static String normalize(Normalize action, String input) { + return input == null ? null : input.replaceAll("\\s+", " ").trim(); + } + + @AtlasActionProcessor + public static String removeFileExtension(RemoveFileExtension action, String input) { + if (input == null) { + return null; + } + + int ndx = input.lastIndexOf('.'); + return ndx < 0 ? input : input.substring(0, ndx); + } + + @AtlasActionProcessor + public static String separateByDash(SeparateByDash action, String input) { + if (input == null || input.length() == 0) { + return input; + } + return STRING_SEPARATOR_PATTERN.matcher(input).replaceAll("-"); + } + + @AtlasActionProcessor + public static String separateByUnderscore(SeparateByUnderscore action, String input) { + if (input == null || input.length() == 0) { + return input; + } + return STRING_SEPARATOR_PATTERN.matcher(input).replaceAll("_"); + } + + @AtlasActionProcessor + public static String trim(Trim action, String input) { + if (input == null || input.length() == 0) { + return input; + } + + return input.trim(); + } + + @AtlasActionProcessor + public static String trimLeft(TrimLeft action, String input) { + if (input == null || input.length() == 0) { + return input; + } + + int i = 0; + while (i < input.length() && Character.isWhitespace(input.charAt(i))) { + i++; + } + return input.substring(i); + } + + @AtlasActionProcessor + public static String trimRight(TrimRight action, String input) { + if (input == null || input.length() == 0) { + return input; + } + + int i = input.length() - 1; + while (i >= 0 && Character.isWhitespace(input.charAt(i))) { + i--; + } + return input.substring(0, i + 1); + } + + @AtlasActionProcessor + public static String uppercase(Uppercase action, String input) { + if (input == null) { + return null; + } + + return input.toUpperCase(); + } + + @AtlasActionProcessor + public static Character uppercaseChar(UppercaseChar action, Character input) { + if (input == null) { + return null; + } + + return String.valueOf(input).toUpperCase().charAt(0); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConstants.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConstants.java new file mode 100644 index 00000000..556e5beb --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConstants.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +public class AtlasConstants { + public static final String DEFAULT_SOURCE_DOCUMENT_ID = "ATLAS_DEFAULT_SOURCE_DOC"; + public static final String DEFAULT_TARGET_DOCUMENT_ID = "ATLAS_DEFAULT_TARGET_DOC"; + public static final String CONSTANTS_DOCUMENT_ID = "ATLAS_CONSTANTS_DOC"; + public static final String PROPERTIES_SOURCE_DOCUMENT_ID = "ATLAS_SOURCE_PROPERTIES_DOC"; + public static final String PROPERTIES_TARGET_DOCUMENT_ID = "ATLAS_TARGET_PROPERTIES_DOC"; + + private AtlasConstants() { + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasContext.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasContext.java new file mode 100644 index 00000000..1a13e743 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasContext.java @@ -0,0 +1,70 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +import io.atlasmap.v2.Audits; +import io.atlasmap.v2.Mapping; + +public interface AtlasContext { + + AtlasContextFactory getContextFactory(); + + AtlasSession createSession() throws AtlasException; + + /* + * https://github.com/atlasmap/atlasmap/issues/872 + * Consider moving following 3 methods into AtlasSession in V2 + */ + + void process(AtlasSession session) throws AtlasException; + + void processValidation(AtlasSession session) throws AtlasException; + + /** + * @deprecated Use {@code AtlasPreviewContext#processPreview(Mapping)} + * + * @param mapping A mapping item to process preview + * @return A list of audit log + */ + @Deprecated + Audits processPreview(Mapping mapping) throws AtlasException; + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasContextFactory.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasContextFactory.java new file mode 100644 index 00000000..13722150 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasContextFactory.java @@ -0,0 +1,97 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +import java.io.File; +import java.io.InputStream; +import java.net.URI; +import java.util.Map; +import java.util.Properties; + +import io.atlasmap.spi.AtlasCombineStrategy; +import io.atlasmap.spi.AtlasConversionService; +import io.atlasmap.spi.AtlasFieldActionService; +import io.atlasmap.spi.AtlasPropertyStrategy; +import io.atlasmap.spi.AtlasSeparateStrategy; + +public interface AtlasContextFactory { + + static final String PROPERTY_ATLASMAP_CORE_VERSION = "atlasmap.core.version"; + + enum Format { ADM, JSON }; + + void init(); + + void destroy(); + + AtlasContext createContext(File atlasMappingFile) throws AtlasException; + + AtlasContext createContext(URI atlasMappingUri) throws AtlasException; + + AtlasContext createContext(Format format, InputStream atlasMappingStream) throws AtlasException; + + AtlasPreviewContext createPreviewContext() throws AtlasException; + + @Deprecated + AtlasCombineStrategy getCombineStrategy() throws AtlasException; + + AtlasConversionService getConversionService() throws AtlasException; + + AtlasFieldActionService getFieldActionService() throws AtlasException; + + AtlasPropertyStrategy getPropertyStrategy() throws AtlasException; + + void setPropertyStrategy(AtlasPropertyStrategy strategy) throws AtlasException; + + @Deprecated + AtlasSeparateStrategy getSeparateStrategy() throws AtlasException; + + AtlasValidationService getValidationService() throws AtlasException; + + void setProperties(Map properties); + + void setProperties(Properties properties); + + Map getProperties(); + + void addClassLoader(ClassLoader cl); + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConversionException.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConversionException.java new file mode 100644 index 00000000..3ea9cd0f --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConversionException.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +public class AtlasConversionException extends AtlasException { + + private static final long serialVersionUID = -8909275615751481096L; + + public AtlasConversionException() { + super(); + } + + public AtlasConversionException(String message, Throwable cause) { + super(message, cause); + } + + public AtlasConversionException(String message) { + super(message); + } + + public AtlasConversionException(Throwable cause) { + super(cause); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConverter.java new file mode 100644 index 00000000..2db73b5a --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasConverter.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +/** + * @deprecated Use {@link io.atlasmap.spi.AtlasConverter} + * @param Java type to convert from + */ +@Deprecated +public interface AtlasConverter extends io.atlasmap.spi.AtlasConverter { + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasException.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasException.java new file mode 100644 index 00000000..adf1bb2b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasException.java @@ -0,0 +1,61 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +public class AtlasException extends Exception { + private static final long serialVersionUID = 7547364931796852076L; + + public AtlasException() { + super(); + } + + public AtlasException(String message, Throwable cause) { + super(message, cause); + } + + public AtlasException(String message) { + super(message); + } + + public AtlasException(Throwable cause) { + super(cause); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasFieldAction.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasFieldAction.java new file mode 100644 index 00000000..2d075804 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasFieldAction.java @@ -0,0 +1,49 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +/** + * @deprecated Use {@link io.atlasmap.spi.AtlasFieldAction} + */ +@Deprecated +public interface AtlasFieldAction extends io.atlasmap.spi.AtlasFieldAction { + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasMappingBuilder.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasMappingBuilder.java new file mode 100644 index 00000000..35f2343b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasMappingBuilder.java @@ -0,0 +1,63 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +/** + * An interface to define a custom mapping logic. User can implement this class and + * define custom mapping logic in {@code #processMapping()}. + * + */ +public interface AtlasMappingBuilder { + + /** + * Define custom mapping logic. User can implement this interface and define + * custom mapping logic in this method. + */ + void process(); + + /** + * Set {@code AtlasSession}. + * @param session {@code AtlasSession} + * @throws AtlasException + */ + void setAtlasSession(AtlasSession session) throws AtlasException; + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasNotFoundException.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasNotFoundException.java new file mode 100644 index 00000000..35a82d22 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasNotFoundException.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +public class AtlasNotFoundException extends AtlasException { + + private static final long serialVersionUID = -780179923312820477L; + + public AtlasNotFoundException() { + super(); + } + + public AtlasNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + public AtlasNotFoundException(String message) { + super(message); + } + + public AtlasNotFoundException(Throwable cause) { + super(cause); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasPreviewContext.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasPreviewContext.java new file mode 100644 index 00000000..a2a63965 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasPreviewContext.java @@ -0,0 +1,50 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +import io.atlasmap.v2.Audits; +import io.atlasmap.v2.Mapping; + +public interface AtlasPreviewContext { + + Audits processPreview(Mapping mapping) throws AtlasException; + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasSession.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasSession.java new file mode 100644 index 00000000..12f1754e --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasSession.java @@ -0,0 +1,108 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +import java.util.Map; + +import io.atlasmap.spi.AtlasPropertyStrategy; +import io.atlasmap.v2.AtlasMapping; +import io.atlasmap.v2.Audits; +import io.atlasmap.v2.Validations; + +public interface AtlasSession { + + @Deprecated + Map getProperties(); + + Map getSourceProperties(); + + Map getTargetProperties(); + + AtlasPropertyStrategy getAtlasPropertyStrategy(); + + void setAtlasPropertyStrategy(AtlasPropertyStrategy strategy); + + AtlasContext getAtlasContext(); + + void setAtlasContext(AtlasContext atlasContext); + + AtlasMapping getMapping(); + + Object getDefaultSourceDocument(); + + void setDefaultSourceDocument(Object sourceDoc); + + Object getSourceDocument(String docId); + + void setSourceDocument(String docId, Object sourceDoc); + + boolean hasSourceDocument(String docId); + + Map getSourceDocumentMap(); + + Object getDefaultTargetDocument(); + + void setDefaultTargetDocument(Object targetDoc); + + Object getTargetDocument(String docId); + + void setTargetDocument(String docId, Object targetDoc); + + boolean hasTargetDocument(String docId); + + Map getTargetDocumentMap(); + + Validations getValidations(); + + void setValidations(Validations validations); + + Audits getAudits(); + + void setAudits(Audits audits); + + boolean hasErrors(); + + boolean hasWarns(); + + Integer errorCount(); + + Integer warnCount(); +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasUnsupportedException.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasUnsupportedException.java new file mode 100644 index 00000000..aba66f34 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasUnsupportedException.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +public class AtlasUnsupportedException extends AtlasException { + + private static final long serialVersionUID = 4276166328541103662L; + + public AtlasUnsupportedException() { + super(); + } + + public AtlasUnsupportedException(String message, Throwable cause) { + super(message, cause); + } + + public AtlasUnsupportedException(String message) { + super(message); + } + + public AtlasUnsupportedException(Throwable cause) { + super(cause); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasValidationException.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasValidationException.java new file mode 100644 index 00000000..2ba250ea --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasValidationException.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +public class AtlasValidationException extends AtlasException { + + private static final long serialVersionUID = 6537018220259702613L; + + public AtlasValidationException() { + super(); + } + + public AtlasValidationException(String message, Throwable cause) { + super(message, cause); + } + + public AtlasValidationException(String message) { + super(message); + } + + public AtlasValidationException(Throwable cause) { + super(cause); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasValidationService.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasValidationService.java new file mode 100644 index 00000000..b3fd4ea1 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/api/AtlasValidationService.java @@ -0,0 +1,52 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.api; + +import java.util.List; + +import io.atlasmap.v2.AtlasMapping; +import io.atlasmap.v2.Validation; + +public interface AtlasValidationService { + + List validateMapping(AtlasMapping mapping); + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/builder/AtlasField.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/builder/AtlasField.java new file mode 100644 index 00000000..4276381d --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/builder/AtlasField.java @@ -0,0 +1,169 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.builder; + +import java.util.List; + +import io.atlasmap.api.AtlasException; +import io.atlasmap.core.ConstantModule; +import io.atlasmap.core.DefaultAtlasConversionService; +import io.atlasmap.core.DefaultAtlasFieldActionService; +import io.atlasmap.core.DefaultAtlasSession; +import io.atlasmap.core.PropertyModule; +import io.atlasmap.spi.ActionProcessor; +import io.atlasmap.spi.AtlasModule; +import io.atlasmap.spi.AtlasModuleMode; +import io.atlasmap.v2.Constant; +import io.atlasmap.v2.Field; +import io.atlasmap.v2.PropertyField; + +/** + * A part of custom mapping builder API to implement custom mapping logic in Java code. + * This class wraps raw {@link Field} and provide some utility methods to introspect + * underlying field tree. {@link DefaultAtlasMappingBuilder#read(String, String)} + * reads from source document and creates AtlasField. + * @see DefaultAtlasMappingBuilder + */ +public class AtlasField { + + private DefaultAtlasSession session; + private DefaultAtlasConversionService conversionService; + private DefaultAtlasFieldActionService fieldActionService; + private Field rawField; + + public AtlasField(DefaultAtlasSession session) { + this.session = session; + this.conversionService = session.getAtlasContext().getContextFactory().getConversionService(); + this.fieldActionService = session.getAtlasContext().getContextFactory().getFieldActionService(); + } + + public AtlasField read(String docId, String path) throws AtlasException { + AtlasModule module = session.resolveModule(docId); + if (module == null) { + throw new AtlasException(String.format("Source document '%s' doesn't exist", docId)); + } + if (module.getMode() != AtlasModuleMode.SOURCE) { + throw new AtlasException(String.format( + "Unable to read from %s Document '%s'", module.getMode(), docId)); + } + Field sourceField = module.createField(); + sourceField.setDocId(docId); + sourceField.setPath(path); + session.head().setSourceField(sourceField); + module.readSourceValue(session); + setRawField(sourceField); + return this; + } + + public AtlasField readConstant(String name) throws AtlasException { + ConstantModule module = session.getConstantModule(); + List constants = session.getMapping().getConstants().getConstant(); + for (Constant constant : constants) { + if (constant.getName() != null && constant.getName().equals(name)) { + Field sourceField = module.createField(); + sourceField.setName(constant.getName()); + sourceField.setFieldType(constant.getFieldType()); + sourceField.setValue(constant.getValue()); + session.head().setSourceField(sourceField); + module.readSourceValue(session); + setRawField(sourceField); + return this; + } + } + throw new AtlasException(String.format("Constant '%s' not found", name)); + } + + public AtlasField readProperty(String scope, String name) throws AtlasException { + PropertyModule module = session.getSourcePropertyModule(); + PropertyField sourceField = module.createField(); + sourceField.setScope(scope); + sourceField.setName(name); + session.head().setSourceField(sourceField); + module.readSourceValue(session); + setRawField(sourceField); + return this; + } + + public void write(String docId, String path) throws AtlasException { + AtlasModule module = session.resolveModule(docId); + if (module == null) { + throw new AtlasException(String.format("Target document '%s' doesn't exist", docId)); + } + if (module.getMode() != AtlasModuleMode.TARGET) { + throw new AtlasException(String.format( + "Unable to write to %s Document '%s'", module.getMode(), docId)); + } + Field f = module.createField(); + f.setDocId(docId); + f.setPath(path); + session.head().setSourceField(getRawField()); + session.head().setTargetField(f); + module.populateTargetField(session); + module.writeTargetValue(session); + } + + public void writeProperty(String scope, String name) throws AtlasException { + PropertyModule module = session.getTargetPropertyModule(); + PropertyField f = module.createField(); + f.setScope(scope); + f.setName(name); + session.head().setSourceField(getRawField()); + session.head().setTargetField(f); + module.populateTargetField(session); + module.writeTargetValue(session); + } + + public AtlasField action(String actionName, List parameters) { + Object value = parameters != null && parameters.size() > 1 ? parameters.get(parameters.size()-1) : null; + ActionProcessor ap = this.fieldActionService.findActionProcessor(actionName, value); + + return this; + } + + public Field getRawField() { + return this.rawField; + } + + public AtlasField setRawField(Field f) { + this.rawField = f; + return this; + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/builder/DefaultAtlasMappingBuilder.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/builder/DefaultAtlasMappingBuilder.java new file mode 100644 index 00000000..adbc3f6a --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/builder/DefaultAtlasMappingBuilder.java @@ -0,0 +1,134 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.builder; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.atlasmap.api.AtlasException; +import io.atlasmap.api.AtlasMappingBuilder; +import io.atlasmap.api.AtlasSession; +import io.atlasmap.core.AtlasUtil; +import io.atlasmap.core.DefaultAtlasSession; +import io.atlasmap.spi.AtlasConversionService; +import io.atlasmap.spi.AtlasFieldActionService; +import io.atlasmap.v2.AuditStatus; +import io.atlasmap.v2.SimpleField; + +/** + * A base {@code AtlasMappingBuilder} with some common utility methods. + * In most cases user can extend this class and just implement {@link #processMapping()}. + * @see AtlasField + */ +public abstract class DefaultAtlasMappingBuilder implements AtlasMappingBuilder { + + private static final Logger LOG = LoggerFactory.getLogger(DefaultAtlasMappingBuilder.class); + private DefaultAtlasSession session; + private AtlasConversionService conversionService; + private AtlasFieldActionService fieldActionService; + + public AtlasField read(String docId, String path) throws AtlasException { + return new AtlasField(session).read(docId, path); + } + + public AtlasField readConstant(String name) throws AtlasException { + return new AtlasField(session).readConstant(name); + } + + public AtlasField readProperty(String scope, String name) throws AtlasException { + return new AtlasField(session).readProperty(scope, name); + } + + public void write(String docId, String path, Object value) throws AtlasException { + SimpleField source = new SimpleField(); + if (value != null) { + source.setValue(value); + source.setFieldType(this.conversionService.fieldTypeFromClass(value.getClass())); + } + new AtlasField(session).setRawField(source).write(docId, path); + } + + @Override + public void process() { + try { + processMapping(); + } catch (Exception e) { + addAudit(e); + } + } + + /** + * Define custom mapping logic. User can extend this class and implement + * custom mapping logic in this method. The thrown Exception will be catched + * in {@link #process()} and added as an Audit. + * @throws Exception Indicate mapping error to be recorded as an Audit + */ + public abstract void processMapping() throws Exception; + + @Override + public void setAtlasSession(AtlasSession session) throws AtlasException { + if (!(session instanceof DefaultAtlasSession)) { + throw new IllegalArgumentException(String.format( + "This version of MappingBuilder doesn't support %s", + session.getClass().getName())); + } + this.session = (DefaultAtlasSession) session; + this.conversionService = session.getAtlasContext().getContextFactory().getConversionService(); + this.fieldActionService = session.getAtlasContext().getContextFactory().getFieldActionService(); + }; + + /** + * Get {@code DefaultAtlasSession}. + * @return {@code AtlasSession}. + */ + public AtlasSession getAtlasSession() { + return this.session; + }; + + public void addAudit(Exception e) { + AtlasUtil.addAudit(this.session, this.getClass().getName(), + e.getMessage(), AuditStatus.ERROR, null); + if (LOG.isDebugEnabled()) { + LOG.error("", e); + } + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BigDecimalConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BigDecimalConverter.java new file mode 100644 index 00000000..3945545b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BigDecimalConverter.java @@ -0,0 +1,287 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class BigDecimalConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(BigDecimal value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(BigDecimal value) { + return value != null ? value.toBigInteger() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.BOOLEAN) + public Boolean toBoolean(BigDecimal value) { + if (value == null) { + return null; + } + return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.BYTE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Byte toByte(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.toBigInteger().byteValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.CHAR, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Character toCharacter(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + Character.valueOf((char) value.intValueExact()); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.DATE_TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Date toDate(BigDecimal date) throws AtlasConversionException { + if (date == null) { + return null; + } + try { + long dateLong = date.toBigInteger().longValueExact(); + if (dateLong >= Instant.MIN.getEpochSecond()) { + return Date.from(Instant.ofEpochMilli(dateLong)); + } + return new Date(dateLong); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", date)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.DOUBLE, + concerns = {AtlasConversionConcern.RANGE}) + public Double toDouble(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + Double answer = value.doubleValue(); + if (answer == Double.NEGATIVE_INFINITY || answer == Double.POSITIVE_INFINITY) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Double.MAX_VALUE or less than Double.MIN_VALUE", value)); + } + return answer; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.FLOAT, + concerns = AtlasConversionConcern.RANGE) + public Float toFloat(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + Float answer = value.floatValue(); + if (answer == Float.NEGATIVE_INFINITY || answer == Float.POSITIVE_INFINITY) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Float.MAX_VALUE or less than Float.MIN_VALUE", value)); + } + return answer; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.INTEGER, + concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.intValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.DATE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalDate toLocalDate(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.toBigInteger().longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalTime toLocalTime(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.toBigInteger().longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalTime(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.DATE_TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalDateTime toLocalDateTime(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.toBigInteger().longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDateTime(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.LONG, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Long toLong(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.toBigInteger().longValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.NUMBER) + public Number toNumber(BigDecimal value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.SHORT, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Short toShort(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.toBigInteger().shortValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException( + String.format("BigDecimal %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.STRING) + public String toString(BigDecimal value) { + return value != null ? value.toString() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(BigDecimal value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.STRING) + public CharSequence toCharSequence(BigDecimal value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(BigDecimal value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(BigDecimal value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DECIMAL, targetType = FieldType.DATE_TIME_TZ, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public ZonedDateTime toZonedDateTime(BigDecimal value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigDecimal %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BigIntegerConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BigIntegerConverter.java new file mode 100644 index 00000000..f25aec52 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BigIntegerConverter.java @@ -0,0 +1,287 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class BigIntegerConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(BigInteger value) { + return value != null ? new BigDecimal(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(BigInteger value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.BOOLEAN) + public Boolean toBoolean(BigInteger value) { + if (value == null) { + return null; + } + return value.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.BYTE, + concerns = AtlasConversionConcern.RANGE) + public Byte toByte(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.byteValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.CHAR, + concerns = AtlasConversionConcern.RANGE) + public Character toCharacter(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + Character.valueOf((char) value.intValueExact()); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.DATE_TIME, + concerns = AtlasConversionConcern.RANGE) + public Date toDate(BigInteger date) throws AtlasConversionException { + if (date == null) { + return null; + } + try { + long dateLong = date.longValueExact(); + if (dateLong >= Instant.MIN.getEpochSecond()) { + return Date.from(Instant.ofEpochMilli(dateLong)); + } + return new Date(dateLong); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", date)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.DOUBLE, + concerns = AtlasConversionConcern.RANGE) + public Double toDouble(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + Double answer = value.doubleValue(); + if (answer == Double.NEGATIVE_INFINITY || answer == Double.POSITIVE_INFINITY) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Double.MAX_VALUE or less than Double.MIN_VALUE", value)); + } + return answer; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.FLOAT, + concerns = AtlasConversionConcern.RANGE) + public Float toFloat(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + Float answer = value.floatValue(); + if (answer == Float.NEGATIVE_INFINITY || answer == Float.POSITIVE_INFINITY) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Float.MAX_VALUE or less than Float.MIN_VALUE", value)); + } + return answer; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.INTEGER, + concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.intValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.DATE, + concerns = AtlasConversionConcern.RANGE) + public LocalDate toLocalDate(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDate(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.TIME, + concerns = AtlasConversionConcern.RANGE) + public LocalTime toLocalTime(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalTime(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.DATE_TIME, + concerns = AtlasConversionConcern.RANGE) + public LocalDateTime toLocalDateTime(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()).toLocalDateTime(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.LONG, + concerns = AtlasConversionConcern.RANGE) + public Long toLong(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.longValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.NUMBER) + public Number toNumber(BigInteger value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.SHORT, + concerns = AtlasConversionConcern.RANGE) + public Short toShort(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return value.shortValueExact(); + } catch (ArithmeticException e) { + throw new AtlasConversionException( + String.format("BigInteger %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.STRING) + public String toString(BigInteger value) { + return value != null ? value.toString() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(BigInteger value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.STRING) + public CharSequence toCharSequence(BigInteger value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(BigInteger value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(BigInteger value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BIG_INTEGER, targetType = FieldType.DATE_TIME_TZ, + concerns = AtlasConversionConcern.RANGE) + public ZonedDateTime toZonedDateTime(BigInteger value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + long longValue = value.longValueExact(); + return Instant.ofEpochMilli(longValue).atZone(ZoneId.systemDefault()); + } catch (ArithmeticException e) { + throw new AtlasConversionException(String.format( + "BigInteger %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BooleanConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BooleanConverter.java new file mode 100644 index 00000000..241c388e --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/BooleanConverter.java @@ -0,0 +1,151 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; + +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class BooleanConverter implements AtlasConverter { + + private static final String STRING_VALUES = "true|false"; + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Boolean value) { + return value != null ? BigDecimal.valueOf(value ? 1 : 0) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Boolean value) { + return value != null ? BigInteger.valueOf(value ? 1 : 0) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.BOOLEAN) + public Boolean toBoolean(Boolean value, String sourceFormat, String targetFormat) { + return value != null ? Boolean.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.BYTE) + public Byte toByte(Boolean value) { + return value != null ? (byte) (value ? 1 : 0) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.CHAR) + public Character toCharacter(Boolean value) { + return value != null ? (char) (value ? 1 : 0) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.DOUBLE) + public Double toDouble(Boolean value) { + return value != null ? value ? 1.0d : 0.0d : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.FLOAT) + public Float toFloat(Boolean value) { + return value != null ? (value ? 1.0f : 0.0f) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.INTEGER) + public Integer toInteger(Boolean value) { + return value != null ? (value ? 1 : 0) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.LONG) + public Long toLong(Boolean value) { + return value != null ? (value ? 1L : 0L) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.NUMBER) + public Number toNumber(Boolean value) { + return toShort(value); + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.SHORT) + public Short toShort(Boolean value) { + return value != null ? (short) (value ? 1 : 0) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.STRING, concerns = { + AtlasConversionConcern.CONVENTION }) + public String toString(Boolean value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + // TODO optimize/save defaults + String format = targetFormat != null && !"".equals(targetFormat) ? targetFormat : STRING_VALUES; + String[] values = format.split("\\|"); + String trueValue = ""; + String falseValue = ""; + if (values.length == 2) { + trueValue = values[0]; + falseValue = values[1]; + } else if (values.length == 1) { + trueValue = values[0]; + } + return String.valueOf((value ? trueValue : falseValue)); + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Boolean value, String sourceFormat, String targetFormat) { + return value != null ? CharBuffer.wrap(toString(value, sourceFormat, targetFormat)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.STRING) + public CharSequence toCharSequence(Boolean value, String sourceFormat, String targetFormat) { + return value != null ? toString(value, sourceFormat, targetFormat) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Boolean value, String sourceFormat, String targetFormat) { + return value != null ? new StringBuffer(toString(value, sourceFormat, targetFormat)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BOOLEAN, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Boolean value, String sourceFormat, String targetFormat) { + return value != null ? new StringBuilder(toString(value, sourceFormat, targetFormat)) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/ByteConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/ByteConverter.java new file mode 100644 index 00000000..5797b79d --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/ByteConverter.java @@ -0,0 +1,177 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class ByteConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Byte value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Byte value) { + return value != null ? BigInteger.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.BOOLEAN, + concerns = {AtlasConversionConcern.CONVENTION}) + public Boolean toBoolean(Byte value) { + if (value == null) { + return null; + } + return value.byteValue() != 0; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.BYTE) + public Byte toByte(Byte value) { + return value != null ? new Byte(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.CHAR) + public Character toCharacter(Byte value) { + return value != null ? (char) value.byteValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.DATE_TIME) + public Date toDate(Byte value) { + if (value == null) { + return null; + } + if (value >= Instant.MIN.getEpochSecond()) { + return Date.from(Instant.ofEpochMilli(value)); + } + return new Date(value); + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.DOUBLE) + public Double toDouble(Byte value) { + return value != null ? (double) value : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.FLOAT) + public Float toFloat(Byte value) { + return value != null ? (float) value : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.INTEGER) + public Integer toInteger(Byte value) { + return value != null ? (int) value : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.DATE) + public LocalDate toLocalDate(Byte value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDate() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.TIME) + public LocalTime toLocalTime(Byte value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(Byte value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDateTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.LONG) + public Long toLong(Byte value) { + return value != null ? (long) value : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.NUMBER) + public Number toNumber(Byte value) { + return toShort(value); + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.SHORT) + public Short toShort(Byte value) { + return value != null ? (short) value : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.STRING, + concerns = {AtlasConversionConcern.CONVENTION}) + public String toString(Byte value) { + return value != null ? String.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Byte value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.STRING) + public CharSequence toCharSequence(Byte value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Byte value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Byte value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.BYTE, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Byte value) { + return Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CalendarConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CalendarConverter.java new file mode 100644 index 00000000..2e73f719 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CalendarConverter.java @@ -0,0 +1,62 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; + +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class CalendarConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME) + public Date toDate(Calendar calendar) { + return calendar != null ? calendar.getTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Calendar calendar) { + return calendar == null ? null : DateTimeHelper.toZonedDateTime(calendar); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharBufferConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharBufferConverter.java new file mode 100644 index 00000000..4710e138 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharBufferConverter.java @@ -0,0 +1,176 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class CharBufferConverter implements AtlasConverter { + + private CharSequenceConverter delegate = new CharSequenceConverter(); + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DECIMAL, + concerns = AtlasConversionConcern.FORMAT) + public BigDecimal toBigDecimal(CharBuffer value) throws AtlasConversionException { + return delegate.toBigDecimal(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.BIG_INTEGER, + concerns = AtlasConversionConcern.FORMAT) + public BigInteger toBigInteger(CharBuffer value) throws AtlasConversionException { + return delegate.toBigInteger(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.BOOLEAN, concerns = AtlasConversionConcern.CONVENTION) + public Boolean toBoolean(CharBuffer value, String sourceFormat, String targetFormat) { + return delegate.toBoolean(value, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.BYTE, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.FORMAT, AtlasConversionConcern.FRACTIONAL_PART}) + public Byte toByte(CharBuffer value) throws AtlasConversionException { + return delegate.toByte(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.CHAR, concerns = AtlasConversionConcern.RANGE) + public Character toCharacter(CharBuffer value) throws AtlasConversionException { + return delegate.toCharacter(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE_TIME) + public Date toDate(CharBuffer date, String sourceFormat, String targetFormat) { + return delegate.toDate(date, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DOUBLE, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE }) + public Double toDouble(CharBuffer value) throws AtlasConversionException { + return delegate.toDouble(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.FLOAT, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE }) + public Float toFloat(CharBuffer value) throws AtlasConversionException { + return delegate.toFloat(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.INTEGER, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART }) + public Integer toInteger(CharBuffer value) throws AtlasConversionException { + return delegate.toInteger(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE) + public LocalDate toLocalDate(CharBuffer value) { + return delegate.toLocalDate(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.TIME) + public LocalTime toLocalTime(CharBuffer value) { + return delegate.toLocalTime(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(CharBuffer value) { + return delegate.toLocalDateTime(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.LONG, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART }) + public Long toLong(CharBuffer value) throws AtlasConversionException { + return delegate.toLong(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.SHORT, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART }) + public Short toShort(CharBuffer value) throws AtlasConversionException { + return delegate.toShort(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(CharBuffer value, String sourceFormat, String targetFormat) { + return delegate.toCharBuffer(value, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public CharSequence toCharSequence(CharBuffer value, String sourceFormat, String targetFormat) { + return delegate.toCharSequence(value, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public String toString(CharBuffer value, String sourceFormat, String targetFormat) { + return delegate.toString(value, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(CharBuffer value, String sourceFormat, String targetFormat) { + return delegate.toStringBuffer(value, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(CharBuffer value, String sourceFormat, String targetFormat) { + return delegate.toStringBuilder(value, sourceFormat, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.NUMBER, concerns = { + AtlasConversionConcern.FORMAT }) + public Number toNumber(CharBuffer value) throws AtlasConversionException { + return delegate.toNumber(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(CharBuffer value) { + return delegate.toZonedDateTime(value); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharSequenceConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharSequenceConverter.java new file mode 100644 index 00000000..8264eb83 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharSequenceConverter.java @@ -0,0 +1,387 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.text.NumberFormat; +import java.text.ParseException; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.regex.Pattern; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class CharSequenceConverter implements AtlasConverter { + + private static final Pattern TRUE_PATTERN = Pattern.compile("true|t|yes|y", Pattern.CASE_INSENSITIVE); + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DECIMAL, + concerns = AtlasConversionConcern.FORMAT) + public BigDecimal toBigDecimal(CharSequence value) throws AtlasConversionException { + try { + return value != null ? new BigDecimal(value.toString()) : null; + } catch (NumberFormatException e) { + throw new AtlasConversionException(String + .format("String %s cannont be converted to a BigDecimal as it is not in a valid format", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.BIG_INTEGER, + concerns = AtlasConversionConcern.FORMAT) + public BigInteger toBigInteger(CharSequence value) throws AtlasConversionException { + try { + return value != null ? new BigInteger(value.toString()) : null; + } catch (NumberFormatException e) { + throw new AtlasConversionException(String + .format("String %s cannont be converted to a BigInteger as it is not in a valid format", value)); + } + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.BOOLEAN, concerns = AtlasConversionConcern.CONVENTION) + public Boolean toBoolean(CharSequence value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + + // string expression of true? + Pattern pattern; + if (sourceFormat != null && !sourceFormat.isEmpty()) { + pattern = Pattern.compile(sourceFormat, Pattern.CASE_INSENSITIVE); + } else { + pattern = TRUE_PATTERN; + } + if (pattern.matcher(value).matches()) { + return Boolean.TRUE; + } + + // then try C like numeric translation + try { + Number n = NumberFormat.getInstance().parse(value.toString()); + if (n.intValue() == 0) { + return Boolean.FALSE; + } + return Boolean.TRUE; + } catch (ParseException e) { + e.getMessage(); // ignore + } + + // false by default + return Boolean.FALSE; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.BYTE, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.FORMAT, AtlasConversionConcern.FRACTIONAL_PART}) + public Byte toByte(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + try { + return Byte.parseByte(value.toString()); + } catch (NumberFormatException nfex) { + try { + BigDecimal bd = new BigDecimal(value.toString()); + if (bd.compareTo(new BigDecimal(Byte.MIN_VALUE)) < 0 + || bd.compareTo(new BigDecimal(Byte.MAX_VALUE)) > 0) { + throw new AtlasConversionException(String + .format("String %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + return bd.byteValue(); + } catch (NumberFormatException nfe2) { + throw new AtlasConversionException(String + .format("String %s cannont be converted to a Byte as it is not in a numerical format", value)); + } + } + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.CHAR, concerns = AtlasConversionConcern.RANGE) + public Character toCharacter(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + // empty or greater than 1 char String throws Exception + if (value.toString().isEmpty() || value.length() > 1) { + throw new AtlasConversionException( + String.format("String '%s' is either empty or greater than one character long", value)); + } else if (value.charAt(0) < Character.MIN_VALUE || value.charAt(0) > Character.MAX_VALUE) { + throw new AtlasConversionException(String + .format("String %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + return value.charAt(0); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE_TIME) + public Date toDate(CharSequence date, String sourceFormat, String targetFormat) { + + DateTimeFormatter formater = sourceFormat != null ? DateTimeFormatter.ofPattern(sourceFormat) + : DateTimeFormatter.ISO_ZONED_DATE_TIME; + return Date.from(ZonedDateTime.parse(date, formater).toInstant()); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DOUBLE, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE }) + public Double toDouble(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + + String str = value.toString(); + double parsedDouble = 0.0d; + try { + parsedDouble = Double.parseDouble(str); + } catch (NumberFormatException nfe) { + throw new AtlasConversionException(nfe); + } + + double absParsedDouble = Math.abs(parsedDouble); + if (absParsedDouble == 0.0d) { + return parsedDouble; + } + if (absParsedDouble < Double.MIN_VALUE || absParsedDouble > Double.MAX_VALUE) { + throw new AtlasConversionException( + String.format( + "String %s is greater than Double.MAX_VALUE or less than Double.MIN_VALUE", + str)); + } + + return parsedDouble; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.FLOAT, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE }) + public Float toFloat(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + + String str = value.toString(); + float parsedFloat = 0.0f; + try { + parsedFloat = Float.parseFloat(str); + } catch (NumberFormatException nfe) { + throw new AtlasConversionException(nfe); + } + + float absParsedFloat = Math.abs(parsedFloat); + if (absParsedFloat == 0.0f) { + return parsedFloat; + } + + if (absParsedFloat < Float.MIN_VALUE || absParsedFloat > Float.MAX_VALUE) { + throw new AtlasConversionException( + String.format( + "String %s is greater than Float.MAX_VALUE or less than Float.MIN_VALUE", + str)); + } + + return Float.valueOf(str); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.INTEGER, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART }) + public Integer toInteger(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + + String str = value.toString(); + Integer i = null; + try { + i = Integer.parseInt(str); + } catch (NumberFormatException nfe) { + try { + BigDecimal bd = new BigDecimal(str); + if (bd.compareTo(new BigDecimal(Integer.MIN_VALUE)) < 0 + || bd.compareTo(new BigDecimal(Integer.MAX_VALUE)) > 0) { + throw new AtlasConversionException(String + .format("String %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", str)); + } + i = bd.intValue(); + } catch (NumberFormatException nfe2) { + throw new AtlasConversionException(nfe); + } + } + + return i; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE) + public LocalDate toLocalDate(CharSequence value) { + return value != null ? LocalDate.parse(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.TIME) + public LocalTime toLocalTime(CharSequence value) { + return value != null ? LocalTime.parse(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(CharSequence value) { + return value != null ? LocalDateTime.parse(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.LONG, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART }) + public Long toLong(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + + String str = value.toString(); + Long l = null; + try { + l = Long.parseLong(str); + } catch (NumberFormatException nfe) { + try { + BigDecimal bd = new BigDecimal(str); + if (bd.compareTo(new BigDecimal(Long.MIN_VALUE)) < 0 + || bd.compareTo(new BigDecimal(Long.MAX_VALUE)) > 0) { + throw new AtlasConversionException(String + .format("String %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + l = bd.longValue(); + } catch (NumberFormatException nfe2) { + throw new AtlasConversionException(nfe); + } + } + + return l; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.SHORT, concerns = { + AtlasConversionConcern.FORMAT, AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART }) + public Short toShort(CharSequence value) throws AtlasConversionException { + if (value == null) { + return null; + } + + String str = value.toString(); + Short shortty = null; + try { + shortty = Short.parseShort(str); + } catch (NumberFormatException nfe) { + try { + BigDecimal bd = new BigDecimal(str); + if (bd.compareTo(new BigDecimal(Short.MIN_VALUE)) < 0 + || bd.compareTo(new BigDecimal(Short.MAX_VALUE)) > 0) { + throw new AtlasConversionException(String + .format("String %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", str)); + } + shortty = bd.shortValue(); + } catch (NumberFormatException nfe2) { + throw new AtlasConversionException(nfe2); + } + } + return shortty; + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(CharSequence value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + return CharBuffer.wrap(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public CharSequence toCharSequence(CharSequence value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + return new String(value.toString()); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public String toString(CharSequence value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + return new String(value.toString()); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(CharSequence value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + return new StringBuffer(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(CharSequence value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + return new StringBuilder(value); + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.NUMBER, concerns = { + AtlasConversionConcern.FORMAT }) + public Number toNumber(CharSequence value) throws AtlasConversionException { + if (value == null || value.toString().trim().isEmpty()) { + return null; + } + String str = value.toString(); + if (str.matches("\\d+")) { + return new BigInteger(str); + } + try { + return new BigDecimal(str); + } catch (NumberFormatException e) { + throw new AtlasConversionException(e); + } + } + + @AtlasConversionInfo(sourceType = FieldType.STRING, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(CharSequence value) { + return value != null ? ZonedDateTime.parse(value) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharacterConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharacterConverter.java new file mode 100644 index 00000000..0c118628 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/CharacterConverter.java @@ -0,0 +1,184 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class CharacterConverter implements AtlasConverter { + + private static final String TRUE_REGEX = "t|T|y|Y|[1-9]"; + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Character value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Character value) { + return value != null ? BigInteger.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.BOOLEAN, concerns = { + AtlasConversionConcern.CONVENTION }) + public Boolean toBoolean(Character value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + + String regex = sourceFormat != null && !"".equals(sourceFormat) ? sourceFormat : TRUE_REGEX; + if (Character.toString(value).matches(regex)) { + return Boolean.TRUE; + } + return Boolean.FALSE; + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.BYTE, concerns = { + AtlasConversionConcern.RANGE }) + public Byte toByte(Character value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value.charValue() > Byte.MAX_VALUE) { + throw new AtlasConversionException( + String.format("Character value %s is greater than BYTE.MAX_VALUE", value)); + } + return (byte) value.charValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.CHAR) + public Character toCharacter(Character value) { + if (value == null) { + return null; + } + // we want new Character from the value + return new Character(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.DOUBLE) + public Double toDouble(Character value) { + if (value == null) { + return null; + } + return Double.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.FLOAT) + public Float toFloat(Character value) { + if (value == null) { + return null; + } + return Float.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.INTEGER) + public Integer toInteger(Character value) { + if (value == null) { + return null; + } + return Integer.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.LONG) + public Long toLong(Character value) { + if (value == null) { + return null; + } + return Long.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.NUMBER) + public Number toNumber(Character value) { + if (value == null) { + return null; + } + return Integer.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.SHORT, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.CONVENTION }) + public Short toShort(Character value) throws AtlasConversionException { + if (value == null) { + return null; + } + // only care if the char is larger than the short MAX + if (value > Short.MAX_VALUE) { + throw new AtlasConversionException(); + } + return (short) value.charValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.STRING) + public String toString(Character value, String sourceFormat, String targetFormat) { + if (value == null) { + return null; + } + return String.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Character value, String sourceFormat, String targetFormat) { + return value != null ? CharBuffer.wrap(toString(value, sourceFormat, targetFormat)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.STRING) + public CharSequence toCharSequence(Character value, String sourceFormat, String targetFormat) { + return value != null ? toString(value, sourceFormat, targetFormat) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Character value, String sourceFormat, String targetFormat) { + return value != null ? new StringBuffer(toString(value, sourceFormat, targetFormat)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.CHAR, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Character value, String sourceFormat, String targetFormat) { + return value != null ? new StringBuilder(toString(value, sourceFormat, targetFormat)) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DateConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DateConverter.java new file mode 100644 index 00000000..cc726c57 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DateConverter.java @@ -0,0 +1,209 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.sql.Time; +import java.sql.Timestamp; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class DateConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Date date) { + return BigDecimal.valueOf(date.getTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Date date) { + return BigInteger.valueOf(date.getTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.BYTE, + concerns = AtlasConversionConcern.RANGE) + public Byte toByte(Date value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = value.getTime(); + if (longValue < Byte.MIN_VALUE || longValue > Byte.MAX_VALUE) { + throw new AtlasConversionException( + String.format("LocalDateTime %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + return longValue.byteValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ) + public Calendar toCalendar(Date date) { + Calendar calendar = Calendar.getInstance(); + calendar.setTimeInMillis(date.getTime()); + return calendar; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DOUBLE) + public Double toDouble(Date value) { + return value != null ? Double.valueOf(value.getTime()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.FLOAT) + public Float toFloat(Date value) { + return value != null ? Float.valueOf(value.getTime()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.INTEGER, + concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(Date value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = value.getTime(); + if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) { + throw new AtlasConversionException(String + .format("Date %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + return longValue.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ) + public GregorianCalendar toGregorianCalendar(Date date, String sourceFormat, String targetFormat) { + return DateTimeHelper.convertDateToGregorianCalendar(date, sourceFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE) + public LocalDate toLocalDate(Date date, String sourceFormat, String targetFormat) { + return DateTimeHelper.convertDateToLocalDate(date, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(Date date, String sourceFormat, String targetFormat) { + return DateTimeHelper.convertDateToLocalDateTime(date, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.TIME) + public LocalTime toLocalTime(Date date, String sourceFormat, String targetFormat) { + return DateTimeHelper.convertDateToLocalTime(date, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.LONG) + public Long toLong(Date date) { + return date.toInstant().toEpochMilli(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.NUMBER) + public Number toNumber(Date date) { + return date.toInstant().toEpochMilli(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.SHORT, + concerns = AtlasConversionConcern.RANGE) + public Short toShort(Date value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = value.getTime(); + if (longValue > Short.MAX_VALUE || longValue < Short.MIN_VALUE) { + throw new AtlasConversionException(String + .format("Date %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + return longValue.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE) + public java.sql.Date toSqlDate(Date date, String sourceFormat, String targetFormat) { + return DateTimeHelper.convertDateToSqlDate(date, sourceFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.TIME) + public Time toSqlTime(Date date, String sourceFormat, String targetFormat) { + return DateTimeHelper.convertDateToTime(date, targetFormat); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public String toString(Date date) { + // by default Instant.toString returns an ISO-8601 representation of the instant + return date.toInstant().toString(); + + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Date value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public CharSequence toCharSequence(Date value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Date value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Date value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME) + public Timestamp toSqlTimestamp(Date date) { + return Timestamp.from(date.toInstant()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Date date) { + return DateTimeHelper.toZonedDateTime(date, null); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DateTimeHelper.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DateTimeHelper.java new file mode 100644 index 00000000..e8a6089f --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DateTimeHelper.java @@ -0,0 +1,118 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.sql.Time; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +public class DateTimeHelper { + + public static GregorianCalendar convertDateToGregorianCalendar(Date date, String timeZone) { + return GregorianCalendar.from(DateTimeHelper.toZonedDateTime(date, timeZone)); + } + + public static Date convertSqlDateToDate(java.sql.Date date, String timeZone) { + return Date.from(date.toLocalDate().atStartOfDay(zoneId(timeZone)).toInstant()); + } + + public static java.sql.Date convertDateToSqlDate(Date date, String timeZone) { + return java.sql.Date.valueOf(DateTimeHelper.convertDateToLocalDate(date, timeZone)); + } + + public static Date convertSqlTimeToDate(Time time, String timeZone) { + return DateTimeHelper.convertLocalTimeToDate(time.toLocalTime(), timeZone); // ? + } + + public static LocalDate convertDateToLocalDate(Date date, String timeZone) { + return LocalDateTime.ofInstant(date.toInstant(), zoneId(timeZone)).toLocalDate(); + } + + public static Date convertLocalTimeToDate(LocalTime localTime, String timeZone) { + return Date.from(localTime.atDate(LocalDate.now()).atZone(zoneId(timeZone)).toInstant()); + } + + public static LocalTime convertDateToLocalTime(Date date, String timeZone) { + return LocalDateTime.ofInstant(date.toInstant(), zoneId(timeZone)).toLocalTime(); + } + + public static Date convertLocalDateTimeToDate(LocalDateTime localDateTime, String timeZone) { + return Date.from(localDateTime.atZone(zoneId(timeZone)).toInstant()); + } + + public static LocalDateTime convertDateToLocalDateTime(Date date, String timeZone) { + return LocalDateTime.ofInstant(date.toInstant(), zoneId(timeZone)); + } + + public static Time convertDateToTime(Date date, String timeZone) { + return Time.valueOf(LocalDateTime.ofInstant(date.toInstant(), zoneId(timeZone)).toLocalTime()); + } + + public static ZonedDateTime toZonedDateTime(Calendar calendar) { + return ZonedDateTime.ofInstant(calendar.toInstant(), calendar.getTimeZone().toZoneId()); + } + + public static ZonedDateTime toZonedDateTime(Date date, String timeZone) { + return ZonedDateTime.ofInstant(date.toInstant(), zoneId(timeZone)); + } + + public static ZonedDateTime toZonedDateTime(LocalDate date, String timeZone) { + return date.atStartOfDay(zoneId(timeZone)); + } + + public static ZonedDateTime toZonedDateTime(LocalTime time, String timeZone) { + return toZonedDateTime(time.atDate(LocalDate.now()), timeZone); + } + + public static ZonedDateTime toZonedDateTime(LocalDateTime date, String timeZone) { + return date.atZone(zoneId(timeZone)); + } + + private static ZoneId zoneId(String timeZone) { + return timeZone != null ? ZoneId.of(timeZone) : ZoneId.systemDefault(); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DoubleConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DoubleConverter.java new file mode 100644 index 00000000..4576d21b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/DoubleConverter.java @@ -0,0 +1,262 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.api.AtlasUnsupportedException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class DoubleConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Double value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.BIG_INTEGER, + concerns = AtlasConversionConcern.FRACTIONAL_PART) + public BigInteger toBigInteger(Double value) { + return value != null ? BigDecimal.valueOf(value).toBigInteger() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.BOOLEAN, concerns = { + AtlasConversionConcern.CONVENTION }) + public Boolean toBoolean(Double value) { + if (value == null) { + return null; + } + return value == 0.0 ? Boolean.FALSE : Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.BYTE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Byte toByte(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value % 1 == 0 && value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + return value.byteValue(); + } + throw new AtlasConversionException(new AtlasUnsupportedException(String.format( + "Double %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE or is not a whole number", + value))); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.CHAR, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Character toCharacter(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + + if (value < Character.MIN_VALUE || value > Character.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Double %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.DATE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Date toDate(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Double %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return new Date(value.longValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.DOUBLE) + public Double toDouble(Double value) { + return value != null ? Double.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.FLOAT, + concerns = AtlasConversionConcern.RANGE) + public Float toFloat(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + double absValue = Math.abs(value); + if (absValue > Float.MAX_VALUE || (absValue < Float.MIN_VALUE && value != 0)) { + throw new AtlasConversionException( + String.format("Double %s is greater than Float.MAX_VALUE or less than Float.MIN_VALUE", value)); + } + return value.floatValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.INTEGER, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Integer toInteger(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Double %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + return value.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.DATE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalDate toLocalDate(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Double %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()).toLocalDate(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalTime toLocalTime(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Double %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()).toLocalTime(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.DATE_TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalDateTime toLocalDateTime(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Double %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()).toLocalDateTime(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.LONG, concerns = AtlasConversionConcern.RANGE) + public Long toLong(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Double %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return value.longValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.NUMBER) + public Number toNumber(Double value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.SHORT, concerns = AtlasConversionConcern.RANGE) + public Short toShort(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("Double %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + return value.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.STRING) + public String toString(Double value) { + return value != null ? String.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Double value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.STRING) + public CharSequence toCharSequence(Double value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Double value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Double value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DOUBLE, targetType = FieldType.DATE_TIME_TZ, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public ZonedDateTime toZonedDateTime(Double value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Long.MAX_VALUE || value < Long.MIN_VALUE) { + throw new AtlasConversionException(String.format( + "Double %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/FloatConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/FloatConverter.java new file mode 100644 index 00000000..d8dd6ac3 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/FloatConverter.java @@ -0,0 +1,264 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.api.AtlasUnsupportedException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class FloatConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Float value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.BIG_INTEGER, + concerns = AtlasConversionConcern.FRACTIONAL_PART) + public BigInteger toBigInteger(Float value) { + return value != null ? BigDecimal.valueOf(value).toBigInteger() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.BOOLEAN, concerns = { + AtlasConversionConcern.CONVENTION }) + public Boolean toBoolean(Float value) { + if (value == null) { + return null; + } + if (value == 0.0) { + return Boolean.FALSE; + } + return Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.BYTE, concerns = { + AtlasConversionConcern.RANGE }) + public Byte toByte(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value % 1 == 0 && value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + return value.byteValue(); + } + throw new AtlasConversionException(new AtlasUnsupportedException(String.format( + "Float %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE or is not a whole number", + value))); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.CHAR, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.CONVENTION }) + public Character toCharacter(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + + if (value < Character.MIN_VALUE || value > Character.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Float %s is greater than Character.MAX_VALUE or is less than Character.MIN_VALUE", value)); + } + + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.DATE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public Date toDate(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Float %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return new Date(value.longValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.DOUBLE) + public Double toDouble(Float value) { + if (value == null) { + return null; + } + return value.doubleValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.FLOAT) + public Float toFloat(Float value) { + if (value == null) { + return null; + } + // we want a copy of value + return value.floatValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.INTEGER, concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Float %s is greater than Integer.MAX_VALUE or is less than Integer.MIN_VALUE", value)); + } + return value.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.DATE, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalDate toLocalDate(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Float %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()).toLocalDate(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalTime toLocalTime(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Float %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()).toLocalTime(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.DATE_TIME, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public LocalDateTime toLocalDateTime(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Long.MIN_VALUE || value > Long.MAX_VALUE) { + throw new AtlasConversionException(String.format( + "Float %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()).toLocalDateTime(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.LONG, + concerns = AtlasConversionConcern.RANGE) + public Long toLong(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Long.MAX_VALUE || value < Long.MIN_VALUE) { + throw new AtlasConversionException( + String.format("Float %s is greater than Long.MAX_VALUE or is less than Long.MIN_VALUE", value)); + } + return value.longValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.NUMBER) + public Number toNumber(Float value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.SHORT, concerns = AtlasConversionConcern.RANGE) + public Short toShort(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("Float %s is greater than Short.MAX_VALUE or is less than Short.MIN_VALUE", value)); + } + return value.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.STRING) + public String toString(Float value) { + return value != null ? String.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Float value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.STRING) + public CharSequence toCharSequence(Float value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Float value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Float value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.FLOAT, targetType = FieldType.DATE_TIME_TZ, + concerns = {AtlasConversionConcern.RANGE, AtlasConversionConcern.FRACTIONAL_PART}) + public ZonedDateTime toZonedDateTime(Float value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Long.MAX_VALUE || value < Long.MIN_VALUE) { + throw new AtlasConversionException(String.format( + "Float %s is greater than Long.MAX_VALUE or less than Long.MIN_VALUE", value)); + } + return Instant.ofEpochMilli(value.longValue()).atZone(ZoneId.systemDefault()); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/GregorianCalendarConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/GregorianCalendarConverter.java new file mode 100644 index 00000000..80b464c2 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/GregorianCalendarConverter.java @@ -0,0 +1,104 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class GregorianCalendarConverter implements AtlasConverter { + + private ZonedDateTimeConverter zdtConverter = new ZonedDateTimeConverter(); + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME_TZ) + public Calendar toCalendar(GregorianCalendar calendar) { + return calendar; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME) + public Date toDate(GregorianCalendar calendar) { + return zdtConverter.toDate(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE) + public LocalDate toLocalDate(GregorianCalendar calendar) { + return zdtConverter.toLocalDate(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(GregorianCalendar calendar) { + return zdtConverter.toLocalDateTime(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.TIME) + public LocalTime toLocalTime(GregorianCalendar calendar) { + return zdtConverter.toLocalTime(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE) + public java.sql.Date toSqlDate(GregorianCalendar calendar) { + return zdtConverter.toSqlDate(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.TIME) + public java.sql.Time toSqlTime(GregorianCalendar calendar) { + return zdtConverter.toSqlTime(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME) + public java.sql.Timestamp toSqlTimestamp(GregorianCalendar calendar) { + return zdtConverter.toSqlTimestamp(calendar.toZonedDateTime()); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME_TZ, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZoneDateTime(GregorianCalendar calendar) { + return calendar.toZonedDateTime(); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/IntegerConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/IntegerConverter.java new file mode 100644 index 00000000..4c32bffd --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/IntegerConverter.java @@ -0,0 +1,197 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.api.AtlasUnsupportedException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class IntegerConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Integer value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Integer value) { + return value != null ? BigInteger.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.BOOLEAN, concerns = { + AtlasConversionConcern.CONVENTION }) + public Boolean toBoolean(Integer value) { + if (value == null) { + return null; + } + return value == 0 ? Boolean.FALSE : Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.BYTE, concerns = AtlasConversionConcern.RANGE) + public Byte toByte(Integer value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + return value.byteValue(); + } + throw new AtlasConversionException(new AtlasUnsupportedException( + String.format("Integer %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value))); + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.CHAR, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.CONVENTION }) + public Character toCharacter(Integer value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value < Character.MIN_VALUE || value > Character.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Integer %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.DATE_TIME) + public Date toDate(Integer value) { + if (value >= Instant.MIN.getEpochSecond()) { + return Date.from(Instant.ofEpochMilli(value)); + } + return new Date(value); + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.DOUBLE) + public Double toDouble(Integer value) { + return value != null ? value.doubleValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.FLOAT, concerns = AtlasConversionConcern.RANGE) + public Float toFloat(Integer value) { + return value != null ? value.floatValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.INTEGER) + public Integer toInteger(Integer value) { + return value != null ? Integer.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.DATE) + public LocalDate toLocalDate(Integer value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDate() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.TIME) + public LocalTime toLocalTime(Integer value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(Integer value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDateTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.LONG) + public Long toLong(Integer value) { + return value != null ? value.longValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.SHORT, concerns = AtlasConversionConcern.RANGE) + public Short toShort(Integer value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("Integer %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + return value.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.STRING) + public String toString(Integer value) { + return value != null ? String.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Integer value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.STRING) + public CharSequence toCharSequence(Integer value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Integer value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Integer value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.NUMBER) + public Number toNumber(Integer value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.INTEGER, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Integer value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalDateConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalDateConverter.java new file mode 100644 index 00000000..b79f246a --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalDateConverter.java @@ -0,0 +1,208 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class LocalDateConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(LocalDate value) { + return value != null ? BigDecimal.valueOf(getStartEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(LocalDate value) { + return value != null ? BigInteger.valueOf(getStartEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.BYTE, + concerns = AtlasConversionConcern.RANGE) + public Byte toByte(LocalDate value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getStartEpochMilli(value); + if (longValue >= Byte.MIN_VALUE && longValue <= Byte.MAX_VALUE) { + return longValue.byteValue(); + } + throw new AtlasConversionException( + String.format("LocalDate %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME_TZ) + public Calendar toCalendar(LocalDate value) { + return value != null ? GregorianCalendar.from(value.atStartOfDay(ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME) + public Date toDate(LocalDate value) { + return value != null ? new Date(getStartEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DOUBLE) + public Double toDouble(LocalDate value) { + return value != null ? getStartEpochMilli(value).doubleValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.FLOAT) + public Float toFloat(LocalDate value) { + return value != null ? getStartEpochMilli(value).floatValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME_TZ) + public GregorianCalendar toGregorianCalendar(LocalDate value) { + return value != null ? GregorianCalendar.from(value.atStartOfDay(ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.INTEGER, + concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(LocalDate value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getStartEpochMilli(value); + if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) { + throw new AtlasConversionException(String + .format("LocalDate %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + return longValue.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE) + public LocalDate toLocalDate(LocalDate value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(LocalDate value) { + return value != null ? value.atStartOfDay() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.TIME) + public LocalTime toLocalTime(LocalDate value) { + return value != null ? value.atStartOfDay().toLocalTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.LONG) + public Long toLong(LocalDate value) { + return value != null ? getStartEpochMilli(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.SHORT, + concerns = AtlasConversionConcern.RANGE) + public Short toShort(LocalDate value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getStartEpochMilli(value); + if (longValue > Short.MAX_VALUE || longValue < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("LocalDate %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + return longValue.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.STRING) + public String toString(LocalDate value) { + return value != null ? value.toString() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(LocalDate value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.STRING) + public CharSequence toCharSequence(LocalDate value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(LocalDate value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(LocalDate value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.NUMBER) + public Number toNumber(LocalDate value) { + return value != null ? getStartEpochMilli(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE) + public java.sql.Date toSqlDate(LocalDate value) { + return java.sql.Date.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME) + public java.sql.Timestamp toSqlTimestamp(LocalDate value) { + return value != null ? java.sql.Timestamp.valueOf(value.atStartOfDay()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(LocalDate value) { + return value != null ? value.atStartOfDay(ZoneId.systemDefault()) : null; + } + + private Long getStartEpochMilli(LocalDate value) { + return value != null ? value.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli() : null; + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalDateTimeConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalDateTimeConverter.java new file mode 100644 index 00000000..614cf38b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalDateTimeConverter.java @@ -0,0 +1,217 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class LocalDateTimeConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(LocalDateTime value) { + return value != null ? BigDecimal.valueOf(getEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(LocalDateTime value) { + return value != null ? BigInteger.valueOf(getEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.BYTE, + concerns = AtlasConversionConcern.RANGE) + public Byte toByte(LocalDateTime value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getEpochMilli(value); + if (longValue >= Byte.MIN_VALUE && longValue <= Byte.MAX_VALUE) { + return longValue.byteValue(); + } + throw new AtlasConversionException( + String.format("LocalDateTime %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ) + public Calendar toCalendar(LocalDateTime value) { + return value != null ? GregorianCalendar.from(value.atZone(ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME) + public Date toDate(LocalDateTime value) { + return value != null ? new Date(getEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DOUBLE) + public Double toDouble(LocalDateTime value) { + return value != null ? getEpochMilli(value).doubleValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.FLOAT) + public Float toFloat(LocalDateTime value) { + return value != null ? getEpochMilli(value).floatValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ) + public GregorianCalendar toGregorianCalendar(LocalDateTime value) { + return value != null ? GregorianCalendar.from(value.atZone(ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.INTEGER, + concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(LocalDateTime value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getEpochMilli(value); + if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) { + throw new AtlasConversionException(String + .format("LocalDateTime %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + return longValue.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE) + public LocalDate toLocalDate(LocalDateTime value) { + return value != null ? value.toLocalDate() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(LocalDateTime value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.TIME) + public LocalTime toLocalTime(LocalDateTime value) { + return value != null ? value.toLocalTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.LONG) + public Long toLong(LocalDateTime value) { + return value != null ? getEpochMilli(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.SHORT, + concerns = AtlasConversionConcern.RANGE) + public Short toShort(LocalDateTime value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getEpochMilli(value); + if (longValue > Short.MAX_VALUE || longValue < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("LocalDateTime %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + return longValue.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public String toString(LocalDateTime value) { + if (value == null) { + return null; + } + return value.toString(); + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(LocalDateTime value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public CharSequence toCharSequence(LocalDateTime value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(LocalDateTime value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(LocalDateTime value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.NUMBER) + public Number toNumber(LocalDateTime value) { + return value != null ? getEpochMilli(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE) + public java.sql.Date toSqlDate(LocalDateTime value) { + return value != null ? java.sql.Date.valueOf(value.toLocalDate()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.TIME) + public java.sql.Time toSqlTime(LocalDateTime value) { + return value != null ? java.sql.Time.valueOf(value.toLocalTime()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME) + public java.sql.Timestamp toSqlTimestamp(LocalDateTime value) { + return value != null ? java.sql.Timestamp.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(LocalDateTime value) { + return value != null ? value.atZone(ZoneId.systemDefault()) : null; + } + + private Long getEpochMilli(LocalDateTime value) { + return value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalTimeConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalTimeConverter.java new file mode 100644 index 00000000..c99dc56b --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LocalTimeConverter.java @@ -0,0 +1,209 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class LocalTimeConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(LocalTime value) { + return value != null ? BigDecimal.valueOf(getTodaysEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(LocalTime value) { + return value != null ? BigInteger.valueOf(getTodaysEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.BYTE, + concerns = AtlasConversionConcern.RANGE) + public Byte toByte(LocalTime value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getTodaysEpochMilli(value); + if (longValue >= Byte.MIN_VALUE && longValue <= Byte.MAX_VALUE) { + return longValue.byteValue(); + } + throw new AtlasConversionException( + String.format("LocalTime %s of today is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value)); + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME_TZ) + public Calendar toCalendar(LocalTime value) { + return value != null ? GregorianCalendar.from(value.atDate(LocalDate.now()).atZone(ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME) + public Date toDate(LocalTime value) { + return value != null ? new Date(getTodaysEpochMilli(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DOUBLE) + public Double toDouble(LocalTime value) { + return value != null ? getTodaysEpochMilli(value).doubleValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.FLOAT) + public Float toFloat(LocalTime value) { + return value != null ? getTodaysEpochMilli(value).floatValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME_TZ) + public GregorianCalendar toGregorianCalendar(LocalTime value) { + return value != null ? GregorianCalendar.from(value.atDate(LocalDate.now()).atZone(ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.INTEGER, + concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(LocalTime value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getTodaysEpochMilli(value); + if (longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE) { + throw new AtlasConversionException(String + .format("LocalTime nano-of-day %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", longValue)); + } + return longValue.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(LocalTime value) { + return value != null ? value.atDate(LocalDate.now()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.TIME) + public LocalTime toLocalTime(LocalTime value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.LONG) + public Long toLong(LocalTime value) { + return value != null ? getTodaysEpochMilli(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.SHORT, + concerns = AtlasConversionConcern.RANGE) + public Short toShort(LocalTime value) throws AtlasConversionException { + if (value == null) { + return null; + } + Long longValue = getTodaysEpochMilli(value); + if (longValue > Short.MAX_VALUE || longValue < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("LocalTime nano-of-day %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", longValue)); + } + return longValue.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.STRING) + public String toString(LocalTime value) { + if (value == null) { + return null; + } + return value.toString(); + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(LocalTime value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.STRING) + public CharSequence toCharSequence(LocalTime value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(LocalTime value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(LocalTime value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.NUMBER) + public Number toNumber(LocalTime value) { + if (value == null) { + return null; + } + return getTodaysEpochMilli(value); + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.TIME) + public java.sql.Time toSqlTime(LocalTime value) { + return java.sql.Time.valueOf(value); + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME) + public java.sql.Timestamp toSqlTimestamp(LocalTime value) { + return value != null ? java.sql.Timestamp.valueOf(value.atDate(LocalDate.now())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(LocalTime value) { + return value != null ? value.atDate(LocalDate.now()).atZone(ZoneId.systemDefault()) : null; + } + + private Long getTodaysEpochMilli(LocalTime value) { + return value.atDate(LocalDate.now()).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LongConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LongConverter.java new file mode 100644 index 00000000..946705d5 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/LongConverter.java @@ -0,0 +1,213 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.api.AtlasUnsupportedException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class LongConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Long value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Long value) { + return value != null ? BigInteger.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.BOOLEAN, + concerns = AtlasConversionConcern.CONVENTION) + public Boolean toBoolean(Long value) { + if (value == null) { + return null; + } + return value == 0L ? Boolean.FALSE : Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.BYTE, + concerns = AtlasConversionConcern.RANGE) + public Byte toByte(Long value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + return value.byteValue(); + } + throw new AtlasConversionException(new AtlasUnsupportedException( + String.format("Long %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value))); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.CHAR, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.CONVENTION }) + public Character toCharacter(Long value) throws AtlasConversionException { + if (value == null) { + return null; + } + + if (value < Character.MIN_VALUE || value > Character.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Long %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.DATE_TIME_TZ) + public Date toDate(Long date) { + if (date >= Instant.MIN.getEpochSecond()) { + return Date.from(Instant.ofEpochMilli(date)); + } + return new Date(date); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.DOUBLE) + public Double toDouble(Long value) { + if (value == null) { + return null; + } + return value.doubleValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.FLOAT) + public Float toFloat(Long value) { + if (value == null) { + return null; + } + return value.floatValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.INTEGER, concerns = AtlasConversionConcern.RANGE) + public Integer toInteger(Long value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Integer.MAX_VALUE || value < Integer.MIN_VALUE) { + throw new AtlasConversionException( + String.format("Long %s is greater than Integer.MAX_VALUE or less than Integer.MIN_VALUE", value)); + } + return value.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.DATE) + public LocalDate toLocalDate(Long value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDate() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.TIME) + public LocalTime toLocalTime(Long value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(Long value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDateTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.LONG) + public Long toLong(Long value) { + return value != null ? new Long(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.SHORT, concerns = AtlasConversionConcern.RANGE) + public Short toShort(Long value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value > Short.MAX_VALUE || value < Short.MIN_VALUE) { + throw new AtlasConversionException( + String.format("Long %s is greater than Short.MAX_VALUE or less than Short.MIN_VALUE", value)); + } + return value.shortValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.NUMBER) + public Number toNumber(Long value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.STRING) + public String toString(Long value) { + return value != null ? String.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Long value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.STRING) + public CharSequence toCharSequence(Long value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Long value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Long value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.LONG, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Long value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/NumberConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/NumberConverter.java new file mode 100644 index 00000000..8d6fe25e --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/NumberConverter.java @@ -0,0 +1,239 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.lang.reflect.Method; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class NumberConverter implements AtlasConverter { + private BigDecimalConverter bigDecimalConverter = new BigDecimalConverter(); + private BigIntegerConverter bigIntegerConverter = new BigIntegerConverter(); + private ByteConverter byteConverter = new ByteConverter(); + private DoubleConverter doubleConverter = new DoubleConverter(); + private FloatConverter floatConverter = new FloatConverter(); + private IntegerConverter integerConverter = new IntegerConverter(); + private LongConverter longConverter = new LongConverter(); + private ShortConverter shortConverter = new ShortConverter(); + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Number value) throws AtlasConversionException { + return invoke(value, BigDecimal.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Number value) throws AtlasConversionException { + return invoke(value, BigInteger.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.BOOLEAN) + public Boolean toBoolean(Number value) throws AtlasConversionException { + return invoke(value, Boolean.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.BYTE) + public Byte toByte(Number value) throws AtlasConversionException { + return invoke(value, Byte.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.CHAR) + public Character toCharacter(Number value) throws AtlasConversionException { + return invoke(value, Character.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.DATE_TIME) + public Date toDate(Number value) throws AtlasConversionException { + return invoke(value, Date.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.DOUBLE) + public Double toDouble(Number value) throws AtlasConversionException { + return invoke(value, Double.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.FLOAT) + public Float toFloat(Number value) throws AtlasConversionException { + return invoke(value, Float.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.INTEGER) + public Integer toInteger(Number value) throws AtlasConversionException { + return invoke(value, Integer.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.DATE) + public LocalDate toLocalDate(Number value) throws AtlasConversionException { + return invoke(value, LocalDate.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.TIME) + public LocalTime toLocalTime(Number value) throws AtlasConversionException { + return invoke(value, LocalTime.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(Number value) throws AtlasConversionException { + return invoke(value, LocalDateTime.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.LONG) + public Long toLong(Number value) throws AtlasConversionException { + return invoke(value, Long.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.NUMBER) + public Number toNumber(Number value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.SHORT) + public Short toShort(Number value) throws AtlasConversionException { + return invoke(value, Short.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.STRING) + public String toString(Number value) throws AtlasConversionException { + return invoke(value, String.class); + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Number value) throws AtlasConversionException { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.STRING) + public CharSequence toCharSequence(Number value) throws AtlasConversionException { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Number value) throws AtlasConversionException { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Number value) throws AtlasConversionException { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.NUMBER, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Number value) throws AtlasConversionException { + return invoke(value, ZonedDateTime.class); + } + + private T invoke(Number object, Class returnType) throws AtlasConversionException { + if (object == null) { + return null; + } + if (returnType.isInstance(object)) { + return returnType.cast(object); + } + + try { + if (object instanceof BigDecimal) { + Method m = bigDecimalConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(bigDecimalConverter, object)); + + } else if (object instanceof BigInteger) { + Method m = bigIntegerConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(bigIntegerConverter, object)); + + } else if (object instanceof Byte) { + Method m = byteConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(byteConverter, object)); + + } else if (object instanceof Double) { + Method m = doubleConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(doubleConverter, object)); + + } else if (object instanceof Float) { + Method m = floatConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(floatConverter, object)); + + } else if (object instanceof Integer) { + Method m = integerConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(integerConverter, object)); + + } else if (object instanceof Long) { + Method m = longConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(longConverter, object)); + + } else if (object instanceof Short) { + Method m = shortConverter.getClass().getDeclaredMethod( + "to" + returnType.getSimpleName(), + object.getClass()); + return returnType.cast(m.invoke(shortConverter, object)); + + } else { + throw new AtlasConversionException(String.format( + "Unsupported Number type '%s'", object.getClass().getName())); + } + } catch (Exception e) { + throw new AtlasConversionException(String.format( + "No converter found from='%s' to='%s'", object.getClass().getName(), returnType.getName())); + } + } +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/ShortConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/ShortConverter.java new file mode 100644 index 00000000..52a1e1d9 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/ShortConverter.java @@ -0,0 +1,199 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.CharBuffer; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Date; + +import io.atlasmap.api.AtlasConversionException; +import io.atlasmap.api.AtlasUnsupportedException; +import io.atlasmap.spi.AtlasConversionConcern; +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class ShortConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.DECIMAL) + public BigDecimal toBigDecimal(Short value) { + return value != null ? BigDecimal.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.BIG_INTEGER) + public BigInteger toBigInteger(Short value) { + return value != null ? BigInteger.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.BOOLEAN, concerns = AtlasConversionConcern.CONVENTION) + public Boolean toBoolean(Short value) { + if (value == null) { + return null; + } + return value == 0 ? Boolean.FALSE : Boolean.TRUE; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.BYTE, concerns = AtlasConversionConcern.RANGE) + public Byte toByte(Short value) throws AtlasConversionException { + if (value == null) { + return null; + } + if (value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE) { + return value.byteValue(); + } + throw new AtlasConversionException(new AtlasUnsupportedException( + String.format("Short %s is greater than Byte.MAX_VALUE or less than Byte.MIN_VALUE", value))); + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.CHAR, concerns = { + AtlasConversionConcern.RANGE, AtlasConversionConcern.CONVENTION }) + public Character toCharacter(Short value) throws AtlasConversionException { + if (value == null) { + return null; + } + + if (value < Character.MIN_VALUE || value > Character.MAX_VALUE) { + throw new AtlasConversionException(String + .format("Short %s is greater than Character.MAX_VALUE or less than Character.MIN_VALUE", value)); + } + return Character.valueOf((char) value.intValue()); + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.DATE_TIME) + public Date toDate(Short value) { + if (value >= Instant.MIN.getEpochSecond()) { + return Date.from(Instant.ofEpochMilli(value)); + } + return new Date(value); + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.DOUBLE) + public Double toDouble(Short value) { + if (value == null) { + return null; + } + return value.doubleValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.FLOAT) + public Float toFloat(Short value) { + if (value == null) { + return null; + } + return value.floatValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.INTEGER) + public Integer toInteger(Short value) { + if (value == null) { + return null; + } + return value.intValue(); + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.DATE) + public LocalDate toLocalDate(Short value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDate() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.TIME) + public LocalTime toLocalTime(Short value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(Short value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()).toLocalDateTime() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.LONG) + public Long toLong(Short value) { + return value != null ? value.longValue() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.NUMBER) + public Number toNumber(Short value) { + return value; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.SHORT) + public Short toShort(Short value) { + return value != null ? new Short(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.STRING) + public String toString(Short value) { + return value != null ? String.valueOf(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.STRING) + public CharBuffer toCharBuffer(Short value) { + return value != null ? CharBuffer.wrap(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.STRING) + public CharSequence toCharSequence(Short value) { + return value != null ? toString(value) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.STRING) + public StringBuffer toStringBuffer(Short value) { + return value != null ? new StringBuffer(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.STRING) + public StringBuilder toStringBuilder(Short value) { + return value != null ? new StringBuilder(toString(value)) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.SHORT, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(Short value) { + return value != null ? Instant.ofEpochMilli(value).atZone(ZoneId.systemDefault()) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/SqlDateConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/SqlDateConverter.java new file mode 100644 index 00000000..c13b9354 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/SqlDateConverter.java @@ -0,0 +1,93 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class SqlDateConverter implements AtlasConverter { + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME_TZ) + public Calendar toCalendar(java.sql.Date date) { + return date != null ? GregorianCalendar.from(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME) + public Date toDate(java.sql.Date date, String sourceFormat, String targetFormat) { + return date != null ? DateTimeHelper.convertSqlDateToDate(date, sourceFormat) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME_TZ) + public GregorianCalendar toGregorianCalendar(java.sql.Date date) { + return date != null ? GregorianCalendar.from(ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault())) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE) + public LocalDate toLocalDate(java.sql.Date date) { + return date != null ? date.toLocalDate() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME) + public LocalDateTime toLocalDateTime(java.sql.Date date) { + return date != null ? date.toLocalDate().atStartOfDay() : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME) + public java.sql.Timestamp toSqlTimestamp(java.sql.Date date) { + return date != null ? new java.sql.Timestamp(date.getTime()) : null; + } + + @AtlasConversionInfo(sourceType = FieldType.DATE, targetType = FieldType.DATE_TIME_TZ) + public ZonedDateTime toZonedDateTime(java.sql.Date date) { + return date != null ? ZonedDateTime.ofInstant(Instant.ofEpochMilli(date.getTime()), ZoneId.systemDefault()) : null; + } + +} diff --git a/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/SqlTimeConverter.java b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/SqlTimeConverter.java new file mode 100644 index 00000000..00c4b915 --- /dev/null +++ b/platform/runtime/modules/atlasmap/atlasmap-entaxy-libs/src/main/java/io/atlasmap/converters/SqlTimeConverter.java @@ -0,0 +1,96 @@ +/*- + * ~~~~~~licensing~~~~~~ + * atlasmap-entaxy-services + * ========== + * 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~~~~~~ + */ +/* + * Copyright (C) 2017 Red Hat, Inc. + * + * 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. + */ +package io.atlasmap.converters; + +import java.sql.Time; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.ZoneId; +import java.time.ZonedDateTime; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +import io.atlasmap.spi.AtlasConversionInfo; +import io.atlasmap.spi.AtlasConverter; +import io.atlasmap.v2.FieldType; + +public class SqlTimeConverter implements AtlasConverter