release version 1.10.0

This commit is contained in:
2024-12-14 04:07:49 +03:00
parent a5088587f7
commit c6b3d793c4
1916 changed files with 254306 additions and 0 deletions

View File

@ -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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -0,0 +1,304 @@
<!--
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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.atlasmap</groupId>
<artifactId>atlas-parent</artifactId>
<version>2.2.3</version>
<!-- relativePath>../parent</relativePath -->
</parent>
<artifactId>camel3-atlasmap-entaxy</artifactId>
<packaging>bundle</packaging>
<version>2.5.2</version>
<name>camel3-atlasmap</name>
<description>Camel component to perform AtlasMap data mapping as a part of Camel route</description>
<properties>
<entaxy.version>1.10.0</entaxy.version>
<osgi.export.pkg>org.apache.camel.component.atlasmap</osgi.export.pkg>
<osgi.export.service>org.apache.camel.spi.ComponentResolver;component=atlas</osgi.export.service>
<camel3.version>3.4.5</camel3.version>
<atlas.version>2.5.2</atlas.version>
<checkstyle.skip>true</checkstyle.skip>
<jackson.version>2.12.3</jackson.version>
</properties>
<licenses>
<license>
<name>The Apache Software License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core</artifactId>
<version>${camel3.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-support</artifactId>
<version>${camel3.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.modules.atlasmap</groupId>
<artifactId>atlasmap-entaxy-libs</artifactId>
<version>${entaxy.version}</version>
</dependency>
<!-- for testing -->
<dependency>
<groupId>io.atlasmap</groupId>
<artifactId>atlas-java-test-model</artifactId>
<version>${atlas.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.atlasmap</groupId>
<artifactId>atlas-xml-test-model</artifactId>
<version>${atlas.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.atlasmap</groupId>
<artifactId>atlas-xml-core</artifactId>
<version>${atlas.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-test-spring</artifactId>
<version>${camel3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-core-xml</artifactId>
<version>${camel3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-javaconfig</artifactId>
<version>${camel3.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.codehaus.woodstox</groupId>
<artifactId>woodstox-core-asl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${camel3-spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.twitter4j</groupId>
<artifactId>twitter4j-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-assertj</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.xmlunit</groupId>
<artifactId>xmlunit-matchers</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<profiles>
<profile>
<id>jacoco</id>
<properties>
<sonar.language>java</sonar.language>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>${argLine}</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<executions>
<execution>
<id>prepare-agent</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<includes>
<include>**/*.class</include>
</includes>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
<profile>
<id>public-deploy</id>
<activation>
<activeByDefault>false</activeByDefault>
</activation>
<distributionManagement>
<repository>
<id>entaxy-public-entaxy</id>
<name>entaxy-public-entaxy</name>
<uniqueVersion>false</uniqueVersion>
<layout>default</layout>
<!-- url>http://localhost:8981/repository/entaxy-public-entaxy/</url -->
<url>https://nexus.entaxy.ru/nexus/repository/entaxy-public-entaxy/</url>
</repository>
<!-- we don't publish snapshots -->
<!-- snapshotRepository>
<id>entaxy-private-snapshots</id>
<name>entaxy-private-snapshots</name>
<uniqueVersion>false</uniqueVersion>
<layout>default</layout>
<url>http://localhost:8981/repository/entaxy-private-snapshots/</url>
</snapshotRepository -->
</distributionManagement>
</profile>
</profiles>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.eclipse.m2e</groupId>
<artifactId>lifecycle-mapping</artifactId>
<version>1.0.0</version>
<configuration>
<lifecycleMappingMetadata>
<pluginExecutions>
<pluginExecution>
<pluginExecutionFilter>
<groupId>org.apache.camel</groupId>
<artifactId>camel-package-maven-plugin</artifactId>
<versionRange>[2.19.0.fuse-000035,)</versionRange>
<goals>
<goal>prepare-components</goal>
</goals>
</pluginExecutionFilter>
<action>
<ignore/>
</action>
</pluginExecution>
</pluginExecutions>
</lifecycleMappingMetadata>
</configuration>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>filter</id>
<phase>generate-resources</phase>
<goals>
<goal>resources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.0.0</version>
<configuration>
<!-- ENTAXY: set to false -->
<failOnError>false</failOnError>
</configuration>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>entaxy-private-releases</id>
<name>entaxy-private-releases</name>
<url>https://nexus.entaxy.ru/nexus/repository/entaxy-private-releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
<repository>
<id>entaxy-private-snapshots</id>
<name>entaxy-private-snapshots</name>
<url>https://nexus.entaxy.ru/nexus/repository/entaxy-private-snapshots/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>

View File

@ -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<String, Object> 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;
}
}

View File

@ -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() {
}
}

View File

@ -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
* <code>java.util.Map&lt;String, Message&gt;</code> 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
* <code>java.util.Map&lt;String, Object&gt;</code> 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<Audit> 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<String, Message> sourceMessages = null;
Map<String, Object> sourceDocuments = null;
if (sourceMapName != null) {
sourceMessages = exchange.getProperty(sourceMapName, Map.class);
}
if (sourceMessages == null) {
Object body = inMessage.getBody();
if (body instanceof Map) {
sourceDocuments = (Map<String, Object>)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<String, Object> 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);
}
}
}

View File

@ -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<String, Message> 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<String, Object> 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;
}
}

View File

@ -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.

View File

@ -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

View File

@ -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<DataSource> 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<DataSource> 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<DataSource> 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<DataSource> 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<DataSource> 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<DataSource> 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<DataSource> 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<Void>() {
@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<Void>() {
@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<Void>() {
@Override
public Void answer(InvocationOnMock invocation) {
LOG.debug("setBody({})", invocation.getArgument(0).toString());
assertEquals("<target/>", invocation.getArgument(0));
return null;
}
}).when(outMessage).setBody(any());
doNothing().when(outMessage).setHeaders(any());
if (targetDocId == null) {
when(session.getDefaultTargetDocument()).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
LOG.debug("getDefaultTargetDocument()");
return "<target/>";
}
});
} else {
when(session.getTargetDocument(any())).thenAnswer(new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
LOG.debug("getTargetDocument({})", invocation.getArgument(0).toString());
assertEquals(targetDocId, invocation.getArgument(0));
return "<target/>";
}
});
}
when(exchange.getMessage()).thenReturn(outMessage);
endpoint.onExchange(exchange);
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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 = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><tns:Patient xmlns:tns=\"http://hl7.org/fhir\"><tns:id value=\"101138\"/></tns:Patient>";
@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("<Patient xmlns=\"http://hl7.org/fhir\"><id value=\"101138\"></id></Patient>".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());
}
}

View File

@ -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 = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><tns:Patient xmlns:tns=\"http://hl7.org/fhir\"><tns:id value=\"101138\"/></tns:Patient>";
@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("<tns:Patient xmlns:tns=\"http://hl7.org/fhir\"><tns:id value=\"101138\"></tns:id></tns:Patient>".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());
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<ns:Contact xmlns:ns=\"http://atlasmap.io/xml/test/v2\"\n" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
" firstName=\"XmlFirstName\" lastName=\"XmlLastName\"\n" +
" phoneNumber=\"XmlPhoneNumber\" zipCode=\"XmlZipCode\" />\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<String, Message> 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<String, Object> 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<String, Object> 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<String, Object> 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<String,String> 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");
}
}

View File

@ -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 =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<tns:request xmlns:tns=\"http://syndesis.io/v1/swagger-connector-template/request\">\n" +
" <tns:body>\n" +
" <Pet>\n" +
" <name>Jackson</name>\n" +
" </Pet>\n" +
" </tns:body>\n" +
"</tns:request>";
@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());
}
}

View File

@ -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"));
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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());
}
}

View File

@ -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());
}
}

View File

@ -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": [
]
}
}
}

View File

@ -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": [
]
}
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
]
}

View File

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="File" fileName="target/camel-atlasmap.log">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console" />
<AppenderRef ref="File" />
</Root>
</Loggers>
</Configuration>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping-java-to-json.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping-json-to-java.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping-xml-to-xml.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmap-mapping.adm" />
<to uri="mock:result" />
</route>
<route>
<from uri="direct:start-n" />
<to uri="atlas:atlasmap-mapping-n.adm" />
<to uri="mock:result-n" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:json-schema-source-to-xml-schema-target.adm" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping-multidocs.json?sourceMapName=CAPTURED_OUT_MESSAGES_MAP&amp;targetMapName=TARGET_MESSAGES_MAP" />
<to uri="mock:result" />
</route>
<route>
<from uri="direct:start-body" />
<to uri="atlas:atlasmapping-multidocs.json" />
<to uri="mock:result-body" />
</route>
<route>
<from uri="direct:start-header" />
<to uri="atlas:atlasmapping-multidocs.json?targetMapMode=MESSAGE_HEADER" />
<to uri="mock:result-body" />
</route>
<route>
<from uri="direct:start-exchange-property" />
<to uri="atlas:atlasmapping-multidocs.json?targetMapMode=EXCHANGE_PROPERTY" />
<to uri="mock:result-body" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:atlasmapping-multins.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,17 @@
[
{
"id" : 1111,
"completed" : 1,
"task" : "task1"
},
{
"id" : 2222,
"completed" : null,
"task" : "task2"
},
{
"id" : 3333,
"completed" : 3,
"task" : "task3"
}
]

View File

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start-old" />
<to uri="atlas:org/apache/camel/component/atlasmap/issue/atlasmapping-2552-old.json" />
<to uri="mock:result-old" />
</route>
<route>
<from uri="direct:start-new" />
<to uri="atlas:org/apache/camel/component/atlasmap/issue/atlasmapping-2552-new.json" />
<to uri="mock:result-new" />
</route>
</camelContext>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route>
<from uri="direct:start" />
<to uri="atlas:org/apache/camel/component/atlasmap/issue/atlasmapping-issue-729.json" />
<to uri="mock:result" />
</route>
</camelContext>
</beans>

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -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"
}
}

View File

@ -0,0 +1,59 @@
<d:SchemaSet xmlns:d="http://atlasmap.io/xml/schemaset/v2" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:schema targetNamespace="http://syndesis.io/v1/swagger-connector-template/request" elementFormDefault="qualified">
<xsd:element name="request">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="body">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="Pet" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<d:AdditionalSchemas>
<xsd:schema>
<xsd:element name="Pet">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:decimal" minOccurs="0" />
<xsd:element name="Category">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:decimal" minOccurs="0" />
<xsd:element name="name" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="name" type="xsd:string" />
<xsd:element name="photoUrl" minOccurs="0" >
<xsd:complexType>
<xsd:sequence>
<xsd:element name="photoUrl" type="xsd:string" maxOccurs="unbounded" minOccurs="0" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="tag" minOccurs="0" >
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Tag" maxOccurs="unbounded" minOccurs="0">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="id" type="xsd:decimal" />
<xsd:element name="name" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="status" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
</d:AdditionalSchemas>
</d:SchemaSet>

View File

@ -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. Если какое-либо положение настоящей Лицензии будет признано судом недействительным,
остальные положения будут продолжать своё действие, а Пользователь будет обязан продолжать
исполнять свои обязанности в соответствии с этими положениями.

View File

@ -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") - это приводило к ошибке

View File

@ -0,0 +1,98 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ru.entaxy.esb.platform.runtime.modules</groupId>
<artifactId>atlasmap</artifactId>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.modules.atlasmap</groupId>
<artifactId>atlasmap-entaxy-libs</artifactId>
<packaging>bundle</packaging>
<name>ENTAXY :: ATLASMAP :: LIBS</name>
<description>ENTAXY :: ATLASMAP :: LIBS</description>
<properties>
<xsom.version>2.5.2</xsom.version>
<javax.ws.rs.version>2.1.1</javax.ws.rs.version>
<!-- we can't up version because lib use the newest java 17-->
<jackson.version>2.9.10</jackson.version>
<jackson.databind.version>2.9.10.8</jackson.databind.version>
<bundle.osgi.export.pkg>
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
</bundle.osgi.export.pkg>
</properties>
<dependencies>
<dependency>
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
<artifactId>base-support</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-cxf</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel.karaf</groupId>
<artifactId>camel-cxf-blueprint</artifactId>
<version>${camel.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.databind.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jsonSchema</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>ru.entaxy.com.sun.xsom</groupId>
<artifactId>xsom</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger.v3.version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>${javax.ws.rs.version}</version>
</dependency>
</dependencies>
</project>

View File

@ -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[]{};
}
}

View File

@ -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();
}
}

View File

@ -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<Object> 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);
}
}

View File

@ -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<MassUnitType, Map<MassUnitType, Double>> massConvertionTable;
static {
Map<MassUnitType, Map<MassUnitType, Double>> rootTable = new EnumMap<>(MassUnitType.class);
Map<MassUnitType, Double> 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<MassUnitType, Double> 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<DistanceUnitType, Map<DistanceUnitType, Double>> distanceConvertionTable;
static {
Map<DistanceUnitType, Map<DistanceUnitType, Double>> rootTable = new EnumMap<>(DistanceUnitType.class);
Map<DistanceUnitType, Double> 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<DistanceUnitType, Double> 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<DistanceUnitType, Double> 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<DistanceUnitType, Double> 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<DistanceUnitType, Double> 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<AreaUnitType, Map<AreaUnitType, Double>> areaConvertionTable;
static {
Map<AreaUnitType, Map<AreaUnitType, Double>> rootTable = new EnumMap<>(AreaUnitType.class);
Map<AreaUnitType, Double> 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<AreaUnitType, Double> 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<AreaUnitType, Double> 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<VolumeUnitType, Map<VolumeUnitType, Double>> volumeConvertionTable;
static {
Map<VolumeUnitType, Map<VolumeUnitType, Double>> rootTable = new EnumMap<>(VolumeUnitType.class);
Map<VolumeUnitType, Double> 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<VolumeUnitType, Double> 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<VolumeUnitType, Double> 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<VolumeUnitType, Double> 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<Number> 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<Number> 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<Number> 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<Number> 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<Number> 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<Number> 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<Number> 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");
}
}

View File

@ -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<Object> inputs) {
if (inputs == null) {
return 0;
}
return inputs.size();
}
@AtlasActionProcessor
public static Boolean contains(Contains contains, List<Object> 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<Object> 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;
}
}

View File

@ -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<String> 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<Object> 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);
}
}

View File

@ -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);
}
}

View File

@ -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() {
}
}

View File

@ -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;
}

View File

@ -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<String, String> properties);
void setProperties(Properties properties);
Map<String, String> getProperties();
void addClassLoader(ClassLoader cl);
}

View File

@ -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);
}
}

View File

@ -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 <T> Java type to convert from
*/
@Deprecated
public interface AtlasConverter<T> extends io.atlasmap.spi.AtlasConverter<T> {
}

View File

@ -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);
}
}

View File

@ -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 {
}

View File

@ -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;
}

View File

@ -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);
}
}

View File

@ -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;
}

View File

@ -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<String, Object> getProperties();
Map<String, Object> getSourceProperties();
Map<String, Object> 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<String, Object> getSourceDocumentMap();
Object getDefaultTargetDocument();
void setDefaultTargetDocument(Object targetDoc);
Object getTargetDocument(String docId);
void setTargetDocument(String docId, Object targetDoc);
boolean hasTargetDocument(String docId);
Map<String, Object> getTargetDocumentMap();
Validations getValidations();
void setValidations(Validations validations);
Audits getAudits();
void setAudits(Audits audits);
boolean hasErrors();
boolean hasWarns();
Integer errorCount();
Integer warnCount();
}

View File

@ -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);
}
}

View File

@ -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);
}
}

View File

@ -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<Validation> validateMapping(AtlasMapping mapping);
}

View File

@ -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<Constant> 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<Object> 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;
}
}

View File

@ -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);
}
}
}

View File

@ -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<BigInteger> {
@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));
}
}
}

View File

@ -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<BigInteger> {
@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));
}
}
}

View File

@ -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<Boolean> {
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;
}
}

View File

@ -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<Byte> {
@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());
}
}

View File

@ -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<Calendar> {
@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);
}
}

View File

@ -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<CharBuffer> {
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);
}
}

View File

@ -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<CharSequence> {
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;
}
}

View File

@ -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<Character> {
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;
}
}

View File

@ -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<Date> {
@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);
}
}

View File

@ -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();
}
}

View File

@ -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<Double> {
@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());
}
}

View File

@ -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<Float> {
@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());
}
}

View File

@ -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<GregorianCalendar> {
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();
}
}

View File

@ -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<Integer> {
@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;
}
}

View File

@ -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<LocalDate> {
@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;
}
}

View File

@ -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<LocalDateTime> {
@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();
}
}

View File

@ -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<LocalTime> {
@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();
}
}

View File

@ -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<Long> {
@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;
}
}

View File

@ -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<Number> {
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> T invoke(Number object, Class<T> 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()));
}
}
}

View File

@ -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<Short> {
@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;
}
}

View File

@ -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<java.sql.Date> {
@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;
}
}

View File

@ -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<Time> {
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME_TZ)
public Calendar toCalendar(Time time, String sourceFormat, String targetFormat) {
return time != null ? GregorianCalendar.from(ZonedDateTime.ofInstant(Instant.ofEpochMilli(time.getTime()), ZoneId.systemDefault())) : null;
}
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME)
public Date toDate(Time time, String sourceFormat, String targetFormat) {
return time != null ? new Date(time.getTime()) : null;
}
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME_TZ)
public GregorianCalendar toGregorianCalendar(Time time, String sourceFormat, String targetFormat) {
return time != null ? GregorianCalendar.from(ZonedDateTime.ofInstant(Instant.ofEpochMilli(time.getTime()), ZoneId.systemDefault())) : null;
}
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.TIME)
public LocalTime toLocalTime(Time time, String sourceFormat, String targetFormat) {
return time != null ? time.toLocalTime() : null;
}
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME)
public LocalDateTime toLocalDateTime(Time time, String sourceFormat, String targetFormat) {
return time != null ? time.toLocalTime().atDate(LocalDate.now()) : null;
}
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME)
public Timestamp toSqlTimestamp(Time time, String sourceFormat, String targetFormat) {
return time != null ? new Timestamp(time.getTime()) : null;
}
@AtlasConversionInfo(sourceType = FieldType.TIME, targetType = FieldType.DATE_TIME_TZ)
public ZonedDateTime toZonedDateTime(Time time, String sourceFormat, String targetFormat) {
return time != null ? ZonedDateTime.ofInstant(Instant.ofEpochMilli(time.getTime()), ZoneId.systemDefault()) : null;
}
}

View File

@ -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.sql.Timestamp;
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 SqlTimestampConverter implements AtlasConverter<Timestamp> {
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ)
public Calendar toCalendar(Timestamp timestamp) {
return timestamp != null ? GregorianCalendar.from(ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault())) : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME)
public Date toDate(Timestamp timestamp) {
return timestamp != null ? Date.from(timestamp.toInstant()) : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ)
public GregorianCalendar toGregorianCalendar(Timestamp timestamp) {
return timestamp != null ? GregorianCalendar.from(ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault())) : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE)
public LocalDate toLocalDate(Timestamp timestamp) {
return timestamp != null ? timestamp.toLocalDateTime().toLocalDate() : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME)
public LocalDateTime toLocalDateTime(Timestamp timestamp) {
return timestamp != null ? timestamp.toLocalDateTime() : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.TIME)
public LocalTime toLocalTime(Timestamp timestamp) {
return timestamp != null ? timestamp.toLocalDateTime().toLocalTime() : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE)
public java.sql.Date toSqlDate(Timestamp timestamp) {
return timestamp != null ? java.sql.Date.valueOf(timestamp.toLocalDateTime().toLocalDate()) : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.TIME)
public java.sql.Time toSqlTime(Timestamp timestamp) {
return timestamp != null ? java.sql.Time.valueOf(timestamp.toLocalDateTime().toLocalTime()) : null;
}
@AtlasConversionInfo(sourceType = FieldType.DATE_TIME, targetType = FieldType.DATE_TIME_TZ)
public ZonedDateTime toZonedDateTime(Timestamp timestamp) {
return timestamp != null ? ZonedDateTime.ofInstant(timestamp.toInstant(), ZoneId.systemDefault()) : null;
}
}

Some files were not shown because too many files have changed in this diff Show More