new line - linux

This commit is contained in:
Radek Davidek 2025-11-03 09:34:56 +01:00
parent bd86e26dda
commit cafa504527
19 changed files with 1913 additions and 1913 deletions

206
pom.xml
View File

@ -1,104 +1,104 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<groupId>cz.trask.migration</groupId> <groupId>cz.trask.migration</groupId>
<artifactId>apicurio-migration-tool</artifactId> <artifactId>apicurio-migration-tool</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<version>1.0.0</version> <version>1.0.0</version>
<name>apicurio-migration-tool</name> <name>apicurio-migration-tool</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<java.version>11</java.version> <java.version>11</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source> <maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target> <maven.compiler.target>${java.version}</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<!-- https://mvnrepository.com/artifact/io.apicurio/apicurio-registry-client --> <!-- https://mvnrepository.com/artifact/io.apicurio/apicurio-registry-client -->
<dependency> <dependency>
<groupId>io.apicurio</groupId> <groupId>io.apicurio</groupId>
<artifactId>apicurio-registry-client</artifactId> <artifactId>apicurio-registry-client</artifactId>
<version>2.6.13.Final</version> <version>2.6.13.Final</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.apache.logging.log4j</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId> <artifactId>log4j-core</artifactId>
<version>2.24.2</version> <version>2.24.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId> <groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId> <artifactId>jackson-databind</artifactId>
<version>2.19.2</version> <version>2.19.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId> <groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId> <artifactId>jackson-dataformat-yaml</artifactId>
<version>2.19.2</version> <version>2.19.2</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.projectlombok</groupId> <groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId> <artifactId>lombok</artifactId>
<version>1.18.38</version> <version>1.18.38</version>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>io.swagger</groupId> <groupId>io.swagger</groupId>
<artifactId>swagger-parser</artifactId> <artifactId>swagger-parser</artifactId>
<version>1.0.75</version> <version>1.0.75</version>
</dependency> </dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId> <artifactId>maven-shade-plugin</artifactId>
<version>3.6.1</version> <version>3.6.1</version>
<executions> <executions>
<execution> <execution>
<goals> <goals>
<goal>shade</goal> <goal>shade</goal>
</goals> </goals>
<configuration> <configuration>
<createDependencyReducedPom>false</createDependencyReducedPom> <createDependencyReducedPom>false</createDependencyReducedPom>
<transformers> <transformers>
<transformer <transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>cz.trask.apioperator.ApiSync</mainClass> <mainClass>cz.trask.apioperator.ApiSync</mainClass>
</transformer> </transformer>
</transformers> </transformers>
</configuration> </configuration>
</execution> </execution>
</executions> </executions>
</plugin> </plugin>
<plugin> <plugin>
<groupId>org.apache.maven.plugins</groupId> <groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId> <artifactId>maven-jar-plugin</artifactId>
<version>3.4.1</version> <version>3.4.1</version>
<configuration> <configuration>
<archive> <archive>
<manifest> <manifest>
<mainClass>cz.trask.apioperator.ApiSync</mainClass> <mainClass>cz.trask.apioperator.ApiSync</mainClass>
</manifest> </manifest>
</archive> </archive>
</configuration> </configuration>
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<repositories> <repositories>
<repository> <repository>
<id>wso2.releases</id> <id>wso2.releases</id>
<name>WSO2 internal Repository</name> <name>WSO2 internal Repository</name>
<url>https://maven.wso2.org/nexus/content/repositories/releases/</url> <url>https://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases> <releases>
<enabled>true</enabled> <enabled>true</enabled>
<updatePolicy>daily</updatePolicy> <updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy> <checksumPolicy>ignore</checksumPolicy>
</releases> </releases>
</repository> </repository>
</repositories> </repositories>
</project> </project>

View File

@ -1,42 +1,42 @@
package cz.trask.migration; package cz.trask.migration;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import cz.trask.migration.impl.v32.ImportToApicurio; import cz.trask.migration.impl.v32.ImportToApicurio;
import cz.trask.migration.impl.v45.ExportToWso2FromV32; import cz.trask.migration.impl.v45.ExportToWso2FromV32;
import cz.trask.migration.model.StartParameters; import cz.trask.migration.model.StartParameters;
public class ApiSync { public class ApiSync {
private static Logger log = LogManager.getLogger(ApiSync.class); private static Logger log = LogManager.getLogger(ApiSync.class);
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
log.info("API Operator started."); log.info("API Operator started.");
if (args == null) { if (args == null) {
log.error("No parameters found."); log.error("No parameters found.");
printHelp(); printHelp();
} else { } else {
String commandLine = String.join("", args).trim(); String commandLine = String.join("", args).trim();
StartParameters sp = StartParameters.parse(commandLine); StartParameters sp = StartParameters.parse(commandLine);
log.info("Parsed parameters: " + sp); log.info("Parsed parameters: " + sp);
if (sp.getCommand().equalsIgnoreCase("wso2ToApicurio")) { if (sp.getCommand().equalsIgnoreCase("wso2ToApicurio")) {
log.info("Import command selected."); log.info("Import command selected.");
ImportToApicurio imp = new ImportToApicurio(); ImportToApicurio imp = new ImportToApicurio();
imp.process(); imp.process();
} else if (sp.getCommand().equalsIgnoreCase("apicurioToWso2")) { } else if (sp.getCommand().equalsIgnoreCase("apicurioToWso2")) {
log.info("Export command selected."); log.info("Export command selected.");
ExportToWso2FromV32 exp = new ExportToWso2FromV32(); ExportToWso2FromV32 exp = new ExportToWso2FromV32();
exp.process(); exp.process();
} else { } else {
log.error("Unknown command: " + sp.getCommand()); log.error("Unknown command: " + sp.getCommand());
printHelp(); printHelp();
} }
} }
} }
private static void printHelp() { private static void printHelp() {
System.out.println("Not enough parameters.\nRun command in this format:\njava -jar shaded.jar [import/export]"); System.out.println("Not enough parameters.\nRun command in this format:\njava -jar shaded.jar [wso2ToApicurio/apicurioToWso2]");
} }
} }

View File

@ -1,77 +1,77 @@
package cz.trask.migration.config; package cz.trask.migration.config;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
import java.nio.file.Files; import java.nio.file.Files;
import cz.trask.migration.AbstractProcess; import cz.trask.migration.AbstractProcess;
import cz.trask.migration.model.ApplicationConfig; import cz.trask.migration.model.ApplicationConfig;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@Log4j2 @Log4j2
public final class ConfigManager { public final class ConfigManager {
private static final String PROPERTY_FILENAME = "apicurio-migrator.yaml"; private static final String PROPERTY_FILENAME = "apicurio-migrator.yaml";
private static volatile ConfigManager INSTANCE; private static volatile ConfigManager INSTANCE;
private static ApplicationConfig config = new ApplicationConfig(); private static ApplicationConfig config = new ApplicationConfig();
private ConfigManager() { private ConfigManager() {
log.info("Loading property file '{}'", PROPERTY_FILENAME); log.info("Loading property file '{}'", PROPERTY_FILENAME);
InputStream in = null; InputStream in = null;
try { try {
File extFile = new File(PROPERTY_FILENAME); File extFile = new File(PROPERTY_FILENAME);
if (extFile.exists() && extFile.isFile()) { if (extFile.exists() && extFile.isFile()) {
log.info("External property file found: {}", extFile.getAbsolutePath()); log.info("External property file found: {}", extFile.getAbsolutePath());
in = Files.newInputStream(extFile.toPath()); in = Files.newInputStream(extFile.toPath());
} else { } else {
log.debug("External property file not found."); log.debug("External property file not found.");
} }
} catch (Exception e) { } catch (Exception e) {
log.warn("Error while accessing external property file", e); log.warn("Error while accessing external property file", e);
} }
if (in == null) { if (in == null) {
try { try {
ClassLoader cl = Thread.currentThread().getContextClassLoader(); ClassLoader cl = Thread.currentThread().getContextClassLoader();
in = cl.getResourceAsStream(PROPERTY_FILENAME); in = cl.getResourceAsStream(PROPERTY_FILENAME);
if (in != null) { if (in != null) {
log.info("Internal property file found on classpath."); log.info("Internal property file found on classpath.");
} else { } else {
log.warn("Property file '{}' not found on classpath.", PROPERTY_FILENAME); log.warn("Property file '{}' not found on classpath.", PROPERTY_FILENAME);
} }
} catch (Exception e) { } catch (Exception e) {
log.error("Unable to load property file from classpath", e); log.error("Unable to load property file from classpath", e);
} }
} }
try (InputStream input = in) { try (InputStream input = in) {
if (input != null) { if (input != null) {
config = AbstractProcess.mapperYaml.readValue(input, ApplicationConfig.class); config = AbstractProcess.mapperYaml.readValue(input, ApplicationConfig.class);
log.info("Property file loaded successfully."); log.info("Property file loaded successfully.");
} else { } else {
log.warn("No property source available; proceeding with defaults where possible."); log.warn("No property source available; proceeding with defaults where possible.");
} }
} catch (Exception e) { } catch (Exception e) {
log.error("Cannot load property file.", e); log.error("Cannot load property file.", e);
} }
} }
public static ConfigManager getInstance() { public static ConfigManager getInstance() {
if (INSTANCE == null) { if (INSTANCE == null) {
synchronized (ConfigManager.class) { synchronized (ConfigManager.class) {
if (INSTANCE == null) { if (INSTANCE == null) {
INSTANCE = new ConfigManager(); INSTANCE = new ConfigManager();
} }
} }
} }
return INSTANCE; return INSTANCE;
} }
public ApplicationConfig getConfig() { public ApplicationConfig getConfig() {
return config; return config;
} }
} }

View File

@ -1,368 +1,368 @@
package cz.trask.migration.impl.v32; package cz.trask.migration.impl.v32;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import cz.trask.migration.AbstractProcess; import cz.trask.migration.AbstractProcess;
import cz.trask.migration.model.APIInfo; import cz.trask.migration.model.APIInfo;
import cz.trask.migration.model.APIList; import cz.trask.migration.model.APIList;
import cz.trask.migration.model.FileType; import cz.trask.migration.model.FileType;
import cz.trask.migration.model.HttpResponse; import cz.trask.migration.model.HttpResponse;
import cz.trask.migration.model.TokenResponse; import cz.trask.migration.model.TokenResponse;
import cz.trask.migration.model.ZipEntryData; import cz.trask.migration.model.ZipEntryData;
import cz.trask.migration.model.v32.Subscriptions; import cz.trask.migration.model.v32.Subscriptions;
import cz.trask.migration.model.v32.Subscriptions.ApplicationInfo; import cz.trask.migration.model.v32.Subscriptions.ApplicationInfo;
import cz.trask.migration.model.v32.Subscriptions.Subscription; import cz.trask.migration.model.v32.Subscriptions.Subscription;
import io.apicurio.registry.rest.client.RegistryClient; import io.apicurio.registry.rest.client.RegistryClient;
import io.apicurio.registry.rest.client.RegistryClientFactory; import io.apicurio.registry.rest.client.RegistryClientFactory;
import io.apicurio.registry.rest.client.exception.VersionAlreadyExistsException; import io.apicurio.registry.rest.client.exception.VersionAlreadyExistsException;
import io.apicurio.registry.rest.v2.beans.ArtifactMetaData; import io.apicurio.registry.rest.v2.beans.ArtifactMetaData;
import io.apicurio.registry.rest.v2.beans.ArtifactReference; import io.apicurio.registry.rest.v2.beans.ArtifactReference;
import io.apicurio.registry.rest.v2.beans.EditableMetaData; import io.apicurio.registry.rest.v2.beans.EditableMetaData;
import io.apicurio.registry.rest.v2.beans.Rule; import io.apicurio.registry.rest.v2.beans.Rule;
import io.apicurio.registry.rest.v2.beans.VersionSearchResults; import io.apicurio.registry.rest.v2.beans.VersionSearchResults;
import io.apicurio.registry.types.RuleType; import io.apicurio.registry.types.RuleType;
public class ImportToApicurio extends AbstractProcess { public class ImportToApicurio extends AbstractProcess {
private static final Logger log = LogManager.getLogger(ImportToApicurio.class); private static final Logger log = LogManager.getLogger(ImportToApicurio.class);
private final AtomicInteger apiCounter = new AtomicInteger(1); private final AtomicInteger apiCounter = new AtomicInteger(1);
private final RegistryClient client; private final RegistryClient client;
public ImportToApicurio() throws Exception { public ImportToApicurio() throws Exception {
this.client = RegistryClientFactory.create(config.getApicurio().getApiUrl()); this.client = RegistryClientFactory.create(config.getApicurio().getApiUrl());
} }
/** /**
* Main entry point for the import process. * Main entry point for the import process.
* *
* @throws RuntimeException if any error occurs * @throws RuntimeException if any error occurs
*/ */
public void process() { public void process() {
try { try {
log.info("Starting API import to Apicurio from WSO2..."); log.info("Starting API import to Apicurio from WSO2...");
TokenResponse token = authenticateToWso2AndGetToken(); TokenResponse token = authenticateToWso2AndGetToken();
APIList apis = getList(config.getSource().getPublisherApiUrl(), token); APIList apis = getList(config.getSource().getPublisherApiUrl(), token);
if (apis == null || apis.getList() == null || apis.getList().length == 0) { if (apis == null || apis.getList() == null || apis.getList().length == 0) {
throw new IllegalStateException( throw new IllegalStateException(
"No APIs to export that match your criteria! Check the name of the API you want to export."); "No APIs to export that match your criteria! Check the name of the API you want to export.");
} }
log.info("Found {} APIs", apis.getCount()); log.info("Found {} APIs", apis.getCount());
int maxThreads = config.getMaxThreads(); int maxThreads = config.getMaxThreads();
ExecutorService executor = Executors.newFixedThreadPool(maxThreads); ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
for (APIInfo api : apis.getList()) { for (APIInfo api : apis.getList()) {
final int index = apiCounter.getAndIncrement(); final int index = apiCounter.getAndIncrement();
executor.submit(() -> processApi(api, token, index, apis.getCount())); executor.submit(() -> processApi(api, token, index, apis.getCount()));
} }
executor.shutdown(); executor.shutdown();
if (!executor.awaitTermination(10, TimeUnit.MINUTES)) { if (!executor.awaitTermination(10, TimeUnit.MINUTES)) {
log.warn("Timeout waiting for API import tasks to finish"); log.warn("Timeout waiting for API import tasks to finish");
} }
log.info("Finished processing APIs."); log.info("Finished processing APIs.");
} catch (Exception e) { } catch (Exception e) {
log.error("Error while exporting APIs.", e); log.error("Error while exporting APIs.", e);
throw new RuntimeException("Export failed", e); throw new RuntimeException("Export failed", e);
} }
} }
/** /**
* Process a single API fetches the data, creates or updates the corresponding * Process a single API fetches the data, creates or updates the corresponding
* artifact in Apicurio. * artifact in Apicurio.
*/ */
private void processApi(APIInfo api, TokenResponse tokenResponse, int index, int total) { private void processApi(APIInfo api, TokenResponse tokenResponse, int index, int total) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
String status = api.getLifeCycleStatus(); String status = api.getLifeCycleStatus();
if (!status.contains("PUBLISHED") && !status.contains("DEPRECATED")) { if (!status.contains("PUBLISHED") && !status.contains("DEPRECATED")) {
log.info("Skipping API {} of {} not published (ID={})", index, total, api.getId()); log.info("Skipping API {} of {} not published (ID={})", index, total, api.getId());
return; return;
} }
try { try {
log.info("Processing API {} of {}", index, total); log.info("Processing API {} of {}", index, total);
Map<String, String> httpHeaders = Collections.singletonMap("Authorization", Map<String, String> httpHeaders = Collections.singletonMap("Authorization",
"Bearer " + tokenResponse.getAccess_token()); "Bearer " + tokenResponse.getAccess_token());
// 1) Retrieve basic information // 1) Retrieve basic information
HttpResponse apiInfoResp = makeRequest("GET", HttpResponse apiInfoResp = makeRequest("GET",
config.getSource().getDevPortalApiUrl() + "/apis/" + api.getId(), httpHeaders, config.getSource().getDevPortalApiUrl() + "/apis/" + api.getId(), httpHeaders,
Collections.emptyMap()); Collections.emptyMap());
HttpResponse subsResp = makeRequest("GET", HttpResponse subsResp = makeRequest("GET",
config.getSource().getPublisherApiUrl() + "/subscriptions?apiId=" + api.getId(), httpHeaders, config.getSource().getPublisherApiUrl() + "/subscriptions?apiId=" + api.getId(), httpHeaders,
Collections.emptyMap()); Collections.emptyMap());
// 2) Export the API as a zip // 2) Export the API as a zip
HttpResponse exportedZip = makeRequest("GET", HttpResponse exportedZip = makeRequest("GET",
config.getSource().getPublisherApiUrl() + "/apis/export?apiId=" + api.getId(), httpHeaders, config.getSource().getPublisherApiUrl() + "/apis/export?apiId=" + api.getId(), httpHeaders,
Collections.emptyMap(), true); Collections.emptyMap(), true);
List<ZipEntryData> zipEntries = ZipUtils.extractFilesFromZip(exportedZip.getResponseBytes()); List<ZipEntryData> zipEntries = ZipUtils.extractFilesFromZip(exportedZip.getResponseBytes());
String swagger = null; String swagger = null;
for (ZipEntryData e : zipEntries) { for (ZipEntryData e : zipEntries) {
if (e.getType().toString().equals(FileType.OPENAPI.toString())) { if (e.getType().toString().equals(FileType.OPENAPI.toString())) {
log.debug("Found main API definition file: {}", e.getName()); log.debug("Found main API definition file: {}", e.getName());
swagger = new String(e.getContent()); swagger = new String(e.getContent());
break; break;
} }
} }
// 3) Deserialize JSON responses // 3) Deserialize JSON responses
Map<String, Object> apiMap = mapper.readValue(apiInfoResp.getResponse(), Map.class); Map<String, Object> apiMap = mapper.readValue(apiInfoResp.getResponse(), Map.class);
Subscriptions subs = mapper.readValue(subsResp.getResponse(), Subscriptions.class); Subscriptions subs = mapper.readValue(subsResp.getResponse(), Subscriptions.class);
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<String> tagsList = (List<String>) apiMap.get("tags"); List<String> tagsList = (List<String>) apiMap.get("tags");
// 4) Build the properties map // 4) Build the properties map
Map<String, String> props = new LinkedHashMap<>(); Map<String, String> props = new LinkedHashMap<>();
props.put("version", api.getVersion()); props.put("version", api.getVersion());
props.put("status", status); props.put("status", status);
props.put(PARAM_SOURCE_APIM, VERSION_32); props.put(PARAM_SOURCE_APIM, VERSION_32);
addSubscriptionsToProps(props, subs); addSubscriptionsToProps(props, subs);
addEndpointsToProps(props, apiMap); addEndpointsToProps(props, apiMap);
addTagsToProps(props, tagsList); addTagsToProps(props, tagsList);
// 5) Build the description that contains the publisher & devportal URLs // 5) Build the description that contains the publisher & devportal URLs
String baseDesc = api.getDescription() != null ? api.getDescription() : ""; String baseDesc = api.getDescription() != null ? api.getDescription() : "";
String pubUrl = config.getPatterns().getPublisherUrlPattern().replace("{API_ID}", api.getId()); String pubUrl = config.getPatterns().getPublisherUrlPattern().replace("{API_ID}", api.getId());
String devPortUrl = config.getPatterns().getDevPortalUrlPattern().replace("{API_ID}", api.getId()); String devPortUrl = config.getPatterns().getDevPortalUrlPattern().replace("{API_ID}", api.getId());
String fullDesc = baseDesc + " ***** PUBLISHER URL ***** " + pubUrl + " ***** DEVPORTAL URL ***** " String fullDesc = baseDesc + " ***** PUBLISHER URL ***** " + pubUrl + " ***** DEVPORTAL URL ***** "
+ devPortUrl; + devPortUrl;
// 6) Update the swagger with the description and servers // 6) Update the swagger with the description and servers
Map<String, Object> swaggerMap = mapperYaml.readValue(swagger, Map.class); Map<String, Object> swaggerMap = mapperYaml.readValue(swagger, Map.class);
ObjectNode swaggerObj = mapperYaml.valueToTree(swaggerMap); ObjectNode swaggerObj = mapperYaml.valueToTree(swaggerMap);
updateSwagger(swaggerObj, apiMap, fullDesc); updateSwagger(swaggerObj, apiMap, fullDesc);
// 7) Prepare artifact creation/update // 7) Prepare artifact creation/update
String group = config.getApicurio().getDefaultApiGroup(); String group = config.getApicurio().getDefaultApiGroup();
String mainArtifactId = api.getName() + api.getContext(); String mainArtifactId = api.getName() + api.getContext();
VersionSearchResults existingArtifacts; VersionSearchResults existingArtifacts;
try { try {
existingArtifacts = client.listArtifactVersions(group, mainArtifactId, 0, Integer.MAX_VALUE); existingArtifacts = client.listArtifactVersions(group, mainArtifactId, 0, Integer.MAX_VALUE);
} catch (Exception e) { } catch (Exception e) {
log.debug("No API {} exists will create it", api.getContext()); log.debug("No API {} exists will create it", api.getContext());
existingArtifacts = null; existingArtifacts = null;
} }
if (existingArtifacts == null) { if (existingArtifacts == null) {
// Create new artifact // Create new artifact
List<ArtifactReference> references = createReferencesFromZip(zipEntries, group, api); List<ArtifactReference> references = createReferencesFromZip(zipEntries, group, api);
addSubscriptionsToReferences(references, subs, api); addSubscriptionsToReferences(references, subs, api);
ArtifactMetaData meta = client.createArtifact(group, mainArtifactId, api.getVersion(), null, null, null, ArtifactMetaData meta = client.createArtifact(group, mainArtifactId, api.getVersion(), null, null, null,
api.getName(), fullDesc, null, null, null, api.getName(), fullDesc, null, null, null,
new ByteArrayInputStream(swaggerObj.toString().getBytes()), references); new ByteArrayInputStream(swaggerObj.toString().getBytes()), references);
setArtifactMetaData(meta, props); setArtifactMetaData(meta, props);
// Create the three required rules // Create the three required rules
createRule(meta, "NONE", RuleType.COMPATIBILITY); createRule(meta, "NONE", RuleType.COMPATIBILITY);
createRule(meta, "NONE", RuleType.VALIDITY); createRule(meta, "NONE", RuleType.VALIDITY);
createRule(meta, "NONE", RuleType.INTEGRITY); createRule(meta, "NONE", RuleType.INTEGRITY);
} else { } else {
// Artifact exists check if the version exists // Artifact exists check if the version exists
boolean versionExists = false; boolean versionExists = false;
try { try {
client.getArtifactVersionMetaData(group, mainArtifactId, api.getVersion()); client.getArtifactVersionMetaData(group, mainArtifactId, api.getVersion());
versionExists = true; versionExists = true;
} catch (Exception e) { } catch (Exception e) {
// Version missing will create it below // Version missing will create it below
} }
List<ArtifactReference> references = createReferencesFromZip(zipEntries, group, api); List<ArtifactReference> references = createReferencesFromZip(zipEntries, group, api);
addSubscriptionsToReferences(references, subs, api); addSubscriptionsToReferences(references, subs, api);
if (!versionExists) { if (!versionExists) {
ArtifactMetaData meta = client.updateArtifact(group, mainArtifactId, api.getVersion(), ArtifactMetaData meta = client.updateArtifact(group, mainArtifactId, api.getVersion(),
api.getName(), fullDesc, new ByteArrayInputStream(swaggerObj.toString().getBytes()), api.getName(), fullDesc, new ByteArrayInputStream(swaggerObj.toString().getBytes()),
references); references);
setArtifactMetaData(meta, props); setArtifactMetaData(meta, props);
} else { } else {
// Version already exists no action needed // Version already exists no action needed
log.warn("API {} with version {} already exists. Skipping import.", api.getContext(), log.warn("API {} with version {} already exists. Skipping import.", api.getContext(),
api.getVersion()); api.getVersion());
} }
} }
log.info("Successfully imported API '{}' ({}). Took {} ms", api.getName(), api.getVersion(), log.info("Successfully imported API '{}' ({}). Took {} ms", api.getName(), api.getVersion(),
System.currentTimeMillis() - start); System.currentTimeMillis() - start);
} catch (IOException e) { } catch (IOException e) {
log.error("IO error while importing API {}: {}", api.getId(), e.getMessage(), e); log.error("IO error while importing API {}: {}", api.getId(), e.getMessage(), e);
} catch (VersionAlreadyExistsException e) { } catch (VersionAlreadyExistsException e) {
log.warn("API version already exists for {}: {}. Skipping.", api.getName(), api.getVersion()); log.warn("API version already exists for {}: {}. Skipping.", api.getName(), api.getVersion());
} catch (Exception e) { } catch (Exception e) {
log.error("Cannot export API '{}':{}", api.getName(), api.getVersion(), e); log.error("Cannot export API '{}':{}", api.getName(), api.getVersion(), e);
} }
} }
/* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */
/* Helper methods */ /* Helper methods */
/* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */
private void updateSwagger(ObjectNode swagger, Map<String, Object> apiMap, String description) { private void updateSwagger(ObjectNode swagger, Map<String, Object> apiMap, String description) {
// Update "info.description" // Update "info.description"
ObjectNode info = (ObjectNode) swagger.get("info"); ObjectNode info = (ObjectNode) swagger.get("info");
if (info != null) { if (info != null) {
info.put("description", description); info.put("description", description);
} }
// Build "servers" array // Build "servers" array
ArrayNode servers = mapper.createArrayNode(); ArrayNode servers = mapper.createArrayNode();
List<Map<String, Object>> endpoints = (List<Map<String, Object>>) apiMap.get("endpointURLs"); List<Map<String, Object>> endpoints = (List<Map<String, Object>>) apiMap.get("endpointURLs");
if (endpoints != null) { if (endpoints != null) {
for (Map<String, Object> env : endpoints) { for (Map<String, Object> env : endpoints) {
Map<String, String> urls = (Map<String, String>) env.get("URLs"); Map<String, String> urls = (Map<String, String>) env.get("URLs");
if (urls == null || urls.isEmpty()) if (urls == null || urls.isEmpty())
continue; continue;
ObjectNode server = mapper.createObjectNode(); ObjectNode server = mapper.createObjectNode();
urls.forEach((k, v) -> { urls.forEach((k, v) -> {
if (v != null && !v.isBlank()) { if (v != null && !v.isBlank()) {
if (k.equals("https") || k.equals("wss")) { if (k.equals("https") || k.equals("wss")) {
server.put("url", v); server.put("url", v);
} }
} }
}); });
server.put("description", "Gateway: " + env.getOrDefault("environmentName", "")); server.put("description", "Gateway: " + env.getOrDefault("environmentName", ""));
servers.add(server); servers.add(server);
} }
} }
// Replace "servers" node // Replace "servers" node
swagger.set("servers", servers); swagger.set("servers", servers);
} }
private void addSubscriptionsToProps(Map<String, String> props, Subscriptions subs) { private void addSubscriptionsToProps(Map<String, String> props, Subscriptions subs) {
if (subs == null || subs.getList() == null || subs.getList().isEmpty()) if (subs == null || subs.getList() == null || subs.getList().isEmpty())
return; return;
int i = 1; int i = 1;
for (Subscription sub : subs.getList()) { for (Subscription sub : subs.getList()) {
ApplicationInfo appInfo = sub.getApplicationInfo(); ApplicationInfo appInfo = sub.getApplicationInfo();
if (appInfo == null) if (appInfo == null)
continue; continue;
props.put("subscription" + i, appInfo.getName() + " (Owner: " + appInfo.getSubscriber() + ")"); props.put("subscription" + i, appInfo.getName() + " (Owner: " + appInfo.getSubscriber() + ")");
i++; i++;
} }
} }
private void addEndpointsToProps(Map<String, String> props, Map<String, Object> apiMap) { private void addEndpointsToProps(Map<String, String> props, Map<String, Object> apiMap) {
if (apiMap == null || !apiMap.containsKey("endpointURLs")) if (apiMap == null || !apiMap.containsKey("endpointURLs"))
return; return;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
List<Map<String, Object>> envs = (List<Map<String, Object>>) apiMap.get("endpointURLs"); List<Map<String, Object>> envs = (List<Map<String, Object>>) apiMap.get("endpointURLs");
for (Map<String, Object> env : envs) { for (Map<String, Object> env : envs) {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
Map<String, String> urls = (Map<String, String>) env.get("URLs"); Map<String, String> urls = (Map<String, String>) env.get("URLs");
if (urls == null) if (urls == null)
continue; continue;
urls.forEach((k, v) -> { urls.forEach((k, v) -> {
if (v != null) if (v != null)
props.put(k + " Endpoint", v); props.put(k + " Endpoint", v);
}); });
} }
} }
private void addTagsToProps(Map<String, String> props, List<String> tags) { private void addTagsToProps(Map<String, String> props, List<String> tags) {
if (tags != null && !tags.isEmpty()) { if (tags != null && !tags.isEmpty()) {
props.put("tags", String.join(", ", tags)); props.put("tags", String.join(", ", tags));
} }
} }
private List<ArtifactReference> createReferencesFromZip(List<ZipEntryData> zipEntries, String group, APIInfo api) private List<ArtifactReference> createReferencesFromZip(List<ZipEntryData> zipEntries, String group, APIInfo api)
throws IOException { throws IOException {
List<ArtifactReference> references = new ArrayList<>(); List<ArtifactReference> references = new ArrayList<>();
for (ZipEntryData entry : zipEntries) { for (ZipEntryData entry : zipEntries) {
String artifactId = api.getName() + "/" + api.getVersion() + "/" + entry.getName(); String artifactId = api.getName() + "/" + api.getVersion() + "/" + entry.getName();
try (ByteArrayInputStream is = new ByteArrayInputStream(entry.getContent())) { try (ByteArrayInputStream is = new ByteArrayInputStream(entry.getContent())) {
ArtifactMetaData meta = client.createArtifactWithVersion(entry.getType().toString(), artifactId, ArtifactMetaData meta = client.createArtifactWithVersion(entry.getType().toString(), artifactId,
api.getVersion(), is); api.getVersion(), is);
Map<String, String> props = new LinkedHashMap<>(); Map<String, String> props = new LinkedHashMap<>();
props.put(PARAM_SOURCE_APIM, VERSION_32); props.put(PARAM_SOURCE_APIM, VERSION_32);
setArtifactMetaData(meta, props); setArtifactMetaData(meta, props);
} }
ArtifactReference ref = new ArtifactReference(); ArtifactReference ref = new ArtifactReference();
ref.setName(entry.getName()); ref.setName(entry.getName());
ref.setGroupId(entry.getType().toString()); ref.setGroupId(entry.getType().toString());
ref.setArtifactId(artifactId); ref.setArtifactId(artifactId);
ref.setVersion(api.getVersion()); ref.setVersion(api.getVersion());
references.add(ref); references.add(ref);
} }
return references; return references;
} }
private void addSubscriptionsToReferences(List<ArtifactReference> references, Subscriptions subs, APIInfo api) private void addSubscriptionsToReferences(List<ArtifactReference> references, Subscriptions subs, APIInfo api)
throws Exception { throws Exception {
if (subs == null || subs.getList() == null || subs.getList().isEmpty()) if (subs == null || subs.getList() == null || subs.getList().isEmpty())
return; return;
String artifactId = api.getName() + "/" + api.getVersion() + "/" + ARTIFACT_NAME_SUBSCRIPTIONS; String artifactId = api.getName() + "/" + api.getVersion() + "/" + ARTIFACT_NAME_SUBSCRIPTIONS;
byte[] subsBytes = mapperYaml.writeValueAsBytes(subs); byte[] subsBytes = mapperYaml.writeValueAsBytes(subs);
try (ByteArrayInputStream is = new ByteArrayInputStream(subsBytes)) { try (ByteArrayInputStream is = new ByteArrayInputStream(subsBytes)) {
ArtifactMetaData meta = client.createArtifactWithVersion(ARTIFACT_GROUP_SUBSCRIPTIONS, artifactId, ArtifactMetaData meta = client.createArtifactWithVersion(ARTIFACT_GROUP_SUBSCRIPTIONS, artifactId,
api.getVersion(), is); api.getVersion(), is);
Map<String, String> props = new LinkedHashMap<>(); Map<String, String> props = new LinkedHashMap<>();
props.put(PARAM_SOURCE_APIM, VERSION_32); props.put(PARAM_SOURCE_APIM, VERSION_32);
setArtifactMetaData(meta, props); setArtifactMetaData(meta, props);
} }
ArtifactReference ref = new ArtifactReference(); ArtifactReference ref = new ArtifactReference();
ref.setName(ARTIFACT_NAME_SUBSCRIPTIONS); ref.setName(ARTIFACT_NAME_SUBSCRIPTIONS);
ref.setGroupId(ARTIFACT_GROUP_SUBSCRIPTIONS); ref.setGroupId(ARTIFACT_GROUP_SUBSCRIPTIONS);
ref.setArtifactId(artifactId); ref.setArtifactId(artifactId);
ref.setVersion(api.getVersion()); ref.setVersion(api.getVersion());
references.add(ref); references.add(ref);
} }
private void setArtifactMetaData(ArtifactMetaData meta, Map<String, String> props) { private void setArtifactMetaData(ArtifactMetaData meta, Map<String, String> props) {
EditableMetaData metaData = new EditableMetaData(); EditableMetaData metaData = new EditableMetaData();
metaData.setName(meta.getName()); metaData.setName(meta.getName());
metaData.setDescription(meta.getDescription()); metaData.setDescription(meta.getDescription());
if (props != null) if (props != null)
metaData.setProperties(props); metaData.setProperties(props);
client.updateArtifactMetaData(meta.getGroupId(), meta.getId(), metaData); client.updateArtifactMetaData(meta.getGroupId(), meta.getId(), metaData);
} }
private void createRule(ArtifactMetaData meta, String config, RuleType type) { private void createRule(ArtifactMetaData meta, String config, RuleType type) {
Rule rule = new Rule(); Rule rule = new Rule();
rule.setConfig(config); rule.setConfig(config);
rule.setType(type); rule.setType(type);
client.createArtifactRule(meta.getGroupId(), meta.getId(), rule); client.createArtifactRule(meta.getGroupId(), meta.getId(), rule);
} }
} }

View File

@ -1,328 +1,328 @@
package cz.trask.migration.impl.v45; package cz.trask.migration.impl.v45;
import java.io.ByteArrayOutputStream; import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.core.type.TypeReference;
import cz.trask.migration.AbstractProcess; import cz.trask.migration.AbstractProcess;
import cz.trask.migration.mapper.ApiDefinitionMapper32to45; import cz.trask.migration.mapper.ApiDefinitionMapper32to45;
import cz.trask.migration.model.FileType; import cz.trask.migration.model.FileType;
import cz.trask.migration.model.HttpResponse; import cz.trask.migration.model.HttpResponse;
import cz.trask.migration.model.TokenResponse; import cz.trask.migration.model.TokenResponse;
import cz.trask.migration.model.v32.ApiDefinition32; import cz.trask.migration.model.v32.ApiDefinition32;
import cz.trask.migration.model.v32.Documents32; import cz.trask.migration.model.v32.Documents32;
import cz.trask.migration.model.v32.HostInfo32; import cz.trask.migration.model.v32.HostInfo32;
import cz.trask.migration.model.v45.ApiDefinition45; import cz.trask.migration.model.v45.ApiDefinition45;
import cz.trask.migration.model.v45.Documents45; import cz.trask.migration.model.v45.Documents45;
import cz.trask.migration.model.v45.EndpointCertificates45; import cz.trask.migration.model.v45.EndpointCertificates45;
import cz.trask.migration.model.v45.OperationPolicySpecification45; import cz.trask.migration.model.v45.OperationPolicySpecification45;
import io.apicurio.registry.rest.client.RegistryClient; import io.apicurio.registry.rest.client.RegistryClient;
import io.apicurio.registry.rest.client.RegistryClientFactory; import io.apicurio.registry.rest.client.RegistryClientFactory;
import io.apicurio.registry.rest.v2.beans.ArtifactMetaData; import io.apicurio.registry.rest.v2.beans.ArtifactMetaData;
import io.apicurio.registry.rest.v2.beans.ArtifactReference; import io.apicurio.registry.rest.v2.beans.ArtifactReference;
import io.apicurio.registry.rest.v2.beans.ArtifactSearchResults; import io.apicurio.registry.rest.v2.beans.ArtifactSearchResults;
import io.apicurio.registry.rest.v2.beans.SearchedArtifact; import io.apicurio.registry.rest.v2.beans.SearchedArtifact;
import io.apicurio.registry.rest.v2.beans.SearchedVersion; import io.apicurio.registry.rest.v2.beans.SearchedVersion;
import io.apicurio.registry.rest.v2.beans.VersionSearchResults; import io.apicurio.registry.rest.v2.beans.VersionSearchResults;
public class ExportToWso2FromV32 extends AbstractProcess { public class ExportToWso2FromV32 extends AbstractProcess {
private static final Logger log = LogManager.getLogger(ExportToWso2FromV32.class); private static final Logger log = LogManager.getLogger(ExportToWso2FromV32.class);
private final AtomicInteger apiCounter = new AtomicInteger(1); private final AtomicInteger apiCounter = new AtomicInteger(1);
private final RegistryClient client; private final RegistryClient client;
public ExportToWso2FromV32() throws Exception { public ExportToWso2FromV32() throws Exception {
this.client = RegistryClientFactory.create(config.getApicurio().getApiUrl()); this.client = RegistryClientFactory.create(config.getApicurio().getApiUrl());
} }
/** /**
* Main entry point for the import process. * Main entry point for the import process.
* *
* @throws RuntimeException if any error occurs * @throws RuntimeException if any error occurs
*/ */
public void process() { public void process() {
try { try {
log.info("Starting API export to WSO2 from Apicurio..."); log.info("Starting API export to WSO2 from Apicurio...");
TokenResponse token = authenticateToWso2AndGetToken(); TokenResponse token = authenticateToWso2AndGetToken();
ArtifactSearchResults apis = client.searchArtifacts(config.getApicurio().getDefaultApiGroup(), null, null, ArtifactSearchResults apis = client.searchArtifacts(config.getApicurio().getDefaultApiGroup(), null, null,
null, null, null, null, null, null); null, null, null, null, null, null);
log.info("Found {} APIs", apis.getCount()); log.info("Found {} APIs", apis.getCount());
int maxThreads = config.getMaxThreads(); int maxThreads = config.getMaxThreads();
ExecutorService executor = Executors.newFixedThreadPool(maxThreads); ExecutorService executor = Executors.newFixedThreadPool(maxThreads);
for (SearchedArtifact api : apis.getArtifacts()) { for (SearchedArtifact api : apis.getArtifacts()) {
final int index = apiCounter.getAndIncrement(); final int index = apiCounter.getAndIncrement();
executor.submit(() -> processApi(api, token, index, apis.getCount())); executor.submit(() -> processApi(api, token, index, apis.getCount()));
} }
executor.shutdown(); executor.shutdown();
if (!executor.awaitTermination(10, TimeUnit.MINUTES)) { if (!executor.awaitTermination(10, TimeUnit.MINUTES)) {
log.warn("Timeout waiting for API import tasks to finish"); log.warn("Timeout waiting for API import tasks to finish");
} }
log.info("Finished processing APIs."); log.info("Finished processing APIs.");
} catch (Exception e) { } catch (Exception e) {
log.error("Error while exporting APIs.", e); log.error("Error while exporting APIs.", e);
throw new RuntimeException("Export failed", e); throw new RuntimeException("Export failed", e);
} }
} }
private void processApi(SearchedArtifact api, TokenResponse tokenResponse, int index, int total) { private void processApi(SearchedArtifact api, TokenResponse tokenResponse, int index, int total) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
try { try {
log.info("Processing API {} of {}", index, total); log.info("Processing API {} of {}", index, total);
VersionSearchResults versions = client.listArtifactVersions(config.getApicurio().getDefaultApiGroup(), VersionSearchResults versions = client.listArtifactVersions(config.getApicurio().getDefaultApiGroup(),
api.getId(), null, null); api.getId(), null, null);
for (SearchedVersion ver : versions.getVersions()) { for (SearchedVersion ver : versions.getVersions()) {
log.info(" - Found version: {}", ver.getVersion()); log.info(" - Found version: {}", ver.getVersion());
List<ArtifactReference> ref = client.getArtifactReferencesByCoordinates( List<ArtifactReference> ref = client.getArtifactReferencesByCoordinates(
config.getApicurio().getDefaultApiGroup(), api.getId(), ver.getVersion()); config.getApicurio().getDefaultApiGroup(), api.getId(), ver.getVersion());
if (ref != null && !ref.isEmpty()) { if (ref != null && !ref.isEmpty()) {
log.info("Artifact has {} references", ref.size()); log.info("Artifact has {} references", ref.size());
byte[] data = prepareApiZipFile32to45(client, ver, ref); byte[] data = prepareApiZipFile32to45(client, ver, ref);
String fileName = api.getName() + "-" + ver.getVersion() + ".zip"; String fileName = api.getName() + "-" + ver.getVersion() + ".zip";
FileOutputStream fos = new FileOutputStream(fileName); FileOutputStream fos = new FileOutputStream(fileName);
fos.write(data); fos.write(data);
fos.flush(); fos.flush();
fos.close(); fos.close();
// System.exit(0); // System.exit(0);
if (data != null && data.length > 0 && fileName != null && !fileName.isEmpty()) { if (data != null && data.length > 0 && fileName != null && !fileName.isEmpty()) {
int responseCode = publishApiToWso2(fileName, data, tokenResponse); int responseCode = publishApiToWso2(fileName, data, tokenResponse);
if (responseCode == 200 || responseCode == 201) { if (responseCode == 200 || responseCode == 201) {
log.info(" - API version {} imported successfully", ver.getVersion()); log.info(" - API version {} imported successfully", ver.getVersion());
} else { } else {
log.warn(" - API version {} import failed with response code {}", ver.getVersion(), log.warn(" - API version {} import failed with response code {}", ver.getVersion(),
responseCode); responseCode);
} }
} }
} }
} }
long end = System.currentTimeMillis(); long end = System.currentTimeMillis();
log.info("Finished processing API {} of {} in {} ms", index, total, (end - start)); log.info("Finished processing API {} of {} in {} ms", index, total, (end - start));
} catch (Exception e) { } catch (Exception e) {
log.error("IO error while importing API {}: {}", api.getId(), e.getMessage(), e); log.error("IO error while importing API {}: {}", api.getId(), e.getMessage(), e);
} }
} }
/* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */
/* Helper methods */ /* Helper methods */
/* --------------------------------------------------------------------- */ /* --------------------------------------------------------------------- */
private int publishApiToWso2(String fileName, byte[] data, TokenResponse tokenResponse) { private int publishApiToWso2(String fileName, byte[] data, TokenResponse tokenResponse) {
int responseCode = -1; int responseCode = -1;
try { try {
String url = config.getTarget().getPublisherApiUrl() String url = config.getTarget().getPublisherApiUrl()
.concat(String.format("?preserveProvider=false&overwrite=true")); .concat(String.format("?preserveProvider=false&overwrite=true"));
log.info("API Import URL: " + url); log.info("API Import URL: " + url);
Map<String, String> httpHeaders = new HashMap<>(); Map<String, String> httpHeaders = new HashMap<>();
httpHeaders.put("Authorization", "Bearer " + tokenResponse.getAccess_token()); httpHeaders.put("Authorization", "Bearer " + tokenResponse.getAccess_token());
HttpResponse response = makeFileRequest("POST", url, httpHeaders, data, fileName); HttpResponse response = makeFileRequest("POST", url, httpHeaders, data, fileName);
responseCode = response.getResponseCode(); responseCode = response.getResponseCode();
if (response.getResponseCode() != 201 && response.getResponseCode() != 200) { if (response.getResponseCode() != 201 && response.getResponseCode() != 200) {
log.info("Cannot import API file: " + fileName + ", response code: " + response.getResponseCode()); log.info("Cannot import API file: " + fileName + ", response code: " + response.getResponseCode());
} }
} catch (Exception e) { } catch (Exception e) {
log.error("IO error while importing API file: " + fileName + ", error: " + e.getMessage(), e); log.error("IO error while importing API file: " + fileName + ", error: " + e.getMessage(), e);
} }
return responseCode; return responseCode;
} }
public byte[] prepareApiZipFile32to45(RegistryClient client, SearchedVersion ver, List<ArtifactReference> ref) public byte[] prepareApiZipFile32to45(RegistryClient client, SearchedVersion ver, List<ArtifactReference> ref)
throws Exception { throws Exception {
String baseDir = ver.getName() + "-" + ver.getVersion() + "/"; String baseDir = ver.getName() + "-" + ver.getVersion() + "/";
try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos)) { ZipOutputStream zos = new ZipOutputStream(baos)) {
ApiDefinition32 apiDef = null; ApiDefinition32 apiDef = null;
String contentStr = null; String contentStr = null;
for (ArtifactReference r : ref) { for (ArtifactReference r : ref) {
log.info(" - Reference: {} {} {}", r.getGroupId(), r.getArtifactId(), r.getVersion()); log.info(" - Reference: {} {} {}", r.getGroupId(), r.getArtifactId(), r.getVersion());
ArtifactMetaData amd = client.getArtifactMetaData(r.getGroupId(), r.getArtifactId()); ArtifactMetaData amd = client.getArtifactMetaData(r.getGroupId(), r.getArtifactId());
byte[] content = client.getContentByGlobalId(amd.getGlobalId()).readAllBytes(); byte[] content = client.getContentByGlobalId(amd.getGlobalId()).readAllBytes();
String subDir = ""; String subDir = "";
boolean appendFile = true; boolean appendFile = true;
String specialName = null; String specialName = null;
if (FileType.POLICY_IN.toString().equals(amd.getGroupId()) if (FileType.POLICY_IN.toString().equals(amd.getGroupId())
|| FileType.POLICY_OUT.toString().equals(amd.getGroupId()) || FileType.POLICY_OUT.toString().equals(amd.getGroupId())
|| FileType.POLICY_FAULT.toString().equals(amd.getGroupId())) { || FileType.POLICY_FAULT.toString().equals(amd.getGroupId())) {
subDir = "Policies/"; subDir = "Policies/";
specialName = r.getName().replace(".xml", "_v1_api.j2"); specialName = r.getName().replace(".xml", "_v1_api.j2");
content = convertSequenceToPolicy(content); content = convertSequenceToPolicy(content);
addGenericPolicyMetadata(zos, baseDir + subDir, specialName.replace(".j2", ".yaml"), r); addGenericPolicyMetadata(zos, baseDir + subDir, specialName.replace(".j2", ".yaml"), r);
} else if (FileType.OPENAPI.toString().equals(amd.getGroupId())) { } else if (FileType.OPENAPI.toString().equals(amd.getGroupId())) {
subDir = "Definitions/"; subDir = "Definitions/";
contentStr = new String(content); contentStr = new String(content);
} else if (FileType.CERTIFICATE.toString().equals(amd.getGroupId())) { } else if (FileType.CERTIFICATE.toString().equals(amd.getGroupId())) {
subDir = "Endpoint-certificates/"; subDir = "Endpoint-certificates/";
content = convertCertificateToEPCertificate(zos, baseDir + subDir, content); content = convertCertificateToEPCertificate(zos, baseDir + subDir, content);
} else if (FileType.APIDEF.toString().equals(amd.getGroupId())) { } else if (FileType.APIDEF.toString().equals(amd.getGroupId())) {
apiDef = mapperYaml.readValue(content, ApiDefinition32.class); apiDef = mapperYaml.readValue(content, ApiDefinition32.class);
appendFile = false; appendFile = false;
} else if (FileType.DOCUMENTATION.toString().equals(amd.getGroupId())) { } else if (FileType.DOCUMENTATION.toString().equals(amd.getGroupId())) {
subDir = "Docs/"; subDir = "Docs/";
if (content != null && content.length > 0) { if (content != null && content.length > 0) {
List<Documents32> docs = mapperYaml.readValue(content, new TypeReference<List<Documents32>>() { List<Documents32> docs = mapperYaml.readValue(content, new TypeReference<List<Documents32>>() {
}); });
for (Documents32 doc : docs) { for (Documents32 doc : docs) {
convertAndAddDocument(zos, baseDir + subDir, doc); convertAndAddDocument(zos, baseDir + subDir, doc);
} }
} }
appendFile = false; appendFile = false;
} }
if (appendFile) { if (appendFile) {
String fileName = baseDir + subDir + (specialName != null ? specialName : r.getName()); String fileName = baseDir + subDir + (specialName != null ? specialName : r.getName());
log.info(" - Adding file: {}", fileName); log.info(" - Adding file: {}", fileName);
zos.putNextEntry(new ZipEntry(fileName)); zos.putNextEntry(new ZipEntry(fileName));
zos.write(content); zos.write(content);
zos.closeEntry(); zos.closeEntry();
} }
} }
if (apiDef != null && contentStr != null) { if (apiDef != null && contentStr != null) {
ApiDefinition45 apiDef45 = ApiDefinitionMapper32to45.map(apiDef, contentStr); ApiDefinition45 apiDef45 = ApiDefinitionMapper32to45.map(apiDef, contentStr);
byte[] content = mapperYaml.writeValueAsBytes(apiDef45); byte[] content = mapperYaml.writeValueAsBytes(apiDef45);
zos.putNextEntry(new ZipEntry(baseDir.concat("api.yaml"))); zos.putNextEntry(new ZipEntry(baseDir.concat("api.yaml")));
zos.write(content); zos.write(content);
zos.closeEntry(); zos.closeEntry();
} }
zos.finish(); zos.finish();
return baos.toByteArray(); return baos.toByteArray();
} }
} }
private void convertAndAddDocument(ZipOutputStream zos, String subDir, Documents32 doc) throws Exception { private void convertAndAddDocument(ZipOutputStream zos, String subDir, Documents32 doc) throws Exception {
Documents45 doc45 = new Documents45(); Documents45 doc45 = new Documents45();
Documents45.Data doc45Data = new Documents45.Data(); Documents45.Data doc45Data = new Documents45.Data();
doc45Data.setName(doc.getName()); doc45Data.setName(doc.getName());
doc45Data.setType(doc.getType()); doc45Data.setType(doc.getType());
doc45Data.setSummary(doc.getSummary()); doc45Data.setSummary(doc.getSummary());
doc45Data.setSourceType(doc.getSourceType()); doc45Data.setSourceType(doc.getSourceType());
doc45Data.setSourceUrl(doc.getSourceUrl()); doc45Data.setSourceUrl(doc.getSourceUrl());
doc45Data.setFileName(doc.getFileName()); doc45Data.setFileName(doc.getFileName());
doc45Data.setInlineContent(doc.getInlineContent()); doc45Data.setInlineContent(doc.getInlineContent());
doc45Data.setOtherTypeName(doc.getOtherTypeName()); doc45Data.setOtherTypeName(doc.getOtherTypeName());
doc45Data.setVisibility(doc.getVisibility()); doc45Data.setVisibility(doc.getVisibility());
doc45Data.setCreatedTime(doc.getCreatedTime()); doc45Data.setCreatedTime(doc.getCreatedTime());
doc45Data.setCreatedBy(doc.getCreatedBy()); doc45Data.setCreatedBy(doc.getCreatedBy());
doc45Data.setLastUpdatedTime(doc.getLastUpdatedTime()); doc45Data.setLastUpdatedTime(doc.getLastUpdatedTime());
doc45Data.setLastUpdatedBy(doc.getLastUpdatedBy()); doc45Data.setLastUpdatedBy(doc.getLastUpdatedBy());
doc45.setData(doc45Data); doc45.setData(doc45Data);
String fileName = subDir + doc.getName() + "/" + DEFAULT_DOC_FILE_NAME; String fileName = subDir + doc.getName() + "/" + DEFAULT_DOC_FILE_NAME;
zos.putNextEntry(new ZipEntry(fileName)); zos.putNextEntry(new ZipEntry(fileName));
zos.write(mapperYaml.writeValueAsBytes(doc45)); zos.write(mapperYaml.writeValueAsBytes(doc45));
zos.closeEntry(); zos.closeEntry();
} }
private byte[] convertCertificateToEPCertificate(ZipOutputStream zos, String subDir, byte[] content) { private byte[] convertCertificateToEPCertificate(ZipOutputStream zos, String subDir, byte[] content) {
if (content != null && content.length > 0) { if (content != null && content.length > 0) {
try { try {
List<HostInfo32> epc32 = mapperYaml.readValue(content, new TypeReference<List<HostInfo32>>() { List<HostInfo32> epc32 = mapperYaml.readValue(content, new TypeReference<List<HostInfo32>>() {
}); });
EndpointCertificates45 epc45 = new EndpointCertificates45(); EndpointCertificates45 epc45 = new EndpointCertificates45();
epc45.setType("endpoint_certificates"); epc45.setType("endpoint_certificates");
epc45.setVersion("v4.5.0"); epc45.setVersion("v4.5.0");
List<EndpointCertificates45.EndpointCertificate> certs = new ArrayList<>(); List<EndpointCertificates45.EndpointCertificate> certs = new ArrayList<>();
for (HostInfo32 hi : epc32) { for (HostInfo32 hi : epc32) {
EndpointCertificates45.EndpointCertificate cert = new EndpointCertificates45.EndpointCertificate(); EndpointCertificates45.EndpointCertificate cert = new EndpointCertificates45.EndpointCertificate();
cert.setAlias(hi.getAlias()); cert.setAlias(hi.getAlias());
cert.setEndpoint(hi.getHostName()); cert.setEndpoint(hi.getHostName());
cert.setCertificate(hi.getAlias().concat(".crt")); cert.setCertificate(hi.getAlias().concat(".crt"));
cert.setTenantId(0); cert.setTenantId(0);
certs.add(cert); certs.add(cert);
zos.putNextEntry(new ZipEntry(subDir + cert.getCertificate())); zos.putNextEntry(new ZipEntry(subDir + cert.getCertificate()));
zos.write("-----BEGIN CERTIFICATE-----\r\n".concat(hi.getCertificate()) zos.write("-----BEGIN CERTIFICATE-----\r\n".concat(hi.getCertificate())
.concat("\r\n-----END CERTIFICATE-----").getBytes()); .concat("\r\n-----END CERTIFICATE-----").getBytes());
zos.closeEntry(); zos.closeEntry();
} }
epc45.setData(certs); epc45.setData(certs);
return mapperYaml.writeValueAsBytes(epc45); return mapperYaml.writeValueAsBytes(epc45);
} catch (Exception e) { } catch (Exception e) {
log.error("Error converting endpoint certificate: {}", e.getMessage(), e); log.error("Error converting endpoint certificate: {}", e.getMessage(), e);
} }
} }
return null; return null;
} }
private void addGenericPolicyMetadata(ZipOutputStream zos, String subDir, String fileName, ArtifactReference r) private void addGenericPolicyMetadata(ZipOutputStream zos, String subDir, String fileName, ArtifactReference r)
throws Exception { throws Exception {
OperationPolicySpecification45 ops = new OperationPolicySpecification45(); OperationPolicySpecification45 ops = new OperationPolicySpecification45();
ops.setVersion("v4.5.0"); ops.setVersion("v4.5.0");
ops.setType("operation_policy_specification"); ops.setType("operation_policy_specification");
OperationPolicySpecification45.Data data = new OperationPolicySpecification45.Data(); OperationPolicySpecification45.Data data = new OperationPolicySpecification45.Data();
data.setName(r.getName().replace(".xml", "")); data.setName(r.getName().replace(".xml", ""));
data.setCategory("Mediation"); data.setCategory("Mediation");
data.setDescription("Generic Migrated policy " + r.getName()); data.setDescription("Generic Migrated policy " + r.getName());
data.setDisplayName(r.getName().replace(".xml", "")); data.setDisplayName(r.getName().replace(".xml", ""));
data.setVersion("v1"); data.setVersion("v1");
data.setApplicableFlows(new ArrayList<>()); data.setApplicableFlows(new ArrayList<>());
data.getApplicableFlows().add("request"); data.getApplicableFlows().add("request");
data.getApplicableFlows().add("response"); data.getApplicableFlows().add("response");
data.setSupportedGateways(new ArrayList<>()); data.setSupportedGateways(new ArrayList<>());
data.getSupportedGateways().add("Synapse"); data.getSupportedGateways().add("Synapse");
data.setSupportedApiTypes(new ArrayList<>()); data.setSupportedApiTypes(new ArrayList<>());
data.getSupportedApiTypes().add("HTTP"); data.getSupportedApiTypes().add("HTTP");
data.getSupportedApiTypes().add("SOAP"); data.getSupportedApiTypes().add("SOAP");
data.setPolicyAttributes(new ArrayList<>()); data.setPolicyAttributes(new ArrayList<>());
ops.setData(data); ops.setData(data);
zos.putNextEntry(new ZipEntry(subDir + fileName)); zos.putNextEntry(new ZipEntry(subDir + fileName));
zos.write(mapperYaml.writeValueAsBytes(ops)); zos.write(mapperYaml.writeValueAsBytes(ops));
zos.closeEntry(); zos.closeEntry();
} }
private byte[] convertSequenceToPolicy(byte[] content) throws Exception { private byte[] convertSequenceToPolicy(byte[] content) throws Exception {
if (content != null && content.length > 0) { if (content != null && content.length > 0) {
Pattern pattern = Pattern.compile("<sequence[^>]*>(.*?)</sequence>", Pattern.DOTALL); Pattern pattern = Pattern.compile("<sequence[^>]*>(.*?)</sequence>", Pattern.DOTALL);
Matcher matcher = pattern.matcher(new String(content)); Matcher matcher = pattern.matcher(new String(content));
// Replace the entire sequence block with its inner content // Replace the entire sequence block with its inner content
String result = matcher.replaceAll("$1").trim(); String result = matcher.replaceAll("$1").trim();
return result.getBytes(); return result.getBytes();
} }
return null; return null;
} }
} }

