This commit is contained in:
Radek Davidek 2025-11-03 14:59:12 +01:00
parent cafa504527
commit 2aadbdb68d
3 changed files with 374 additions and 374 deletions

View File

@ -3,7 +3,7 @@ package cz.trask.migration;
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.Logger;
import cz.trask.migration.impl.v32.ImportToApicurio; import cz.trask.migration.impl.v32.Wso2v32ToApicurio;
import cz.trask.migration.impl.v45.ExportToWso2FromV32; import cz.trask.migration.impl.v45.ExportToWso2FromV32;
import cz.trask.migration.model.StartParameters; import cz.trask.migration.model.StartParameters;
@ -23,7 +23,7 @@ public class ApiSync {
if (sp.getCommand().equalsIgnoreCase("wso2ToApicurio")) { if (sp.getCommand().equalsIgnoreCase("wso2ToApicurio")) {
log.info("Import command selected."); log.info("Import command selected.");
ImportToApicurio imp = new ImportToApicurio(); Wso2v32ToApicurio imp = new Wso2v32ToApicurio();
imp.process(); imp.process();
} else if (sp.getCommand().equalsIgnoreCase("apicurioToWso2")) { } else if (sp.getCommand().equalsIgnoreCase("apicurioToWso2")) {
log.info("Export command selected."); log.info("Export command selected.");

View File

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

View File

@ -1,8 +1,8 @@
source: source:
registration_api_url: https://localhost:9443/client-registration/v0.17/register registration_api_url: https://localhost:9444/client-registration/v0.17/register
publisher_api_url: https://localhost:9443/api/am/publisher publisher_api_url: https://localhost:9444/api/am/publisher
devportal_api_url: https://localhost:9443/api/am/store devportal_api_url: https://localhost:9444/api/am/store
publisher_token_url: https://localhost:9443/oauth2/token publisher_token_url: https://localhost:9444/oauth2/token
wso2_user: YWRtaW46YWRtaW4= wso2_user: YWRtaW46YWRtaW4=
target: target: