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

View File

@ -1,42 +1,42 @@
package cz.trask.migration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cz.trask.migration.impl.v32.ImportToApicurio;
import cz.trask.migration.impl.v45.ExportToWso2FromV32;
import cz.trask.migration.model.StartParameters;
public class ApiSync {
private static Logger log = LogManager.getLogger(ApiSync.class);
public static void main(String[] args) throws Exception {
log.info("API Operator started.");
if (args == null) {
log.error("No parameters found.");
printHelp();
} else {
String commandLine = String.join("", args).trim();
StartParameters sp = StartParameters.parse(commandLine);
log.info("Parsed parameters: " + sp);
if (sp.getCommand().equalsIgnoreCase("wso2ToApicurio")) {
log.info("Import command selected.");
ImportToApicurio imp = new ImportToApicurio();
imp.process();
} else if (sp.getCommand().equalsIgnoreCase("apicurioToWso2")) {
log.info("Export command selected.");
ExportToWso2FromV32 exp = new ExportToWso2FromV32();
exp.process();
} else {
log.error("Unknown command: " + sp.getCommand());
printHelp();
}
}
}
private static void printHelp() {
System.out.println("Not enough parameters.\nRun command in this format:\njava -jar shaded.jar [import/export]");
}
}
package cz.trask.migration;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import cz.trask.migration.impl.v32.ImportToApicurio;
import cz.trask.migration.impl.v45.ExportToWso2FromV32;
import cz.trask.migration.model.StartParameters;
public class ApiSync {
private static Logger log = LogManager.getLogger(ApiSync.class);
public static void main(String[] args) throws Exception {
log.info("API Operator started.");
if (args == null) {
log.error("No parameters found.");
printHelp();
} else {
String commandLine = String.join("", args).trim();
StartParameters sp = StartParameters.parse(commandLine);
log.info("Parsed parameters: " + sp);
if (sp.getCommand().equalsIgnoreCase("wso2ToApicurio")) {
log.info("Import command selected.");
ImportToApicurio imp = new ImportToApicurio();
imp.process();
} else if (sp.getCommand().equalsIgnoreCase("apicurioToWso2")) {
log.info("Export command selected.");
ExportToWso2FromV32 exp = new ExportToWso2FromV32();
exp.process();
} else {
log.error("Unknown command: " + sp.getCommand());
printHelp();
}
}
}
private static void printHelp() {
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;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import cz.trask.migration.AbstractProcess;
import cz.trask.migration.model.ApplicationConfig;
import lombok.extern.log4j.Log4j2;
@Log4j2
public final class ConfigManager {
private static final String PROPERTY_FILENAME = "apicurio-migrator.yaml";
private static volatile ConfigManager INSTANCE;
private static ApplicationConfig config = new ApplicationConfig();
private ConfigManager() {
log.info("Loading property file '{}'", PROPERTY_FILENAME);
InputStream in = null;
try {
File extFile = new File(PROPERTY_FILENAME);
if (extFile.exists() && extFile.isFile()) {
log.info("External property file found: {}", extFile.getAbsolutePath());
in = Files.newInputStream(extFile.toPath());
} else {
log.debug("External property file not found.");
}
} catch (Exception e) {
log.warn("Error while accessing external property file", e);
}
if (in == null) {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
in = cl.getResourceAsStream(PROPERTY_FILENAME);
if (in != null) {
log.info("Internal property file found on classpath.");
} else {
log.warn("Property file '{}' not found on classpath.", PROPERTY_FILENAME);
}
} catch (Exception e) {
log.error("Unable to load property file from classpath", e);
}
}
try (InputStream input = in) {
if (input != null) {
config = AbstractProcess.mapperYaml.readValue(input, ApplicationConfig.class);
log.info("Property file loaded successfully.");
} else {
log.warn("No property source available; proceeding with defaults where possible.");
}
} catch (Exception e) {
log.error("Cannot load property file.", e);
}
}
public static ConfigManager getInstance() {
if (INSTANCE == null) {
synchronized (ConfigManager.class) {
if (INSTANCE == null) {
INSTANCE = new ConfigManager();
}
}
}
return INSTANCE;
}
public ApplicationConfig getConfig() {
return config;
}
}
package cz.trask.migration.config;
import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import cz.trask.migration.AbstractProcess;
import cz.trask.migration.model.ApplicationConfig;
import lombok.extern.log4j.Log4j2;
@Log4j2
public final class ConfigManager {
private static final String PROPERTY_FILENAME = "apicurio-migrator.yaml";
private static volatile ConfigManager INSTANCE;
private static ApplicationConfig config = new ApplicationConfig();
private ConfigManager() {
log.info("Loading property file '{}'", PROPERTY_FILENAME);
InputStream in = null;
try {
File extFile = new File(PROPERTY_FILENAME);
if (extFile.exists() && extFile.isFile()) {
log.info("External property file found: {}", extFile.getAbsolutePath());
in = Files.newInputStream(extFile.toPath());
} else {
log.debug("External property file not found.");
}
} catch (Exception e) {
log.warn("Error while accessing external property file", e);
}
if (in == null) {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
in = cl.getResourceAsStream(PROPERTY_FILENAME);
if (in != null) {
log.info("Internal property file found on classpath.");
} else {
log.warn("Property file '{}' not found on classpath.", PROPERTY_FILENAME);
}
} catch (Exception e) {
log.error("Unable to load property file from classpath", e);
}
}
try (InputStream input = in) {
if (input != null) {
config = AbstractProcess.mapperYaml.readValue(input, ApplicationConfig.class);
log.info("Property file loaded successfully.");
} else {
log.warn("No property source available; proceeding with defaults where possible.");
}
} catch (Exception e) {
log.error("Cannot load property file.", e);
}
}
public static ConfigManager getInstance() {
if (INSTANCE == null) {
synchronized (ConfigManager.class) {
if (INSTANCE == null) {
INSTANCE = new ConfigManager();
}
}
}
return INSTANCE;
}
public ApplicationConfig getConfig() {
return config;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,53 +1,53 @@
package cz.trask.migration.model;
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}
private String access_token;
private String refresh_token;
private String scope;
private String token_type;
private long expires_in;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public long getExpires_in() {
return expires_in;
}
public void setExpires_in(long expires_in) {
this.expires_in = expires_in;
}
}
package cz.trask.migration.model;
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}
private String access_token;
private String refresh_token;
private String scope;
private String token_type;
private long expires_in;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public String getRefresh_token() {
return refresh_token;
}
public void setRefresh_token(String refresh_token) {
this.refresh_token = refresh_token;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public long getExpires_in() {
return expires_in;
}
public void setExpires_in(long expires_in) {
this.expires_in = expires_in;
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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