View File

@ -1,346 +1,346 @@
package cz.trask.migration.mapper; package cz.trask.migration.mapper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.JsonNode;
import cz.trask.migration.AbstractProcess; import cz.trask.migration.AbstractProcess;
import cz.trask.migration.model.v32.ApiDefinition32; import cz.trask.migration.model.v32.ApiDefinition32;
import cz.trask.migration.model.v45.ApiDefinition45; import cz.trask.migration.model.v45.ApiDefinition45;
import cz.trask.migration.model.v45.ApiDefinition45.ApiPolicies; import cz.trask.migration.model.v45.ApiDefinition45.ApiPolicies;
import cz.trask.migration.model.v45.ApiDefinition45.Operation; import cz.trask.migration.model.v45.ApiDefinition45.Operation;
import cz.trask.migration.model.v45.ApiDefinition45.OperationPolicies; import cz.trask.migration.model.v45.ApiDefinition45.OperationPolicies;
public class ApiDefinitionMapper32to45 { public class ApiDefinitionMapper32to45 {
public static ApiDefinition45 map(ApiDefinition32 oldApi, String swagger) throws Exception { public static ApiDefinition45 map(ApiDefinition32 oldApi, String swagger) throws Exception {
if (oldApi == null) if (oldApi == null)
return null; return null;
ApiDefinition45 newApi = new ApiDefinition45(); ApiDefinition45 newApi = new ApiDefinition45();
newApi.setType("api"); newApi.setType("api");
newApi.setVersion("v4.5.0"); newApi.setVersion("v4.5.0");
ApiDefinition45.DataSection data = new ApiDefinition45.DataSection(); ApiDefinition45.DataSection data = new ApiDefinition45.DataSection();
Map<String, Object> swaggerData = AbstractProcess.mapperYaml.readValue(swagger, Map.class); Map<String, Object> swaggerData = AbstractProcess.mapperYaml.readValue(swagger, Map.class);
// ---------- základní metadata ---------- // ---------- základní metadata ----------
data.setId(oldApi.getUuid()); data.setId(oldApi.getUuid());
data.setName(oldApi.getId() != null ? oldApi.getId().getApiName() : null); data.setName(oldApi.getId() != null ? oldApi.getId().getApiName() : null);
data.setDescription(swaggerData.get("info") != null data.setDescription(swaggerData.get("info") != null
? ((Map<String, Object>) swaggerData.get("info")).get("description") != null ? ((Map<String, Object>) swaggerData.get("info")).get("description") != null
? ((Map<String, Object>) swaggerData.get("info")).get("description").toString() ? ((Map<String, Object>) swaggerData.get("info")).get("description").toString()
: "" : ""
: ""); : "");
data.setVersion(oldApi.getId() != null ? oldApi.getId().getVersion() : null); data.setVersion(oldApi.getId() != null ? oldApi.getId().getVersion() : null);
data.setProvider(oldApi.getId() != null ? oldApi.getId().getProviderName() : null); data.setProvider(oldApi.getId() != null ? oldApi.getId().getProviderName() : null);
//data.setContext(swaggerData.get("basePath") != null ? swaggerData.get("basePath").toString() : ""); //data.setContext(swaggerData.get("basePath") != null ? swaggerData.get("basePath").toString() : "");
data.setContext(oldApi.getContext()); data.setContext(oldApi.getContext());
data.setLifeCycleStatus(oldApi.getStatus()); data.setLifeCycleStatus(oldApi.getStatus());
data.setDefaultVersion(oldApi.isDefaultVersion()); data.setDefaultVersion(oldApi.isDefaultVersion());
data.setRevision(false); data.setRevision(false);
data.setEnableSchemaValidation(oldApi.isEnableSchemaValidation()); data.setEnableSchemaValidation(oldApi.isEnableSchemaValidation());
data.setAuthorizationHeader(oldApi.getAuthorizationHeader()); data.setAuthorizationHeader(oldApi.getAuthorizationHeader());
data.setTransport( data.setTransport(
oldApi.getTransports() != null ? List.of(oldApi.getTransports().split(",")) : Collections.emptyList()); oldApi.getTransports() != null ? List.of(oldApi.getTransports().split(",")) : Collections.emptyList());
data.setTags(oldApi.getTags()); data.setTags(oldApi.getTags());
data.setVisibility(oldApi.getVisibility().toUpperCase()); data.setVisibility(oldApi.getVisibility().toUpperCase());
data.setVisibleRoles(Collections.emptyList()); data.setVisibleRoles(Collections.emptyList());
data.setVisibleTenants(Collections.emptyList()); data.setVisibleTenants(Collections.emptyList());
data.setAccessControl("NONE"); data.setAccessControl("NONE");
data.setAccessControlRoles(Collections.emptyList()); data.setAccessControlRoles(Collections.emptyList());
data.setOrganizationPolicies(Collections.emptyList()); data.setOrganizationPolicies(Collections.emptyList());
data.setType(oldApi.getType()); data.setType(oldApi.getType());
data.setAudiences(Arrays.asList("all")); data.setAudiences(Arrays.asList("all"));
List<String> policies = new ArrayList<>(); List<String> policies = new ArrayList<>();
for (ApiDefinition32.Tier tier : oldApi.getAvailableTiers()) { for (ApiDefinition32.Tier tier : oldApi.getAvailableTiers()) {
if (tier.getName() != null && !tier.getName().isEmpty()) { if (tier.getName() != null && !tier.getName().isEmpty()) {
policies.add(tier.getName()); policies.add(tier.getName());
} }
} }
data.setPolicies(policies); data.setPolicies(policies);
if (oldApi.getApiSecurity() != null && !oldApi.getApiSecurity().isEmpty()) { if (oldApi.getApiSecurity() != null && !oldApi.getApiSecurity().isEmpty()) {
data.setSecurityScheme( data.setSecurityScheme(
Arrays.stream(oldApi.getApiSecurity().split(",")).map(String::trim).collect(Collectors.toList())); Arrays.stream(oldApi.getApiSecurity().split(",")).map(String::trim).collect(Collectors.toList()));
} else { } else {
data.setSecurityScheme(Collections.emptyList()); data.setSecurityScheme(Collections.emptyList());
} }
data.setApiKeyHeader("ApiKey"); data.setApiKeyHeader("ApiKey");
data.setOrganizationId("carbon.super"); data.setOrganizationId("carbon.super");
data.setAsyncTransportProtocols(Collections.emptyList()); data.setAsyncTransportProtocols(Collections.emptyList());
data.setCategories(Collections.emptyList()); data.setCategories(Collections.emptyList());
data.setSubtypeConfiguration(new ApiDefinition45.SubtypeConfiguration()); data.setSubtypeConfiguration(new ApiDefinition45.SubtypeConfiguration());
data.getSubtypeConfiguration().setSubtype("DEFAULT"); data.getSubtypeConfiguration().setSubtype("DEFAULT");
data.setScopes(new ArrayList<>()); data.setScopes(new ArrayList<>());
data.setWebsubSubscriptionConfiguration(new ApiDefinition45.WebsubSubscriptionConfiguration()); data.setWebsubSubscriptionConfiguration(new ApiDefinition45.WebsubSubscriptionConfiguration());
data.getWebsubSubscriptionConfiguration().setEnable(false); data.getWebsubSubscriptionConfiguration().setEnable(false);
data.getWebsubSubscriptionConfiguration().setSecret(""); data.getWebsubSubscriptionConfiguration().setSecret("");
data.getWebsubSubscriptionConfiguration().setSigningAlgorithm("SHA1"); data.getWebsubSubscriptionConfiguration().setSigningAlgorithm("SHA1");
data.getWebsubSubscriptionConfiguration().setSignatureHeader("x-hub-signature"); data.getWebsubSubscriptionConfiguration().setSignatureHeader("x-hub-signature");
// ---------- cache ---------- // ---------- cache ----------
data.setResponseCachingEnabled( data.setResponseCachingEnabled(
oldApi.getResponseCache() != null && !"disabled".equalsIgnoreCase(oldApi.getResponseCache())); oldApi.getResponseCache() != null && !"disabled".equalsIgnoreCase(oldApi.getResponseCache()));
data.setCacheTimeout(oldApi.getCacheTimeout()); data.setCacheTimeout(oldApi.getCacheTimeout());
// ---------- CORS ---------- // ---------- CORS ----------
data.setCorsConfiguration(mapCors(oldApi.getCorsConfiguration())); data.setCorsConfiguration(mapCors(oldApi.getCorsConfiguration()));
// ---------- endpoint ---------- // ---------- endpoint ----------
data.setEndpointConfig(oldApi.getEndpointConfig()); data.setEndpointConfig(oldApi.getEndpointConfig());
data.setEndpointImplementationType(oldApi.getImplementation()); data.setEndpointImplementationType(oldApi.getImplementation());
// ---------- API policies ---------- // ---------- API policies ----------
data.setApiPolicies(mapApiPolicies(oldApi)); data.setApiPolicies(mapApiPolicies(oldApi));
// data.setApiPolicies(mapApiPolicies(null)); // data.setApiPolicies(mapApiPolicies(null));
// ---------- key managers ---------- // ---------- key managers ----------
data.setKeyManagers(oldApi.getKeyManagers()); data.setKeyManagers(oldApi.getKeyManagers());
// ---------- advertise info ---------- // ---------- advertise info ----------
ApiDefinition45.AdvertiseInfo ai = new ApiDefinition45.AdvertiseInfo(); ApiDefinition45.AdvertiseInfo ai = new ApiDefinition45.AdvertiseInfo();
ai.setAdvertised(oldApi.isAdvertiseOnly()); ai.setAdvertised(oldApi.isAdvertiseOnly());
ai.setApiOwner(oldApi.getId() != null ? oldApi.getId().getProviderName() : null); ai.setApiOwner(oldApi.getId() != null ? oldApi.getId().getProviderName() : null);
ai.setVendor("WSO2"); ai.setVendor("WSO2");
data.setAdvertiseInfo(ai); data.setAdvertiseInfo(ai);
data.setVisibleOrganizations(Arrays.asList("none")); data.setVisibleOrganizations(Arrays.asList("none"));
// ---------- gateway ---------- // ---------- gateway ----------
data.setGatewayVendor("wso2"); data.setGatewayVendor("wso2");
data.setGatewayType("wso2/synapse"); data.setGatewayType("wso2/synapse");
// ---------- business & monetization ---------- // ---------- business & monetization ----------
data.setBusinessInformation(new HashMap<>()); data.setBusinessInformation(new HashMap<>());
data.getBusinessInformation().put("businessOwner", oldApi.getBusinessOwner()); data.getBusinessInformation().put("businessOwner", oldApi.getBusinessOwner());
data.getBusinessInformation().put("businessOwnerEmail", oldApi.getBusinessOwnerEmail()); data.getBusinessInformation().put("businessOwnerEmail", oldApi.getBusinessOwnerEmail());
data.getBusinessInformation().put("technicalOwner", oldApi.getTechnicalOwner()); data.getBusinessInformation().put("technicalOwner", oldApi.getTechnicalOwner());
data.getBusinessInformation().put("technicalOwnerEmail", oldApi.getTechnicalOwnerEmail()); data.getBusinessInformation().put("technicalOwnerEmail", oldApi.getTechnicalOwnerEmail());
// ---------- additional properties ---------- // ---------- additional properties ----------
data.setAdditionalProperties(mapAdditionalProperties(oldApi.getAdditionalProperties())); data.setAdditionalProperties(mapAdditionalProperties(oldApi.getAdditionalProperties()));
data.setAdditionalPropertiesMap(mapAdditionalPropertiesMap(oldApi.getAdditionalProperties())); data.setAdditionalPropertiesMap(mapAdditionalPropertiesMap(oldApi.getAdditionalProperties()));
// ---------- subscription ---------- // ---------- subscription ----------
data.setSubscriptionAvailability(oldApi.getSubscriptionAvailability().toUpperCase()); data.setSubscriptionAvailability(oldApi.getSubscriptionAvailability().toUpperCase());
data.setSubscriptionAvailableTenants(Collections.emptyList()); data.setSubscriptionAvailableTenants(Collections.emptyList());
// ---------- operations ---------- // ---------- operations ----------
data.setOperations(mapOperations(swagger)); data.setOperations(mapOperations(swagger));
// ---------- additional metadata ---------- // ---------- additional metadata ----------
data.setCreatedTime(oldApi.getCreatedTime()); data.setCreatedTime(oldApi.getCreatedTime());
data.setLastUpdatedTime(oldApi.getLastUpdated()); data.setLastUpdatedTime(oldApi.getLastUpdated());
// ---------- mediace ---------- // ---------- mediace ----------
data.setMediationPolicies(oldApi.getDocuments()); data.setMediationPolicies(oldApi.getDocuments());
newApi.setData(data); newApi.setData(data);
return newApi; return newApi;
} }
private static List<Object> mapAdditionalProperties(Map<String, Object> additionalProperties) { private static List<Object> mapAdditionalProperties(Map<String, Object> additionalProperties) {
if (additionalProperties != null && !additionalProperties.isEmpty()) { if (additionalProperties != null && !additionalProperties.isEmpty()) {
List<Object> list = new ArrayList<>(); List<Object> list = new ArrayList<>();
for (Map.Entry<String, Object> entry : additionalProperties.entrySet()) { for (Map.Entry<String, Object> entry : additionalProperties.entrySet()) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("name", entry.getKey()); map.put("name", entry.getKey());
map.put("value", entry.getValue()); map.put("value", entry.getValue());
map.put("display", "false"); map.put("display", "false");
list.add(map); list.add(map);
} }
return list; return list;
} }
return null; return null;
} }
private static Map<String, Object> mapAdditionalPropertiesMap(Map<String, Object> additionalProperties) { private static Map<String, Object> mapAdditionalPropertiesMap(Map<String, Object> additionalProperties) {
if (additionalProperties != null && !additionalProperties.isEmpty()) { if (additionalProperties != null && !additionalProperties.isEmpty()) {
Map<String, Object> res = new HashMap<>(); Map<String, Object> res = new HashMap<>();
for (Map.Entry<String, Object> entry : additionalProperties.entrySet()) { for (Map.Entry<String, Object> entry : additionalProperties.entrySet()) {
Map<String, Object> map = new HashMap<>(); Map<String, Object> map = new HashMap<>();
map.put("name", entry.getKey()); map.put("name", entry.getKey());
map.put("value", entry.getValue()); map.put("value", entry.getValue());
map.put("display", "false"); map.put("display", "false");
res.put(entry.getKey(), map); res.put(entry.getKey(), map);
} }
return res; return res;
} }
return null; return null;
} }
private static ApiPolicies mapApiPolicies(ApiDefinition32 oldApi) { private static ApiPolicies mapApiPolicies(ApiDefinition32 oldApi) {
ApiDefinition45.ApiPolicies apiPolicies = new ApiDefinition45.ApiPolicies(); ApiDefinition45.ApiPolicies apiPolicies = new ApiDefinition45.ApiPolicies();
// ---------- request policies ---------- // ---------- request policies ----------
if (oldApi != null && oldApi.getInSequence() != null && !oldApi.getInSequence().isEmpty()) { if (oldApi != null && oldApi.getInSequence() != null && !oldApi.getInSequence().isEmpty()) {
ApiDefinition45.Policy requestPolicy = new ApiDefinition45.Policy(); ApiDefinition45.Policy requestPolicy = new ApiDefinition45.Policy();
requestPolicy.setPolicyName(oldApi.getInSequence()); requestPolicy.setPolicyName(oldApi.getInSequence());
requestPolicy.setPolicyType("api"); requestPolicy.setPolicyType("api");
requestPolicy.setPolicyVersion("v1"); requestPolicy.setPolicyVersion("v1");
requestPolicy.setPolicyId(""); requestPolicy.setPolicyId("");
requestPolicy.setParameters(Collections.emptyMap()); requestPolicy.setParameters(Collections.emptyMap());
apiPolicies.setRequest(List.of(requestPolicy)); apiPolicies.setRequest(List.of(requestPolicy));
} else } else
apiPolicies.setRequest(Collections.emptyList()); apiPolicies.setRequest(Collections.emptyList());
// ---------- response policies ---------- // ---------- response policies ----------
if (oldApi != null && oldApi.getOutSequence() != null && !oldApi.getOutSequence().isEmpty()) { if (oldApi != null && oldApi.getOutSequence() != null && !oldApi.getOutSequence().isEmpty()) {
ApiDefinition45.Policy requestPolicy = new ApiDefinition45.Policy(); ApiDefinition45.Policy requestPolicy = new ApiDefinition45.Policy();
requestPolicy.setPolicyName(oldApi.getOutSequence()); requestPolicy.setPolicyName(oldApi.getOutSequence());
requestPolicy.setPolicyType("api"); requestPolicy.setPolicyType("api");
requestPolicy.setPolicyVersion("v1"); requestPolicy.setPolicyVersion("v1");
requestPolicy.setPolicyId(""); requestPolicy.setPolicyId("");
requestPolicy.setParameters(Collections.emptyMap()); requestPolicy.setParameters(Collections.emptyMap());
apiPolicies.setResponse(List.of(requestPolicy)); apiPolicies.setResponse(List.of(requestPolicy));
} else } else
apiPolicies.setResponse(Collections.emptyList()); apiPolicies.setResponse(Collections.emptyList());
// ---------- fault policies ---------- // ---------- fault policies ----------
if (oldApi != null && oldApi.getFaultSequence() != null && !oldApi.getFaultSequence().isEmpty()) { if (oldApi != null && oldApi.getFaultSequence() != null && !oldApi.getFaultSequence().isEmpty()) {
ApiDefinition45.Policy requestPolicy = new ApiDefinition45.Policy(); ApiDefinition45.Policy requestPolicy = new ApiDefinition45.Policy();
requestPolicy.setPolicyName(oldApi.getFaultSequence()); requestPolicy.setPolicyName(oldApi.getFaultSequence());
requestPolicy.setPolicyType("api"); requestPolicy.setPolicyType("api");
requestPolicy.setPolicyVersion("v1"); requestPolicy.setPolicyVersion("v1");
requestPolicy.setPolicyId(""); requestPolicy.setPolicyId("");
requestPolicy.setParameters(Collections.emptyMap()); requestPolicy.setParameters(Collections.emptyMap());
apiPolicies.setFault(List.of(requestPolicy)); apiPolicies.setFault(List.of(requestPolicy));
} else } else
apiPolicies.setFault(Collections.emptyList()); apiPolicies.setFault(Collections.emptyList());
return apiPolicies; return apiPolicies;
} }
private static ApiDefinition45.CorsConfiguration mapCors(ApiDefinition32.CorsConfiguration oldCors) { private static ApiDefinition45.CorsConfiguration mapCors(ApiDefinition32.CorsConfiguration oldCors) {
if (oldCors == null) if (oldCors == null)
return null; return null;
ApiDefinition45.CorsConfiguration cors = new ApiDefinition45.CorsConfiguration(); ApiDefinition45.CorsConfiguration cors = new ApiDefinition45.CorsConfiguration();
cors.setCorsConfigurationEnabled(oldCors.isCorsConfigurationEnabled()); cors.setCorsConfigurationEnabled(oldCors.isCorsConfigurationEnabled());
cors.setAccessControlAllowOrigins(oldCors.getAccessControlAllowOrigins()); cors.setAccessControlAllowOrigins(oldCors.getAccessControlAllowOrigins());
cors.setAccessControlAllowHeaders(oldCors.getAccessControlAllowHeaders()); cors.setAccessControlAllowHeaders(oldCors.getAccessControlAllowHeaders());
cors.setAccessControlAllowMethods(oldCors.getAccessControlAllowMethods()); cors.setAccessControlAllowMethods(oldCors.getAccessControlAllowMethods());
cors.setAccessControlAllowCredentials(oldCors.isAccessControlAllowCredentials()); cors.setAccessControlAllowCredentials(oldCors.isAccessControlAllowCredentials());
return cors; return cors;
} }
// private static ApiDefinition45.EndpointConfig mapEndpointConfig(ApiDefinition32.EndpointConfig oldEndpoint) { // private static ApiDefinition45.EndpointConfig mapEndpointConfig(ApiDefinition32.EndpointConfig oldEndpoint) {
// if (oldEndpoint == null) // if (oldEndpoint == null)
// return null; // return null;
// //
// ApiDefinition45.EndpointConfig newEndpoint = new ApiDefinition45.EndpointConfig(); // ApiDefinition45.EndpointConfig newEndpoint = new ApiDefinition45.EndpointConfig();
// newEndpoint.setEndpoint_type(oldEndpoint.getEndpointType()); // newEndpoint.setEndpoint_type(oldEndpoint.getEndpointType());
// //
// if (oldEndpoint.getSandboxEndpoints() != null) { // if (oldEndpoint.getSandboxEndpoints() != null) {
// ApiDefinition45.EndpointGroup sandbox = new ApiDefinition45.EndpointGroup(); // ApiDefinition45.EndpointGroup sandbox = new ApiDefinition45.EndpointGroup();
// sandbox.setUrl(oldEndpoint.getSandboxEndpoints().getUrl()); // sandbox.setUrl(oldEndpoint.getSandboxEndpoints().getUrl());
// newEndpoint.setSandbox_endpoints(sandbox); // newEndpoint.setSandbox_endpoints(sandbox);
// } // }
// //
// if (oldEndpoint.getProductionEndpoints() != null) { // if (oldEndpoint.getProductionEndpoints() != null) {
// ApiDefinition45.EndpointGroup production = new ApiDefinition45.EndpointGroup(); // ApiDefinition45.EndpointGroup production = new ApiDefinition45.EndpointGroup();
// production.setUrl(oldEndpoint.getProductionEndpoints().getUrl()); // production.setUrl(oldEndpoint.getProductionEndpoints().getUrl());
// newEndpoint.setProduction_endpoints(production); // newEndpoint.setProduction_endpoints(production);
// } // }
// //
// if (oldEndpoint.getEndpointSecurity() != null) { // if (oldEndpoint.getEndpointSecurity() != null) {
// ApiDefinition45.EndpointSecurity security = new ApiDefinition45.EndpointSecurity(); // ApiDefinition45.EndpointSecurity security = new ApiDefinition45.EndpointSecurity();
// security.setSandbox(mapSecurityEnv(oldEndpoint.getEndpointSecurity().getSandbox())); // security.setSandbox(mapSecurityEnv(oldEndpoint.getEndpointSecurity().getSandbox()));
// security.setProduction(mapSecurityEnv(oldEndpoint.getEndpointSecurity().getProduction())); // security.setProduction(mapSecurityEnv(oldEndpoint.getEndpointSecurity().getProduction()));
// newEndpoint.setEndpoint_security(security); // newEndpoint.setEndpoint_security(security);
// } // }
// //
// return newEndpoint; // return newEndpoint;
// } // }
// //
// private static ApiDefinition45.SecurityEnv mapSecurityEnv(ApiDefinition32.SecurityEnvironment oldSec) { // private static ApiDefinition45.SecurityEnv mapSecurityEnv(ApiDefinition32.SecurityEnvironment oldSec) {
// if (oldSec == null) // if (oldSec == null)
// return null; // return null;
// //
// ApiDefinition45.SecurityEnv newSec = new ApiDefinition45.SecurityEnv(); // ApiDefinition45.SecurityEnv newSec = new ApiDefinition45.SecurityEnv();
// newSec.setType(oldSec.getType()); // newSec.setType(oldSec.getType());
// newSec.setTokenUrl(oldSec.getTokenUrl()); // newSec.setTokenUrl(oldSec.getTokenUrl());
// newSec.setClientId(oldSec.getClientId()); // newSec.setClientId(oldSec.getClientId());
// newSec.setClientSecret( // newSec.setClientSecret(
// CredentialsDecoder.decodeCredentials(oldSec.getClientSecret(), AbstractProcess.PRIVATE_KEY_APIM_32)); // CredentialsDecoder.decodeCredentials(oldSec.getClientSecret(), AbstractProcess.PRIVATE_KEY_APIM_32));
// newSec.setUsername(oldSec.getUsername()); // newSec.setUsername(oldSec.getUsername());
// newSec.setPassword(oldSec.getPassword()); // newSec.setPassword(oldSec.getPassword());
// newSec.setGrantType(oldSec.getGrantType()); // newSec.setGrantType(oldSec.getGrantType());
// newSec.setEnabled(oldSec.isEnabled()); // newSec.setEnabled(oldSec.isEnabled());
// newSec.setConnectionTimeoutDuration(0); // newSec.setConnectionTimeoutDuration(0);
// newSec.setSocketTimeoutDuration(0); // newSec.setSocketTimeoutDuration(0);
// newSec.setConnectionRequestTimeoutDuration(0); // newSec.setConnectionRequestTimeoutDuration(0);
// newSec.setProxyConfigs(new ApiDefinition45.ProxyConfigs()); // newSec.setProxyConfigs(new ApiDefinition45.ProxyConfigs());
// //
// // ---------- parse customParameters JSON string ---------- // // ---------- parse customParameters JSON string ----------
// if (oldSec.getCustomParameters() != null && !oldSec.getCustomParameters().isEmpty()) { // if (oldSec.getCustomParameters() != null && !oldSec.getCustomParameters().isEmpty()) {
// try { // try {
// Map<String, Object> map = AbstractProcess.mapperYaml.readValue(oldSec.getCustomParameters(), // Map<String, Object> map = AbstractProcess.mapperYaml.readValue(oldSec.getCustomParameters(),
// new TypeReference<>() { // new TypeReference<>() {
// }); // });
// newSec.setCustomParameters(map); // newSec.setCustomParameters(map);
// } catch (Exception e) { // } catch (Exception e) {
// newSec.setCustomParameters(Collections.emptyMap()); // newSec.setCustomParameters(Collections.emptyMap());
// } // }
// } else { // } else {
// newSec.setCustomParameters(Collections.emptyMap()); // newSec.setCustomParameters(Collections.emptyMap());
// } // }
// //
// // ---------- parse additionalProperties JSON string ---------- // // ---------- parse additionalProperties JSON string ----------
// newSec.setAdditionalProperties(Collections.emptyMap()); // newSec.setAdditionalProperties(Collections.emptyMap());
// //
// return newSec; // return newSec;
// } // }
public static List<Operation> mapOperations(String swaggerYamlString) throws Exception { public static List<Operation> mapOperations(String swaggerYamlString) throws Exception {
JsonNode root = AbstractProcess.mapperYaml.readTree(swaggerYamlString); JsonNode root = AbstractProcess.mapperYaml.readTree(swaggerYamlString);
JsonNode pathsNode = root.get("paths"); JsonNode pathsNode = root.get("paths");
if (pathsNode == null || !pathsNode.isObject()) { if (pathsNode == null || !pathsNode.isObject()) {
throw new IllegalArgumentException("Swagger YAML neobsahuje sekci 'paths'."); throw new IllegalArgumentException("Swagger YAML neobsahuje sekci 'paths'.");
} }
List<Operation> operationsList = new ArrayList<>(); List<Operation> operationsList = new ArrayList<>();
Iterator<Map.Entry<String, JsonNode>> pathIter = pathsNode.fields(); Iterator<Map.Entry<String, JsonNode>> pathIter = pathsNode.fields();
while (pathIter.hasNext()) { while (pathIter.hasNext()) {
Map.Entry<String, JsonNode> pathEntry = pathIter.next(); Map.Entry<String, JsonNode> pathEntry = pathIter.next();
String path = pathEntry.getKey(); String path = pathEntry.getKey();
JsonNode methodsNode = pathEntry.getValue(); JsonNode methodsNode = pathEntry.getValue();
Iterator<Map.Entry<String, JsonNode>> methodIter = methodsNode.fields(); Iterator<Map.Entry<String, JsonNode>> methodIter = methodsNode.fields();
while (methodIter.hasNext()) { while (methodIter.hasNext()) {
Map.Entry<String, JsonNode> methodEntry = methodIter.next(); Map.Entry<String, JsonNode> methodEntry = methodIter.next();
String verb = methodEntry.getKey().toUpperCase(); String verb = methodEntry.getKey().toUpperCase();
JsonNode methodDef = methodEntry.getValue(); JsonNode methodDef = methodEntry.getValue();
Operation op = new Operation(); Operation op = new Operation();
op.setId(""); op.setId("");
op.setTarget(path); op.setTarget(path);
op.setVerb(verb); op.setVerb(verb);
op.setAuthType(methodDef.path("x-auth-type").asText("")); op.setAuthType(methodDef.path("x-auth-type").asText(""));
op.setThrottlingPolicy(methodDef.path("x-throttling-tier").asText("")); op.setThrottlingPolicy(methodDef.path("x-throttling-tier").asText(""));
op.setScopes(new ArrayList<>()); op.setScopes(new ArrayList<>());
op.setUsedProductIds(new ArrayList<>()); op.setUsedProductIds(new ArrayList<>());
OperationPolicies policies = new OperationPolicies(); OperationPolicies policies = new OperationPolicies();
policies.setRequest(new ArrayList<>()); policies.setRequest(new ArrayList<>());
policies.setResponse(new ArrayList<>()); policies.setResponse(new ArrayList<>());
policies.setFault(new ArrayList<>()); policies.setFault(new ArrayList<>());
op.setOperationPolicies(policies); op.setOperationPolicies(policies);
operationsList.add(op); operationsList.add(op);
} }
} }
return operationsList; return operationsList;
} }
} }

View File

@ -1,92 +1,92 @@
package cz.trask.migration.model; package cz.trask.migration.model;
public class APIInfo { public class APIInfo {
private String id; private String id;
private String name; private String name;
private String description; private String description;
private String context; private String context;
private String version; private String version;
private String provider; private String provider;
private String lifeCycleStatus; private String lifeCycleStatus;
private String thumbnailUri; private String thumbnailUri;
private String type; private String type;
public String getId() { public String getId() {
return id; return id;
} }
public void setId(String id) { public void setId(String id) {
this.id = id; this.id = id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public void setDescription(String description) { public void setDescription(String description) {
this.description = description; this.description = description;
} }
public String getContext() { public String getContext() {
return context; return context;
} }
public void setContext(String context) { public void setContext(String context) {
this.context = context; this.context = context;
} }
public String getVersion() { public String getVersion() {
return version; return version;
} }
public void setVersion(String version) { public void setVersion(String version) {
this.version = version; this.version = version;
} }
public String getProvider() { public String getProvider() {
return provider; return provider;
} }
public void setProvider(String provider) { public void setProvider(String provider) {
this.provider = provider; this.provider = provider;
} }
public String getLifeCycleStatus() { public String getLifeCycleStatus() {
return lifeCycleStatus; return lifeCycleStatus;
} }
public void setLifeCycleStatus(String lifeCycleStatus) { public void setLifeCycleStatus(String lifeCycleStatus) {
this.lifeCycleStatus = lifeCycleStatus; this.lifeCycleStatus = lifeCycleStatus;
} }
public String getThumbnailUri() { public String getThumbnailUri() {
return thumbnailUri; return thumbnailUri;
} }
public void setThumbnailUri(String thumbnailUri) { public void setThumbnailUri(String thumbnailUri) {
this.thumbnailUri = thumbnailUri; this.thumbnailUri = thumbnailUri;
} }
public String getType() { public String getType() {
return type; return type;
} }
public void setType(String type) { public void setType(String type) {
this.type = type; this.type = type;
} }
@Override @Override
public String toString() { public String toString() {
return id + "\t" + name + "\t" + version + "\t" + provider + "\t" + lifeCycleStatus + "\t" + description; return id + "\t" + name + "\t" + version + "\t" + provider + "\t" + lifeCycleStatus + "\t" + description;
} }
} }

View File

@ -1,31 +1,31 @@
package cz.trask.migration.model; package cz.trask.migration.model;
public class APIList { public class APIList {
// "count": 102, "next": "", "previous": "", "list": [ // "count": 102, "next": "", "previous": "", "list": [
private int count; private int count;
private APIInfo[] list = null; private APIInfo[] list = null;
public int getCount() { public int getCount() {
return count; return count;
} }
public void setCount(int count) { public void setCount(int count) {
this.count = count; this.count = count;
} }
public APIInfo[] getList() { public APIInfo[] getList() {
return list; return list;
} }
public void setList(APIInfo[] list) { public void setList(APIInfo[] list) {
this.list = list; this.list = list;
} }
@Override @Override
public String toString() { public String toString() {
return count + "\t" + list; return count + "\t" + list;
} }
} }

View File

@ -1,5 +1,5 @@
package cz.trask.migration.model; package cz.trask.migration.model;
public enum FileType { public enum FileType {
APIDEF, OPENAPI, WSDL, POLICY_IN, POLICY_OUT, POLICY_FAULT, CERTIFICATE, SUBSCRIPTIONS, DOCUMENTATION, UNKNOWN APIDEF, OPENAPI, WSDL, POLICY_IN, POLICY_OUT, POLICY_FAULT, CERTIFICATE, SUBSCRIPTIONS, DOCUMENTATION, UNKNOWN
} }

View File

@ -1,92 +1,92 @@
package cz.trask.migration.model; package cz.trask.migration.model;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
public class RegisterResponse { public class RegisterResponse {
private String clientId; private String clientId;
private String clientName; private String clientName;
private String callBackURL; private String callBackURL;
private String clientSecret; private String clientSecret;
@JsonProperty("isSaasApplication") @JsonProperty("isSaasApplication")
private boolean saasApplication; private boolean saasApplication;
private String appOwner; private String appOwner;
private String jsonString; private String jsonString;
private String jsonAppAttribute; private String jsonAppAttribute;
private String tokenType; private String tokenType;
// getters a setters // getters a setters
public String getClientId() { public String getClientId() {
return clientId; return clientId;
} }
public void setClientId(String clientId) { public void setClientId(String clientId) {
this.clientId = clientId; this.clientId = clientId;
} }
public String getClientName() { public String getClientName() {
return clientName; return clientName;
} }
public void setClientName(String clientName) { public void setClientName(String clientName) {
this.clientName = clientName; this.clientName = clientName;
} }
public String getCallBackURL() { public String getCallBackURL() {
return callBackURL; return callBackURL;
} }
public void setCallBackURL(String callBackURL) { public void setCallBackURL(String callBackURL) {
this.callBackURL = callBackURL; this.callBackURL = callBackURL;
} }
public String getClientSecret() { public String getClientSecret() {
return clientSecret; return clientSecret;
} }
public void setClientSecret(String clientSecret) { public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret; this.clientSecret = clientSecret;
} }
public boolean isSaasApplication() { public boolean isSaasApplication() {
return saasApplication; return saasApplication;
} }
public void setSaasApplication(boolean saasApplication) { public void setSaasApplication(boolean saasApplication) {
this.saasApplication = saasApplication; this.saasApplication = saasApplication;
} }
public String getAppOwner() { public String getAppOwner() {
return appOwner; return appOwner;
} }
public void setAppOwner(String appOwner) { public void setAppOwner(String appOwner) {
this.appOwner = appOwner; this.appOwner = appOwner;
} }
public String getJsonString() { public String getJsonString() {
return jsonString; return jsonString;
} }
public void setJsonString(String jsonString) { public void setJsonString(String jsonString) {
this.jsonString = jsonString; this.jsonString = jsonString;
} }
public String getJsonAppAttribute() { public String getJsonAppAttribute() {
return jsonAppAttribute; return jsonAppAttribute;
} }
public void setJsonAppAttribute(String jsonAppAttribute) { public void setJsonAppAttribute(String jsonAppAttribute) {
this.jsonAppAttribute = jsonAppAttribute; this.jsonAppAttribute = jsonAppAttribute;
} }
public String getTokenType() { public String getTokenType() {
return tokenType; return tokenType;
} }
public void setTokenType(String tokenType) { public void setTokenType(String tokenType) {
this.tokenType = tokenType; this.tokenType = tokenType;
} }
} }

View File

@ -1,35 +1,35 @@
package cz.trask.migration.model; package cz.trask.migration.model;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
public class StartParameters { public class StartParameters {
private static Logger log = LogManager.getLogger(StartParameters.class); private static Logger log = LogManager.getLogger(StartParameters.class);
String command; String command;
public String getCommand() { public String getCommand() {
return command; return command;
} }
public void setCommand(String command) { public void setCommand(String command) {
this.command = command.toLowerCase(); this.command = command.toLowerCase();
} }
public static StartParameters parse(String commandLine) throws Exception { public static StartParameters parse(String commandLine) throws Exception {
StartParameters res = new StartParameters(); StartParameters res = new StartParameters();
try { try {
String[] rawParams = commandLine.split("-"); String[] rawParams = commandLine.split("-");
res.setCommand(rawParams[0]); res.setCommand(rawParams[0]);
} catch (Exception e) { } catch (Exception e) {
log.error("Error while parsing startup parameters.", e); log.error("Error while parsing startup parameters.", e);
throw e; throw e;
} }
return res; return res;
} }
} }

View File

@ -1,53 +1,53 @@
package cz.trask.migration.model; package cz.trask.migration.model;
public class TokenResponse { public class TokenResponse {
// {"access_token":"6be1aa81-d0ae-321e-9e3e-2ea89dd9f847","refresh_token":"5cff194d-cb16-3dc2-ab60-3c44ba25ae4a","scope":"apim:api_view","token_type":"Bearer","expires_in":3600} // {"access_token":"6be1aa81-d0ae-321e-9e3e-2ea89dd9f847","refresh_token":"5cff194d-cb16-3dc2-ab60-3c44ba25ae4a","scope":"apim:api_view","token_type":"Bearer","expires_in":3600}
private String access_token; private String access_token;
private String refresh_token; private String refresh_token;
private String scope; private String scope;
private String token_type; private String token_type;
private long expires_in; private long expires_in;
public String getAccess_token() { public String getAccess_token() {
return access_token; return access_token;
} }
public void setAccess_token(String access_token) { public void setAccess_token(String access_token) {
this.access_token = access_token; this.access_token = access_token;
} }
public String getRefresh_token() { public String getRefresh_token() {
return refresh_token; return refresh_token;
} }
public void setRefresh_token(String refresh_token) { public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token; this.refresh_token = refresh_token;
} }
public String getScope() { public String getScope() {
return scope; return scope;
} }
public void setScope(String scope) { public void setScope(String scope) {
this.scope = scope; this.scope = scope;
} }
public String getToken_type() { public String getToken_type() {
return token_type; return token_type;
} }
public void setToken_type(String token_type) { public void setToken_type(String token_type) {
this.token_type = token_type; this.token_type = token_type;
} }
public long getExpires_in() { public long getExpires_in() {
return expires_in; return expires_in;
} }
public void setExpires_in(long expires_in) { public void setExpires_in(long expires_in) {
this.expires_in = expires_in; this.expires_in = expires_in;
} }
} }

View File

@ -1,43 +1,43 @@
package cz.trask.migration.model; package cz.trask.migration.model;
public class ZipEntryData { public class ZipEntryData {
private String name; private String name;
private FileType type; private FileType type;
private byte[] content; private byte[] content;
public ZipEntryData(String name, FileType type, byte[] content) { public ZipEntryData(String name, FileType type, byte[] content) {
this.name = name; this.name = name;
this.type = type; this.type = type;
this.content = content; this.content = content;
} }
// Gettery a settery // Gettery a settery
public String getName() { public String getName() {
return name; return name;
} }
public void setName(String name) { public void setName(String name) {
this.name = name; this.name = name;
} }
public FileType getType() { public FileType getType() {
return type; return type;
} }
public void setType(FileType type) { public void setType(FileType type) {
this.type = type; this.type = type;
} }
public byte[] getContent() { public byte[] getContent() {
return content; return content;
} }
public void setContent(byte[] content) { public void setContent(byte[] content) {
this.content = content; this.content = content;
} }
@Override @Override
public String toString() { public String toString() {
return "ZipEntryData{name='" + name + "', type=" + type + "}"; return "ZipEntryData{name='" + name + "', type=" + type + "}";
} }
} }

View File

@ -1,112 +1,112 @@
package cz.trask.migration.model.v32; package cz.trask.migration.model.v32;
import java.util.Objects; import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data; import lombok.Data;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class Documents32 { public class Documents32 {
private String id = null; private String id = null;
private String name = null; private String name = null;
private TypeEnum type = null; private TypeEnum type = null;
private String summary = null; private String summary = null;
private SourceTypeEnum sourceType = null; private SourceTypeEnum sourceType = null;
private String sourceUrl = null; private String sourceUrl = null;
private String fileName = null; private String fileName = null;
private String inlineContent = null; private String inlineContent = null;
private String otherTypeName = null; private String otherTypeName = null;
private VisibilityEnum visibility = null; private VisibilityEnum visibility = null;
private String createdTime = null; private String createdTime = null;
private String createdBy = null; private String createdBy = null;
private String lastUpdatedTime = null; private String lastUpdatedTime = null;
private String lastUpdatedBy = null; private String lastUpdatedBy = null;
public enum TypeEnum { public enum TypeEnum {
HOWTO, HOWTO,
SAMPLES, SAMPLES,
PUBLIC_FORUM, PUBLIC_FORUM,
SUPPORT_FORUM, SUPPORT_FORUM,
API_MESSAGE_FORMAT, API_MESSAGE_FORMAT,
SWAGGER_DOC, SWAGGER_DOC,
OTHER OTHER
} }
public enum SourceTypeEnum { public enum SourceTypeEnum {
INLINE, INLINE,
MARKDOWN, MARKDOWN,
URL, URL,
FILE FILE
} }
public enum VisibilityEnum { public enum VisibilityEnum {
OWNER_ONLY, OWNER_ONLY,
PRIVATE, PRIVATE,
API_LEVEL API_LEVEL
} }
@Override @Override
public boolean equals(java.lang.Object o) { public boolean equals(java.lang.Object o) {
if (this == o) { if (this == o) {
return true; return true;
} }
if (o == null || getClass() != o.getClass()) { if (o == null || getClass() != o.getClass()) {
return false; return false;
} }
Documents32 document = (Documents32) o; Documents32 document = (Documents32) o;
return Objects.equals(id, document.id) && Objects.equals(name, document.name) return Objects.equals(id, document.id) && Objects.equals(name, document.name)
&& Objects.equals(type, document.type) && Objects.equals(summary, document.summary) && Objects.equals(type, document.type) && Objects.equals(summary, document.summary)
&& Objects.equals(sourceType, document.sourceType) && Objects.equals(sourceUrl, document.sourceUrl) && Objects.equals(sourceType, document.sourceType) && Objects.equals(sourceUrl, document.sourceUrl)
&& Objects.equals(fileName, document.fileName) && Objects.equals(inlineContent, document.inlineContent) && Objects.equals(fileName, document.fileName) && Objects.equals(inlineContent, document.inlineContent)
&& Objects.equals(otherTypeName, document.otherTypeName) && Objects.equals(otherTypeName, document.otherTypeName)
&& Objects.equals(visibility, document.visibility) && Objects.equals(createdTime, document.createdTime) && Objects.equals(visibility, document.visibility) && Objects.equals(createdTime, document.createdTime)
&& Objects.equals(createdBy, document.createdBy) && Objects.equals(createdBy, document.createdBy)
&& Objects.equals(lastUpdatedTime, document.lastUpdatedTime) && Objects.equals(lastUpdatedTime, document.lastUpdatedTime)
&& Objects.equals(lastUpdatedBy, document.lastUpdatedBy); && Objects.equals(lastUpdatedBy, document.lastUpdatedBy);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, name, type, summary, sourceType, sourceUrl, fileName, inlineContent, otherTypeName, return Objects.hash(id, name, type, summary, sourceType, sourceUrl, fileName, inlineContent, otherTypeName,
visibility, createdTime, createdBy, lastUpdatedTime, lastUpdatedBy); visibility, createdTime, createdBy, lastUpdatedTime, lastUpdatedBy);
} }
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
sb.append("class DocumentDTO {\n"); sb.append("class DocumentDTO {\n");
sb.append(" documentId: ").append(toIndentedString(id)).append("\n"); sb.append(" documentId: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" summary: ").append(toIndentedString(summary)).append("\n"); sb.append(" summary: ").append(toIndentedString(summary)).append("\n");
sb.append(" sourceType: ").append(toIndentedString(sourceType)).append("\n"); sb.append(" sourceType: ").append(toIndentedString(sourceType)).append("\n");
sb.append(" sourceUrl: ").append(toIndentedString(sourceUrl)).append("\n"); sb.append(" sourceUrl: ").append(toIndentedString(sourceUrl)).append("\n");
sb.append(" fileName: ").append(toIndentedString(fileName)).append("\n"); sb.append(" fileName: ").append(toIndentedString(fileName)).append("\n");
sb.append(" inlineContent: ").append(toIndentedString(inlineContent)).append("\n"); sb.append(" inlineContent: ").append(toIndentedString(inlineContent)).append("\n");
sb.append(" otherTypeName: ").append(toIndentedString(otherTypeName)).append("\n"); sb.append(" otherTypeName: ").append(toIndentedString(otherTypeName)).append("\n");
sb.append(" visibility: ").append(toIndentedString(visibility)).append("\n"); sb.append(" visibility: ").append(toIndentedString(visibility)).append("\n");
sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n"); sb.append(" createdTime: ").append(toIndentedString(createdTime)).append("\n");
sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n"); sb.append(" createdBy: ").append(toIndentedString(createdBy)).append("\n");
sb.append(" lastUpdatedTime: ").append(toIndentedString(lastUpdatedTime)).append("\n"); sb.append(" lastUpdatedTime: ").append(toIndentedString(lastUpdatedTime)).append("\n");
sb.append(" lastUpdatedBy: ").append(toIndentedString(lastUpdatedBy)).append("\n"); sb.append(" lastUpdatedBy: ").append(toIndentedString(lastUpdatedBy)).append("\n");
sb.append("}"); sb.append("}");
return sb.toString(); return sb.toString();
} }
/** /**
* Convert the given object to string with each line indented by 4 spaces * Convert the given object to string with each line indented by 4 spaces
* (except the first line). * (except the first line).
*/ */
private String toIndentedString(java.lang.Object o) { private String toIndentedString(java.lang.Object o) {
if (o == null) { if (o == null) {
return "null"; return "null";
} }
return o.toString().replace("\n", "\n "); return o.toString().replace("\n", "\n ");
} }
} }

View File

@ -1,31 +1,31 @@
package cz.trask.migration.model.v32; package cz.trask.migration.model.v32;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data; import lombok.Data;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class Subscriptions { public class Subscriptions {
private List<Subscription> list; private List<Subscription> list;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public static class Subscription { public static class Subscription {
private String subscriptionId; private String subscriptionId;
private ApplicationInfo applicationInfo; private ApplicationInfo applicationInfo;
private String throttlingPolicy; private String throttlingPolicy;
private String subscriptionStatus; private String subscriptionStatus;
} }
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public static class ApplicationInfo { public static class ApplicationInfo {
private String applicationId; private String applicationId;
private String name; private String name;
private String subscriber; private String subscriber;
private String description; private String description;
private int subscriptionCount; private int subscriptionCount;
} }
} }

View File

@ -1,40 +1,40 @@
package cz.trask.migration.model.v45; package cz.trask.migration.model.v45;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude;
import cz.trask.migration.model.v32.Documents32.SourceTypeEnum; import cz.trask.migration.model.v32.Documents32.SourceTypeEnum;
import cz.trask.migration.model.v32.Documents32.TypeEnum; import cz.trask.migration.model.v32.Documents32.TypeEnum;
import cz.trask.migration.model.v32.Documents32.VisibilityEnum; import cz.trask.migration.model.v32.Documents32.VisibilityEnum;
import lombok.Data; import lombok.Data;
@Data @Data
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class Documents45 { public class Documents45 {
private String type = "document"; private String type = "document";
private String version = "v4.5.0"; private String version = "v4.5.0";
private Data data = null; private Data data = null;
@lombok.Data @lombok.Data
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public static class Data { public static class Data {
private String id = null; private String id = null;
private String name = null; private String name = null;
private TypeEnum type = null; private TypeEnum type = null;
private String summary = null; private String summary = null;
private SourceTypeEnum sourceType = null; private SourceTypeEnum sourceType = null;
private String sourceUrl = null; private String sourceUrl = null;
private String fileName = null; private String fileName = null;
private String inlineContent = null; private String inlineContent = null;
private String otherTypeName = null; private String otherTypeName = null;
private VisibilityEnum visibility = null; private VisibilityEnum visibility = null;
private String createdTime = null; private String createdTime = null;
private String createdBy = null; private String createdBy = null;
private String lastUpdatedTime = null; private String lastUpdatedTime = null;
private String lastUpdatedBy = null; private String lastUpdatedBy = null;
} }
} }

View File

@ -1,26 +1,26 @@
package cz.trask.migration.model.v45; package cz.trask.migration.model.v45;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data; import lombok.Data;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class EndpointCertificates45 { public class EndpointCertificates45 {
private String type; private String type;
private String version; private String version;
private List<EndpointCertificate> data; private List<EndpointCertificate> data;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public static class EndpointCertificate { public static class EndpointCertificate {
private String alias; private String alias;
private String endpoint; private String endpoint;
private String certificate; private String certificate;
private int tenantId; private int tenantId;
} }
} }

View File

@ -1,35 +1,35 @@
package cz.trask.migration.model.v45; package cz.trask.migration.model.v45;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data; import lombok.Data;
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class OperationPolicySpecification45 { public class OperationPolicySpecification45 {
private String type; private String type;
private String version; private String version;
private Data data; private Data data;
@lombok.Data @lombok.Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public static class Data { public static class Data {
private String category; private String category;
private String name; private String name;
private String version; // version of the policy itself private String version; // version of the policy itself
private String displayName; private String displayName;
private String description; private String description;
private List<String> applicableFlows; private List<String> applicableFlows;
private List<String> supportedGateways; private List<String> supportedGateways;
private List<String> supportedApiTypes; private List<String> supportedApiTypes;
private List<Object> policyAttributes = new ArrayList<>(); private List<Object> policyAttributes = new ArrayList<>();
} }
} }

View File

@ -1,60 +1,60 @@
package cz.trask.migration.util; package cz.trask.migration.util;
import java.nio.file.Files; import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.security.KeyFactory; import java.security.KeyFactory;
import java.security.PrivateKey; import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64; import java.util.Base64;
import java.util.Map; import java.util.Map;
import javax.crypto.Cipher; import javax.crypto.Cipher;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.log4j.Log4j2; import lombok.extern.log4j.Log4j2;
@Log4j2 @Log4j2
public class CredentialsDecoder { public class CredentialsDecoder {
public static String decodeCredentials(String credentials, String pkFile) { public static String decodeCredentials(String credentials, String pkFile) {
if (credentials == null || credentials.isEmpty()) { if (credentials == null || credentials.isEmpty()) {
log.warn("No credentials provided to decode."); log.warn("No credentials provided to decode.");
return null; return null;
} }
try { try {
String decodedJson = new String(Base64.getDecoder().decode(credentials)); String decodedJson = new String(Base64.getDecoder().decode(credentials));
log.debug("Decoded JSON: {}", decodedJson); log.debug("Decoded JSON: {}", decodedJson);
ObjectMapper mapper = new ObjectMapper(); ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonMap = mapper.readValue(decodedJson, Map.class); Map<String, String> jsonMap = mapper.readValue(decodedJson, Map.class);
String cipherBase64 = jsonMap.get("c"); String cipherBase64 = jsonMap.get("c");
String transformation = jsonMap.get("t"); String transformation = jsonMap.get("t");
log.debug("Used algorithm: {}", transformation); log.debug("Used algorithm: {}", transformation);
String privateKeyPEM = new String(Files.readAllBytes(Paths.get(pkFile))) String privateKeyPEM = new String(Files.readAllBytes(Paths.get(pkFile)))
.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "") .replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", ""); .replaceAll("\\s+", "");
byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyPEM); byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyPEM);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA"); KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(keySpec); PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
byte[] encryptedBytes = Base64.getDecoder().decode(cipherBase64); byte[] encryptedBytes = Base64.getDecoder().decode(cipherBase64);
Cipher cipher = Cipher.getInstance(transformation); Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, privateKey); cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes); byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedText = new String(decryptedBytes, "UTF-8"); String decryptedText = new String(decryptedBytes, "UTF-8");
log.debug("Decoded credential: {}", decryptedText); log.debug("Decoded credential: {}", decryptedText);
return decryptedText; return decryptedText;
} catch (Exception e) { } catch (Exception e) {
log.error("Error decoding credentials: ", e); log.error("Error decoding credentials: ", e);
return null; return null;
} }
} }
} }