Merge pull request 'Implement API layer for publish API method' (#112) from pasindu/device-mgt-core:publisherAPILayer into master

Reviewed-on: community/device-mgt-core#112
app-icon-change
Amalka Subasinghe 2 years ago
commit 302f62a264

@ -34,6 +34,11 @@
<url>https://entgra.io</url> <url>https://entgra.io</url>
<dependencies> <dependencies>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId> <artifactId>org.wso2.carbon.logging</artifactId>

@ -23,8 +23,16 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.Mediation;
import org.wso2.carbon.apimgt.api.model.APIRevision;
import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment;
import org.wso2.carbon.apimgt.api.model.Documentation;
import java.util.List;
public interface PublisherRESTAPIServices { public interface PublisherRESTAPIServices {
@ -34,6 +42,77 @@ public interface PublisherRESTAPIServices {
boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key) boolean isSharedScopeNameExists(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String key)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean addNewSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope) boolean updateSharedScope(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, Scope scope)
throws APIServicesException, BadRequestException, UnexpectedResponseException; throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIIdentifier apiIdentifier)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getApis(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject addAPI(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateApi(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, APIInfo api)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean saveAsyncApiDefinition(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
String asyncApiDefinition)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAllApiSpecificMediationPolicies(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIIdentifier apiIdentifier)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean addApiSpecificMediationPolicy(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Mediation mediation)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean updateApiSpecificMediationPolicyContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Mediation mediation)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean changeLifeCycleStatus(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, String action)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getAPIRevisions(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
Boolean deploymentStatus)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject addAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIRevision apiRevision)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deployAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo, String uuid,
String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeploymentList)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
abstract boolean undeployAPIRevisionDeployment(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevisionDeployment, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deleteAPIRevision(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
JSONObject apiRevision, String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
JSONObject getDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean deleteDocumentations(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, String documentID)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
Documentation addDocumentation(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
String uuid, Documentation documentation)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
boolean addDocumentationContent(APIApplicationKey apiApplicationKey, AccessTokenInfo accessTokenInfo,
APIInfo api, String docId, String docContent)
throws APIServicesException, BadRequestException, UnexpectedResponseException;
} }

@ -34,7 +34,7 @@ public final class Constants {
public static final String OAUTH_TOKEN_TYPE = "token_type"; public static final String OAUTH_TOKEN_TYPE = "token_type";
public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token"; public static final String REFRESH_TOKEN_GRANT_TYPE = "refresh_token";
public static final String SCOPE_PARAM_NAME = "scope"; public static final String SCOPE_PARAM_NAME = "scope";
public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage"; public static final String SCOPES = "apim:api_create apim:api_view apim:shared_scope_manage apim:api_import_export apim:api_publish";
public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint"; public static final String DCR_END_POINT = "WorkflowConfigurations.DCREndPoint";
public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint"; public static final String TOKE_END_POINT = "WorkflowConfigurations.TokenEndPoint";
public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive"; public static final String ADAPTER_CONF_KEEP_ALIVE = "keepAlive";
@ -58,10 +58,13 @@ public final class Constants {
public static final String SCHEME_SEPARATOR = "://"; public static final String SCHEME_SEPARATOR = "://";
public static final String COLON = ":"; public static final String COLON = ":";
public static final String QUERY_KEY_VALUE_SEPARATOR = "="; public static final String QUERY_KEY_VALUE_SEPARATOR = "=";
public static final String SPACE = " ";
public static final String IOT_CORE_HOST = "iot.core.host"; public static final String IOT_CORE_HOST = "iot.core.host";
public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port"; public static final String IOT_CORE_HTTPS_PORT = "iot.core.https.port";
public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000"; public static final String GET_ALL_SCOPES = "/api/am/publisher/v2/scopes?limit=1000";
public static final String GET_SCOPE = "/api/am/publisher/v2/scopes/"; public static final String SCOPE_API_ENDPOINT = "/api/am/publisher/v2/scopes/";
public static final String API_ENDPOINT = "/api/am/publisher/v2/apis/";
public static final String GET_ALL_APIS = "/api/am/publisher/v2/apis?limit=1000";
} }

@ -0,0 +1,478 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.model.APICategory;
import org.wso2.carbon.apimgt.api.model.CORSConfiguration;
import org.wso2.carbon.apimgt.api.model.WebsubSubscriptionConfiguration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* This class represents the API response.
*/
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 wsdlInfo;
private String wsdlUrl;
private boolean responseCachingEnabled;
private int cacheTimeout;
private boolean hasThumbnail;
private boolean isDefaultVersion;
private boolean isRevision;
private String revisionedApiId;
private int revisionId;
private boolean enableSchemaValidation;
private String type;
private Set<String> transport;
private Set<String> tags;
private Set<String> policies;
private String apiThrottlingPolicy;
private String authorizationHeader;
private String securityScheme;
private String maxTps;
private String visibility;
private String visibleRoles;
private String visibleTenants;
private String mediationPolicies;
private String subscriptionAvailability;
private String subscriptionAvailableTenants;
private String additionalProperties;
private String monetization;
private String accessControl;
private String accessControlRoles;
private BusinessInformation businessInformation;
private CORSConfiguration corsConfiguration;
private WebsubSubscriptionConfiguration websubSubscriptionConfiguration;
private String workflowStatus;
private String createdTime;
private String lastUpdatedTime;
private JSONObject endpointConfig = new JSONObject();
private String endpointImplementationType;
private List<JSONObject> scopes = new ArrayList();
private List<JSONObject> operations;
private String threatProtectionPolicies;
private List<APICategory> apiCategories;
private List<String> keyManagers = new ArrayList();
private JSONObject serviceInfo = new JSONObject();
private AdvertiseInfo advertiseInfo;
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 getWsdlInfo() {
return wsdlInfo;
}
public void setWsdlInfo(String wsdlInfo) {
this.wsdlInfo = wsdlInfo;
}
public String getWsdlUrl() {
return wsdlUrl;
}
public void setWsdlUrl(String wsdlUrl) {
this.wsdlUrl = wsdlUrl;
}
public boolean isResponseCachingEnabled() {
return responseCachingEnabled;
}
public void setResponseCachingEnabled(boolean responseCachingEnabled) {
this.responseCachingEnabled = responseCachingEnabled;
}
public int getCacheTimeout() {
return cacheTimeout;
}
public void setCacheTimeout(int cacheTimeout) {
this.cacheTimeout = cacheTimeout;
}
public boolean isHasThumbnail() {
return hasThumbnail;
}
public void setHasThumbnail(boolean hasThumbnail) {
this.hasThumbnail = hasThumbnail;
}
public boolean isDefaultVersion() {
return isDefaultVersion;
}
public void setDefaultVersion(boolean defaultVersion) {
isDefaultVersion = defaultVersion;
}
public boolean isRevision() {
return isRevision;
}
public void setRevision(boolean revision) {
isRevision = revision;
}
public String getRevisionedApiId() {
return revisionedApiId;
}
public void setRevisionedApiId(String revisionedApiId) {
this.revisionedApiId = revisionedApiId;
}
public int getRevisionId() {
return revisionId;
}
public void setRevisionId(int revisionId) {
this.revisionId = revisionId;
}
public boolean isEnableSchemaValidation() {
return enableSchemaValidation;
}
public void setEnableSchemaValidation(boolean enableSchemaValidation) {
this.enableSchemaValidation = enableSchemaValidation;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Set<String> getTransport() {
return transport;
}
public void setTransport(Set<String> transport) {
this.transport = transport;
}
public Set<String> getTags() {
return tags;
}
public void setTags(Set<String> tags) {
this.tags = tags;
}
public Set<String> getPolicies() {
return policies;
}
public void setPolicies(Set<String> policies) {
this.policies = policies;
}
public String getApiThrottlingPolicy() {
return apiThrottlingPolicy;
}
public void setApiThrottlingPolicy(String apiThrottlingPolicy) {
this.apiThrottlingPolicy = apiThrottlingPolicy;
}
public String getAuthorizationHeader() {
return authorizationHeader;
}
public void setAuthorizationHeader(String authorizationHeader) {
this.authorizationHeader = authorizationHeader;
}
public String getSecurityScheme() {
return securityScheme;
}
public void setSecurityScheme(String securityScheme) {
this.securityScheme = securityScheme;
}
public String getMaxTps() {
return maxTps;
}
public void setMaxTps(String maxTps) {
this.maxTps = maxTps;
}
public String getVisibility() {
return visibility;
}
public void setVisibility(String visibility) {
this.visibility = visibility;
}
public String getVisibleRoles() {
return visibleRoles;
}
public void setVisibleRoles(String visibleRoles) {
this.visibleRoles = visibleRoles;
}
public String getVisibleTenants() {
return visibleTenants;
}
public void setVisibleTenants(String visibleTenants) {
this.visibleTenants = visibleTenants;
}
public String getMediationPolicies() {
return mediationPolicies;
}
public void setMediationPolicies(String mediationPolicies) {
this.mediationPolicies = mediationPolicies;
}
public String getSubscriptionAvailability() {
return subscriptionAvailability;
}
public void setSubscriptionAvailability(String subscriptionAvailability) {
this.subscriptionAvailability = subscriptionAvailability;
}
public String getSubscriptionAvailableTenants() {
return subscriptionAvailableTenants;
}
public void setSubscriptionAvailableTenants(String subscriptionAvailableTenants) {
this.subscriptionAvailableTenants = subscriptionAvailableTenants;
}
public String getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(String additionalProperties) {
this.additionalProperties = additionalProperties;
}
public String getMonetization() {
return monetization;
}
public void setMonetization(String monetization) {
this.monetization = monetization;
}
public String getAccessControl() {
return accessControl;
}
public void setAccessControl(String accessControl) {
this.accessControl = accessControl;
}
public String getAccessControlRoles() {
return accessControlRoles;
}
public void setAccessControlRoles(String accessControlRoles) {
this.accessControlRoles = accessControlRoles;
}
public BusinessInformation getBusinessInformation() {
return businessInformation;
}
public void setBusinessInformation(BusinessInformation businessInformation) {
this.businessInformation = businessInformation;
}
public CORSConfiguration getCorsConfiguration() {
return corsConfiguration;
}
public void setCorsConfiguration(CORSConfiguration corsConfiguration) {
this.corsConfiguration = corsConfiguration;
}
public WebsubSubscriptionConfiguration getWebsubSubscriptionConfiguration() {
return websubSubscriptionConfiguration;
}
public void setWebsubSubscriptionConfiguration(WebsubSubscriptionConfiguration websubSubscriptionConfiguration) {
this.websubSubscriptionConfiguration = websubSubscriptionConfiguration;
}
public String getWorkflowStatus() {
return workflowStatus;
}
public void setWorkflowStatus(String workflowStatus) {
this.workflowStatus = workflowStatus;
}
public String getCreatedTime() {
return createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public String getLastUpdatedTime() {
return lastUpdatedTime;
}
public void setLastUpdatedTime(String lastUpdatedTime) {
this.lastUpdatedTime = lastUpdatedTime;
}
public JSONObject getEndpointConfig() {
return endpointConfig;
}
public void setEndpointConfig(JSONObject endpointConfig) {
this.endpointConfig = endpointConfig;
}
public String getEndpointImplementationType() {
return endpointImplementationType;
}
public void setEndpointImplementationType(String endpointImplementationType) {
this.endpointImplementationType = endpointImplementationType;
}
public List<JSONObject>getScopes() {
return scopes;
}
public void setScopes(List<JSONObject> scopes) {
this.scopes = scopes;
}
public List<JSONObject> getOperations() {
return operations;
}
public void setOperations(List<JSONObject> operations) {
this.operations = operations;
}
public String getThreatProtectionPolicies() {
return threatProtectionPolicies;
}
public void setThreatProtectionPolicies(String threatProtectionPolicies) {
this.threatProtectionPolicies = threatProtectionPolicies;
}
public List<APICategory> getApiCategories() {
return apiCategories;
}
public void setApiCategories(List<APICategory> apiCategories) {
this.apiCategories = apiCategories;
}
public List<String> getKeyManagers() {
return keyManagers;
}
public void setKeyManagers(List<String> keyManagers) {
this.keyManagers = keyManagers;
}
public JSONObject getServiceInfo() {
return serviceInfo;
}
public void setServiceInfo(JSONObject serviceInfo) {
this.serviceInfo = serviceInfo;
}
public AdvertiseInfo getAdvertiseInfo() {
return advertiseInfo;
}
public void setAdvertiseInfo(AdvertiseInfo advertiseInfo) {
this.advertiseInfo = advertiseInfo;
}
}

@ -0,0 +1,62 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
/**
* This hold the advertisement information of an API.
*/
public class AdvertiseInfo {
private boolean advertised;
private String originalDevPortalUrl;
private String apiOwner;
private String vendor;
public boolean isAdvertised() {
return advertised;
}
public void setAdvertised(boolean advertised) {
this.advertised = advertised;
}
public String getOriginalDevPortalUrl() {
return originalDevPortalUrl;
}
public void setOriginalDevPortalUrl(String originalDevPortalUrl) {
this.originalDevPortalUrl = originalDevPortalUrl;
}
public String getApiOwner() {
return apiOwner;
}
public void setApiOwner(String apiOwner) {
this.apiOwner = apiOwner;
}
public String getVendor() {
return vendor;
}
public void setVendor(String vendor) {
this.vendor = vendor;
}
}

@ -0,0 +1,62 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
/**
* This hold the business information of an API.
*/
public class BusinessInformation {
private String businessOwner;
private String businessOwnerEmail;
private String technicalOwner;
private String technicalOwnerEmail;
public String getBusinessOwner() {
return businessOwner;
}
public void setBusinessOwner(String businessOwner) {
this.businessOwner = businessOwner;
}
public String getBusinessOwnerEmail() {
return businessOwnerEmail;
}
public void setBusinessOwnerEmail(String businessOwnerEmail) {
this.businessOwnerEmail = businessOwnerEmail;
}
public String getTechnicalOwner() {
return technicalOwner;
}
public void setTechnicalOwner(String technicalOwner) {
this.technicalOwner = technicalOwner;
}
public String getTechnicalOwnerEmail() {
return technicalOwnerEmail;
}
public void setTechnicalOwnerEmail(String technicalOwnerEmail) {
this.technicalOwnerEmail = technicalOwnerEmail;
}
}

@ -0,0 +1,129 @@
/*
* Copyright (c) 2023, Entgra (Pvt) Ltd. (http://www.entgra.io) All Rights Reserved.
*
* Entgra (Pvt) Ltd. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo;
import java.util.Set;
/**
* This hold the api operations information.
*/
public class Operations {
private String id;
private String target;
private String verb;
private String authType;
private String throttlingPolicy;
private Set<String> scopes;
private String usedProductIds;
private String amznResourceName;
private String amznResourceTimeout;
private String payloadSchema;
private String uriMapping;
public Operations() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public String getVerb() {
return verb;
}
public void setVerb(String verb) {
this.verb = verb;
}
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getThrottlingPolicy() {
return throttlingPolicy;
}
public void setThrottlingPolicy(String throttlingPolicy) {
this.throttlingPolicy = throttlingPolicy;
}
public Set<String> getScopes() {
return scopes;
}
public void setScopes(Set<String> scopes) {
this.scopes = scopes;
}
public String getUsedProductIds() {
return usedProductIds;
}
public void setUsedProductIds(String usedProductIds) {
this.usedProductIds = usedProductIds;
}
public String getAmznResourceName() {
return amznResourceName;
}
public void setAmznResourceName(String amznResourceName) {
this.amznResourceName = amznResourceName;
}
public String getAmznResourceTimeout() {
return amznResourceTimeout;
}
public void setAmznResourceTimeout(String amznResourceTimeout) {
this.amznResourceTimeout = amznResourceTimeout;
}
public String getPayloadSchema() {
return payloadSchema;
}
public void setPayloadSchema(String payloadSchema) {
this.payloadSchema = payloadSchema;
}
public String getUriMapping() {
return uriMapping;
}
public void setUriMapping(String uriMapping) {
this.uriMapping = uriMapping;
}
}

@ -27,6 +27,10 @@ public class ScopeUtils {
private String name; private String name;
private String roles; private String roles;
private String description; private String description;
private int id;
public ScopeUtils() {
}
public String getKey() { public String getKey() {
return key; return key;
@ -62,13 +66,13 @@ public class ScopeUtils {
public String toJSON() { public String toJSON() {
String jsonString = "{\n" + String jsonString = "{\n" +
" \"name\":\" " + key + "\",\n" + " \"name\":\"" + key + "\",\n" +
" \"displayName\":\" " + name + "\",\n" + " \"displayName\":\"" + name + "\",\n" +
" \"description\":\" " + description + " \",\n" + " \"description\":\"" + description + "\",\n" +
" \"bindings\":[\n" + " \"bindings\":[\n" +
" \" " + roles + " \"\n" + " \"" + roles + "\"\n" +
" ]\n" + " ]\n" +
"}"; "}";
return jsonString; return jsonString;
} }
} }

@ -174,9 +174,7 @@
org.scannotation;version="1.0", org.scannotation;version="1.0",
org.scannotation.archiveiterator;version="1.0", org.scannotation.archiveiterator;version="1.0",
org.w3c.dom, org.w3c.dom,
io.entgra.device.mgt.core.apimgt.extension.rest.api, io.entgra.device.mgt.core.apimgt.extension.rest.api.*,
io.entgra.device.mgt.core.apimgt.extension.rest.api.dto,
io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions,
io.entgra.device.mgt.core.apimgt.annotations, io.entgra.device.mgt.core.apimgt.annotations,
org.wso2.carbon.apimgt.api, org.wso2.carbon.apimgt.api,
org.wso2.carbon.apimgt.api.model, org.wso2.carbon.apimgt.api.model,

@ -22,11 +22,13 @@ import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationService
import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.APIApplicationServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServices;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl; import io.entgra.device.mgt.core.apimgt.extension.rest.api.PublisherRESTAPIServicesImpl;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.constants.Constants;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIApplicationKey;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo; import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.AccessTokenInfo;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.APIServicesException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.BadRequestException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException; import io.entgra.device.mgt.core.apimgt.extension.rest.api.exceptions.UnexpectedResponseException;
import io.entgra.device.mgt.core.apimgt.extension.rest.api.dto.APIInfo.APIInfo;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -36,19 +38,14 @@ import org.json.JSONArray;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.api.APIManagementException; import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.APIProvider; import org.wso2.carbon.apimgt.api.APIProvider;
import org.wso2.carbon.apimgt.api.FaultGatewaysException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIIdentifier; import org.wso2.carbon.apimgt.api.model.APIIdentifier;
import org.wso2.carbon.apimgt.api.model.APIRevision; import org.wso2.carbon.apimgt.api.model.APIRevision;
import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment; import org.wso2.carbon.apimgt.api.model.APIRevisionDeployment;
import org.wso2.carbon.apimgt.api.model.CORSConfiguration; import org.wso2.carbon.apimgt.api.model.CORSConfiguration;
import org.wso2.carbon.apimgt.api.model.Mediation; import org.wso2.carbon.apimgt.api.model.Mediation;
import org.wso2.carbon.apimgt.api.model.Scope; import org.wso2.carbon.apimgt.api.model.Scope;
import org.wso2.carbon.apimgt.api.model.Tier;
import org.wso2.carbon.apimgt.api.model.URITemplate;
import org.wso2.carbon.apimgt.impl.APIConstants; import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.APIManagerFactory; import org.wso2.carbon.apimgt.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.impl.definitions.AsyncApiParser;
import org.wso2.carbon.apimgt.impl.utils.APIUtil; import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig; import io.entgra.device.mgt.core.apimgt.webapp.publisher.config.WebappPublisherConfig;
import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope; import io.entgra.device.mgt.core.apimgt.webapp.publisher.dto.ApiScope;
@ -91,6 +88,11 @@ public class APIPublisherServiceImpl implements APIPublisherService {
private static final String API_PUBLISH_ENVIRONMENT = "Default"; private static final String API_PUBLISH_ENVIRONMENT = "Default";
private static final String CREATED_STATUS = "CREATED"; private static final String CREATED_STATUS = "CREATED";
private static final String PUBLISH_ACTION = "Publish"; private static final String PUBLISH_ACTION = "Publish";
public static final String SUBSCRIPTION_TO_ALL_TENANTS = "ALL_TENANTS";
public static final String SUBSCRIPTION_TO_CURRENT_TENANT = "CURRENT_TENANT";
public static final String API_GLOBAL_VISIBILITY = "PUBLIC";
public static final String API_PRIVATE_VISIBILITY = "PRIVATE";
private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class); private static final Log log = LogFactory.getLog(APIPublisherServiceImpl.class);
@Override @Override
@ -100,6 +102,20 @@ public class APIPublisherServiceImpl implements APIPublisherService {
tenants.addAll(config.getTenants().getTenant()); tenants.addAll(config.getTenants().getTenant());
RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext() RealmService realmService = (RealmService) PrivilegedCarbonContext.getThreadLocalCarbonContext()
.getOSGiService(RealmService.class, null); .getOSGiService(RealmService.class, null);
APIApplicationServices apiApplicationServices = new APIApplicationServicesImpl();
APIApplicationKey apiApplicationKey;
AccessTokenInfo accessTokenInfo;
try {
apiApplicationKey = apiApplicationServices.createAndRetrieveApplicationCredentials();
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) {
String errorMsg = "Error occurred while generating the API application";
log.error(errorMsg, e);
throw new APIManagerPublisherException(e);
}
try { try {
boolean tenantFound = false; boolean tenantFound = false;
boolean tenantsLoaded = false; boolean tenantsLoaded = false;
@ -140,27 +156,38 @@ public class APIPublisherServiceImpl implements APIPublisherService {
APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()), APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(apiConfig.getOwner()),
apiConfig.getName(), apiConfig.getVersion()); apiConfig.getName(), apiConfig.getVersion());
if (!apiProvider.isAPIAvailable(apiIdentifier)) { PublisherRESTAPIServices publisherRESTAPIServices = new PublisherRESTAPIServicesImpl();
JSONArray apiList = (JSONArray) publisherRESTAPIServices.getApis(apiApplicationKey, accessTokenInfo).get("list");
boolean apiFound = false;
for (int i = 0; i < apiList.length(); i++) {
JSONObject apiObj = apiList.getJSONObject(i);
if (apiObj.getString("name").equals(apiIdentifier.getApiName().replace(Constants.SPACE,
Constants.EMPTY_STRING))){
apiFound = true;
apiIdentifier.setUuid(apiObj.getString("id"));
break;
}
}
if (!apiFound) {
// add new scopes as shared scopes // add new scopes as shared scopes
Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain);
for (ApiScope apiScope : apiConfig.getScopes()) { for (ApiScope apiScope : apiConfig.getScopes()) {
if (!allSharedScopeKeys.contains(apiScope.getKey())) { if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo,
apiScope.getKey())) {
Scope scope = new Scope(); Scope scope = new Scope();
scope.setName(apiScope.getName()); scope.setName(apiScope.getName());
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles()); scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
API api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
api.setId(apiIdentifier); JSONObject createdAPI = publisherRESTAPIServices.addAPI(apiApplicationKey, accessTokenInfo, api);
API createdAPI = apiProvider.addAPI(api);
if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) {
apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo,
createdAPI.getString("id"), apiConfig.getAsyncApiDefinition());
} }
if (CREATED_STATUS.equals(createdAPI.getStatus())) { if (CREATED_STATUS.equals(createdAPI.getString("lifeCycleStatus"))) {
// if endpoint type "dynamic" and then add in sequence // if endpoint type "dynamic" and then add in sequence
if ("dynamic".equals(apiConfig.getEndpointType())) { if ("dynamic".equals(apiConfig.getEndpointType())) {
Mediation mediation = new Mediation(); Mediation mediation = new Mediation();
@ -168,14 +195,17 @@ public class APIPublisherServiceImpl implements APIPublisherService {
mediation.setConfig(apiConfig.getInSequenceConfig()); mediation.setConfig(apiConfig.getInSequenceConfig());
mediation.setType("in"); mediation.setType("in");
mediation.setGlobal(false); mediation.setGlobal(false);
apiProvider.addApiSpecificMediationPolicy(createdAPI.getUuid(), mediation, publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey,
tenantDomain); accessTokenInfo, createdAPI.getString("id"), mediation);
} }
apiProvider.changeLifeCycleStatus(tenantDomain, createdAPI.getUuid(), PUBLISH_ACTION, null); publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey, accessTokenInfo,
createdAPI.getString("id"), PUBLISH_ACTION);
APIRevision apiRevision = new APIRevision(); APIRevision apiRevision = new APIRevision();
apiRevision.setApiUUID(createdAPI.getUuid()); apiRevision.setApiUUID(createdAPI.getString("id"));
apiRevision.setDescription("Initial Revision"); apiRevision.setDescription("Initial Revision");
String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getString("id");
APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment(); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT); apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
@ -184,7 +214,8 @@ public class APIPublisherServiceImpl implements APIPublisherService {
List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>(); List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>();
apiRevisionDeploymentList.add(apiRevisionDeployment); apiRevisionDeploymentList.add(apiRevisionDeployment);
apiProvider.deployAPIRevision(createdAPI.getUuid(), apiRevisionId, apiRevisionDeploymentList); publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo,
createdAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList);
} }
} else { } else {
if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) { if (WebappPublisherConfig.getInstance().isEnabledUpdateApi()) {
@ -203,12 +234,12 @@ public class APIPublisherServiceImpl implements APIPublisherService {
// 1. add new scopes as shared scopes // 1. add new scopes as shared scopes
// 2. update the API adding scopes for the URI Templates // 2. update the API adding scopes for the URI Templates
Set<String> allSharedScopeKeys = apiProvider.getAllSharedScopeKeys(tenantDomain);
Set<ApiScope> scopesToMoveAsSharedScopes = new HashSet<>(); Set<ApiScope> scopesToMoveAsSharedScopes = new HashSet<>();
for (ApiScope apiScope : apiConfig.getScopes()) { for (ApiScope apiScope : apiConfig.getScopes()) {
// if the scope is not available as shared scope and it is assigned to an API as a local scope // if the scope is not available as shared scope, and it is assigned to an API as a local scope
// need remove the local scope and add as a shared scope // need remove the local scope and add as a shared scope
if (!allSharedScopeKeys.contains(apiScope.getKey())) { if (!publisherRESTAPIServices.isSharedScopeNameExists(apiApplicationKey, accessTokenInfo,
apiScope.getKey())) {
if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) { if (apiProvider.isScopeKeyAssignedLocally(apiIdentifier, apiScope.getKey(), tenantId)) {
// collect scope to move as shared scopes // collect scope to move as shared scopes
scopesToMoveAsSharedScopes.add(apiScope); scopesToMoveAsSharedScopes.add(apiScope);
@ -219,19 +250,20 @@ public class APIPublisherServiceImpl implements APIPublisherService {
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles()); scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
} }
// Get existing API // Get existing API
API existingAPI = apiProvider.getAPI(apiIdentifier); JSONObject existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo,
apiIdentifier);
if (scopesToMoveAsSharedScopes.size() > 0) { if (scopesToMoveAsSharedScopes.size() > 0) {
// update API to remove local scopes // update API to remove local scopes
API api = getAPI(apiConfig, false); APIInfo api = getAPI(apiConfig, false);
api.setStatus(existingAPI.getStatus()); api.setLifeCycleStatus(existingAPI.getString("lifeCycleStatus"));
apiProvider.updateAPI(api); publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
for (ApiScope apiScope : scopesToMoveAsSharedScopes) { for (ApiScope apiScope : scopesToMoveAsSharedScopes) {
Scope scope = new Scope(); Scope scope = new Scope();
@ -239,17 +271,19 @@ public class APIPublisherServiceImpl implements APIPublisherService {
scope.setDescription(apiScope.getDescription()); scope.setDescription(apiScope.getDescription());
scope.setKey(apiScope.getKey()); scope.setKey(apiScope.getKey());
scope.setRoles(apiScope.getRoles()); scope.setRoles(apiScope.getRoles());
apiProvider.addSharedScope(scope, tenantDomain); publisherRESTAPIServices.addNewSharedScope(apiApplicationKey, accessTokenInfo, scope);
} }
} }
existingAPI = apiProvider.getAPI(apiIdentifier); existingAPI = publisherRESTAPIServices.getApi(apiApplicationKey, accessTokenInfo, apiIdentifier);
API api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
api.setStatus(existingAPI.getStatus()); api.setLastUpdatedTime(existingAPI.getString("lifeCycleStatus"));
apiProvider.updateAPI(api); api.setId(existingAPI.getString("id"));
publisherRESTAPIServices.updateApi(apiApplicationKey, accessTokenInfo, api);
if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) { if (apiConfig.getEndpointType() != null && "WS".equals(apiConfig.getEndpointType())) {
apiProvider.saveAsyncApiDefinition(api, apiConfig.getAsyncApiDefinition()); publisherRESTAPIServices.saveAsyncApiDefinition(apiApplicationKey, accessTokenInfo,
existingAPI.getString("id"), apiConfig.getAsyncApiDefinition());
} }
// if endpoint type "dynamic" and then add /update in sequence // if endpoint type "dynamic" and then add /update in sequence
@ -260,54 +294,71 @@ public class APIPublisherServiceImpl implements APIPublisherService {
mediation.setType("in"); mediation.setType("in");
mediation.setGlobal(false); mediation.setGlobal(false);
List<Mediation> mediationList = apiProvider List<Mediation> mediationList = (List) publisherRESTAPIServices
.getAllApiSpecificMediationPolicies(apiIdentifier); .getAllApiSpecificMediationPolicies(apiApplicationKey, accessTokenInfo,
apiIdentifier).get("list");
boolean isMediationPolicyFound = false; boolean isMediationPolicyFound = false;
for (Mediation m : mediationList) { for (Mediation m : mediationList) {
if (apiConfig.getInSequenceName().equals(m.getName())) { if (apiConfig.getInSequenceName().equals(m.getName())) {
m.setConfig(apiConfig.getInSequenceConfig()); m.setConfig(apiConfig.getInSequenceConfig());
apiProvider publisherRESTAPIServices.
.updateApiSpecificMediationPolicyContent(existingAPI.getUuid(), m, updateApiSpecificMediationPolicyContent(apiApplicationKey,
tenantDomain); accessTokenInfo, existingAPI.getString("id"), m);
isMediationPolicyFound = true; isMediationPolicyFound = true;
break; break;
} }
} }
if (!isMediationPolicyFound) { if (!isMediationPolicyFound) {
apiProvider.addApiSpecificMediationPolicy(existingAPI.getUuid(), mediation, publisherRESTAPIServices.addApiSpecificMediationPolicy(apiApplicationKey,
tenantDomain); accessTokenInfo, existingAPI.getString("id"), mediation);
} }
} }
// Assumption: Assume the latest revision is the published one // This will retrieve the deployed revision
String latestRevisionUUID = apiProvider.getLatestRevisionUUID(existingAPI.getUuid()); JSONArray revisionDeploymentList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
List<APIRevisionDeployment> latestRevisionDeploymentList = accessTokenInfo, existingAPI.getString("id"), true).get("list");
apiProvider.getAPIRevisionDeploymentList(latestRevisionUUID); // This will retrieve the un deployed revision list
JSONArray undeployedRevisionList = (JSONArray) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
List<APIRevision> apiRevisionList = apiProvider.getAPIRevisions(existingAPI.getUuid()); accessTokenInfo, existingAPI.getString("id"), false).get("list");
if (apiRevisionList.size() >= 5) { int apiRevisionCount = (int) publisherRESTAPIServices.getAPIRevisions(apiApplicationKey,
String earliestRevisionUUID = apiProvider.getEarliestRevisionUUID(existingAPI.getUuid()); accessTokenInfo, existingAPI.getString("id"), null).get("count");
List<APIRevisionDeployment> earliestRevisionDeploymentList =
apiProvider.getAPIRevisionDeploymentList(earliestRevisionUUID); if (apiRevisionCount >= 5) {
apiProvider.undeployAPIRevisionDeployment(existingAPI.getUuid(), earliestRevisionUUID, earliestRevisionDeploymentList); JSONObject latestRevisionDeployment = revisionDeploymentList.getJSONObject(0);
apiProvider.deleteAPIRevision(existingAPI.getUuid(), earliestRevisionUUID, tenantDomain); JSONObject earliestUndeployRevision = undeployedRevisionList.getJSONObject(0);
publisherRESTAPIServices.undeployAPIRevisionDeployment(apiApplicationKey,
accessTokenInfo, latestRevisionDeployment, existingAPI.getString("id"));
publisherRESTAPIServices.deleteAPIRevision(apiApplicationKey, accessTokenInfo,
earliestUndeployRevision, existingAPI.getString("id"));
} }
// create new revision // create new revision
APIRevision apiRevision = new APIRevision(); APIRevision apiRevision = new APIRevision();
apiRevision.setApiUUID(existingAPI.getUuid()); apiRevision.setApiUUID(existingAPI.getString("id"));
apiRevision.setDescription("Updated Revision"); apiRevision.setDescription("Updated Revision");
String apiRevisionId = apiProvider.addAPIRevision(apiRevision, tenantDomain); String apiRevisionId = publisherRESTAPIServices.addAPIRevision(apiApplicationKey,
accessTokenInfo, apiRevision).getString("id");
apiProvider.deployAPIRevision(existingAPI.getUuid(), apiRevisionId, latestRevisionDeploymentList); APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
apiRevisionDeployment.setDeployment(API_PUBLISH_ENVIRONMENT);
apiRevisionDeployment.setVhost(System.getProperty("iot.gateway.host"));
apiRevisionDeployment.setDisplayOnDevportal(true);
List<APIRevisionDeployment> apiRevisionDeploymentList = new ArrayList<>();
apiRevisionDeploymentList.add(apiRevisionDeployment);
if (CREATED_STATUS.equals(existingAPI.getStatus())) { publisherRESTAPIServices.deployAPIRevision(apiApplicationKey, accessTokenInfo,
apiProvider.changeLifeCycleStatus(tenantDomain, existingAPI.getUuid(), PUBLISH_ACTION, null); existingAPI.getString("id"), apiRevisionId, apiRevisionDeploymentList);
if (CREATED_STATUS.equals(existingAPI.getString("lifeCycleStatus"))) {
publisherRESTAPIServices.changeLifeCycleStatus(apiApplicationKey,accessTokenInfo,
existingAPI.getString("id"), PUBLISH_ACTION);
} }
} }
} }
if (apiConfig.getApiDocumentationSourceFile() != null) { if (apiConfig.getApiDocumentationSourceFile() != null) {
API api = getAPI(apiConfig, true); APIInfo api = getAPI(apiConfig, true);
String fileName = String fileName =
CarbonUtils.getCarbonHome() + File.separator + "repository" + CarbonUtils.getCarbonHome() + File.separator + "repository" +
@ -334,17 +385,29 @@ public class APIPublisherServiceImpl implements APIPublisherService {
apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary()); apiDocumentation.setSummary(apiConfig.getApiDocumentationSummary());
apiDocumentation.setOtherTypeName(null); apiDocumentation.setOtherTypeName(null);
try { JSONArray documentList = (JSONArray) publisherRESTAPIServices.getDocumentations(apiApplicationKey,
//Including below code lines inside the try block because 'getDocumentation' method returns an APIManagementException exception when it doesn't have any existing doc accessTokenInfo, api.getId()).get("list");
Documentation existingDoc = apiProvider.getDocumentation(api.getId(), DocumentationType.HOWTO, apiConfig.getApiDocumentationName());
apiProvider.removeDocumentation(api.getId(), existingDoc.getId(), null); if (documentList.length() > 0) {
} catch (APIManagementException e) { for (int i = 0; i < documentList.length(); i++) {
JSONObject existingDoc = documentList.getJSONObject(i);
if (existingDoc.getString("name").equals(apiConfig.getApiDocumentationName())
&& existingDoc.getString("type").equals(DocumentationType.HOWTO)) {
publisherRESTAPIServices.deleteDocumentations(apiApplicationKey, accessTokenInfo,
api.getId(), existingDoc.getString("documentId"));
}
}
} else {
log.info("There is no any existing api documentation."); log.info("There is no any existing api documentation.");
} }
apiProvider.addDocumentation(api.getId(), apiDocumentation); Documentation createdDoc = publisherRESTAPIServices.addDocumentation(apiApplicationKey, accessTokenInfo,
apiProvider.addDocumentationContent(api, apiConfig.getApiDocumentationName(), docContent); api.getId(), apiDocumentation);
publisherRESTAPIServices.addDocumentationContent(apiApplicationKey, accessTokenInfo, api,
createdDoc.getId(), docContent);
} }
} catch (FaultGatewaysException | APIManagementException | IOException e) { } catch (APIManagementException | IOException | APIServicesException |
BadRequestException | UnexpectedResponseException e) {
String msg = "Error occurred while publishing api"; String msg = "Error occurred while publishing api";
log.error(msg, e); log.error(msg, e);
throw new APIManagerPublisherException(e); throw new APIManagerPublisherException(e);
@ -376,7 +439,7 @@ public class APIPublisherServiceImpl implements APIPublisherService {
accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication( accessTokenInfo = apiApplicationServices.generateAccessTokenFromRegisteredApplication(
apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret()); apiApplicationKey.getClientId(), apiApplicationKey.getClientSecret());
} catch (APIServicesException e) { } catch (APIServicesException e) {
String errorMsg = "Error while generating application"; String errorMsg = "Error occurred while generating the API application";
log.error(errorMsg, e); log.error(errorMsg, e);
throw new APIManagerPublisherException(e); throw new APIManagerPublisherException(e);
} }
@ -479,103 +542,137 @@ public class APIPublisherServiceImpl implements APIPublisherService {
} }
} }
private API getAPI(APIConfig config, boolean includeScopes) { private APIInfo getAPI(APIConfig config, boolean includeScopes) {
APIIdentifier apiIdentifier = new APIIdentifier(config.getOwner(), config.getName(), config.getVersion()); APIInfo apiInfo = new APIInfo();
API api = new API(apiIdentifier); apiInfo.setName(config.getName().replace(Constants.SPACE, Constants.EMPTY_STRING));
api.setDescription(""); apiInfo.setDescription("");
String context = config.getContext(); apiInfo.setContext(config.getContext());
context = context.startsWith("/") ? context : ("/" + context); apiInfo.setVersion(config.getVersion());
api.setContext(context + "/" + config.getVersion()); apiInfo.setProvider(config.getOwner());
api.setStatus(CREATED_STATUS); apiInfo.setLifeCycleStatus(CREATED_STATUS);
api.setWsdlUrl(null); apiInfo.setWsdlInfo(null);
api.setResponseCache("Disabled"); apiInfo.setWsdlUrl(null);
api.setContextTemplate(context + "/{version}"); apiInfo.setResponseCachingEnabled(false);
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { apiInfo.setCacheTimeout(0);
api.setAsyncApiDefinition(config.getAsyncApiDefinition()); apiInfo.setHasThumbnail(false);
AsyncApiParser asyncApiParser = new AsyncApiParser(); apiInfo.setDefaultVersion(config.isDefault());
try { apiInfo.setRevision(false);
api.setUriTemplates(asyncApiParser.getURITemplates(config.getAsyncApiDefinition(), true)); apiInfo.setRevisionedApiId(null);
} catch (APIManagementException e) { apiInfo.setEnableSchemaValidation(false);
} Set<String> tags = new HashSet<>();
api.setWsUriMapping(asyncApiParser.buildWSUriMapping(config.getAsyncApiDefinition())); tags.addAll(Arrays.asList(config.getTags()));
apiInfo.setTags(tags);
Set<String> availableTiers = new HashSet<>();
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
availableTiers.add(WS_UNLIMITED_TIER);
} else { } else {
api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config)); availableTiers.add(UNLIMITED_TIER);
}
apiInfo.setPolicies(availableTiers);
Set<URITemplate> uriTemplates = new HashSet<>(); if (config.getEndpointType() == null) {
List<JSONObject> operations = new ArrayList();
List<JSONObject> scopeSet = new ArrayList();
Iterator<ApiUriTemplate> iterator; Iterator<ApiUriTemplate> iterator;
for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) { for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) {
ApiUriTemplate apiUriTemplate = iterator.next(); ApiUriTemplate apiUriTemplate = iterator.next();
URITemplate uriTemplate = new URITemplate(); JSONObject operation = new JSONObject();
uriTemplate.setAuthType(apiUriTemplate.getAuthType()); operation.put("target", apiUriTemplate.getUriTemplate());
uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb()); operation.put("verb", apiUriTemplate.getHttpVerb());
uriTemplate.setResourceURI(apiUriTemplate.getResourceURI()); operation.put("authType", apiUriTemplate.getAuthType());
uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate()); operation.put("throttlingPolicy", UNLIMITED_TIER);
if (includeScopes) { if (includeScopes) {
Scope scope = new Scope();
if (apiUriTemplate.getScope() != null) { if (apiUriTemplate.getScope() != null) {
scope.setName(apiUriTemplate.getScope().getName()); String scopeString = "{\n" +
scope.setDescription(apiUriTemplate.getScope().getDescription()); " \"scope\": {\n" +
scope.setKey(apiUriTemplate.getScope().getKey()); " \"id\": null,\n" +
scope.setRoles(apiUriTemplate.getScope().getRoles()); " \"name\": \"" + apiUriTemplate.getScope().getKey() + "\",\n" +
uriTemplate.setScopes(scope); " \"displayName\": \"" + apiUriTemplate.getScope().getName() + "\",\n" +
" \"description\": \"" + apiUriTemplate.getScope().getDescription() + "\",\n" +
" \"bindings\": [\n" +
" \"" + apiUriTemplate.getScope().getRoles() + "\"\n" +
" ],\n" +
" \"usageCount\": null\n" +
" },\n" +
" \"shared\": true\n" +
" }";
JSONObject scope = new JSONObject(scopeString);
scopeSet.add(scope);
Set<String> scopes = new HashSet<>();
scopes.add(apiUriTemplate.getScope().getKey());
operation.put("scopes", scopes);
} }
} }
uriTemplates.add(uriTemplate); operations.add(operation);
} }
api.setUriTemplates(uriTemplates); apiInfo.setScopes(scopeSet);
apiInfo.setOperations(operations);
} }
api.setApiOwner(config.getOwner()); if (config.isSharedWithAllTenants()) {
apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_ALL_TENANTS);
apiInfo.setVisibility(API_GLOBAL_VISIBILITY);
api.setDefaultVersion(config.isDefault());
Set<String> tags = new HashSet<>();
tags.addAll(Arrays.asList(config.getTags()));
api.setTags(tags);
Set<Tier> availableTiers = new HashSet<>();
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
availableTiers.add(new Tier(WS_UNLIMITED_TIER));
} else { } else {
availableTiers.add(new Tier(UNLIMITED_TIER)); apiInfo.setSubscriptionAvailability(SUBSCRIPTION_TO_CURRENT_TENANT);
apiInfo.setVisibility(API_PRIVATE_VISIBILITY);
} }
api.setAvailableTiers(availableTiers);
Set<String> environments = new HashSet<>(); String endpointConfig;
environments.add(API_PUBLISH_ENVIRONMENT); endpointConfig = "{\n" +
api.setEnvironments(environments); " \"endpoint_type\": \"http\",\n" +
" \"sandbox_endpoints\": {\n" +
" \"url\": \"" + config.getEndpoint() + "\"\n" +
" },\n" +
" \"production_endpoints\": {\n" +
" \"url\": \"" + config.getEndpoint() + "\"\n" +
" }\n" +
" }";
JSONObject endPointConfig = new JSONObject(endpointConfig);
if (config.isSharedWithAllTenants()) { Set<String> transports = new HashSet<>();
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_ALL_TENANTS); transports.addAll(Arrays.asList(config.getTransports()));
api.setVisibility(APIConstants.API_GLOBAL_VISIBILITY); apiInfo.setTransport(transports);
} else {
api.setSubscriptionAvailability(APIConstants.SUBSCRIPTION_TO_CURRENT_TENANT); apiInfo.setType("HTTP");
api.setVisibility(APIConstants.API_PRIVATE_VISIBILITY);
}
String endpointConfig = "{ \"endpoint_type\": \"http\", \"sandbox_endpoints\": { \"url\": \" " +
config.getEndpoint() + "\" }, \"production_endpoints\": { \"url\": \" " + config.getEndpoint() + "\" } }";
api.setTransports(config.getTransports());
api.setType("HTTP");
// if dynamic endpoint
if (config.getEndpointType() != null && "dynamic".equals(config.getEndpointType())) { if (config.getEndpointType() != null && "dynamic".equals(config.getEndpointType())) {
endpointConfig = "{ \"endpoint_type\":\"default\", \"sandbox_endpoints\":{ \"url\":\"default\" }, \"production_endpoints\":{ \"url\":\"default\" } }"; endpointConfig = "{\n" +
api.setInSequence(config.getInSequenceName()); " \"endpoint_type\": \"http\",\n" +
" \"sandbox_endpoints\": {\n" +
" \"url\": \" default \"\n" +
" },\n" +
" \"production_endpoints\": {\n" +
" \"url\": \" default \"\n" +
" }\n" +
" }";
endPointConfig = new JSONObject(endpointConfig);
//TODO: Will be used in dynamic endpoints
// apiInfo.setInSequence(config.getInSequenceName());
} }
// if ws endpoint // if ws endpoint
if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) { if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
endpointConfig = "{ \"endpoint_type\": \"ws\", \"sandbox_endpoints\": { \"url\": \" " + endpointConfig = "{\n" +
config.getEndpoint() + "\" }, \"production_endpoints\": { \"url\": \" " + config.getEndpoint() " \"endpoint_type\": \"ws\",\n" +
+ "\" } }"; " \"sandbox_endpoints\": {\n" +
api.setTransports("wss,ws"); " \"url\": \"" + config.getEndpoint() + "\"\n" +
api.setType("WS"); " },\n" +
" \"production_endpoints\": {\n" +
" \"url\": \"" + config.getEndpoint() + "\"\n" +
" }\n" +
" }";
endPointConfig = new JSONObject(endpointConfig);
transports.addAll(Arrays.asList("wss,ws"));
apiInfo.setTransport(transports);
apiInfo.setType("WS");
} }
api.setEndpointConfig(endpointConfig); apiInfo.setEndpointConfig(endPointConfig);
List<String> accessControlAllowOrigins = new ArrayList<>(); List<String> accessControlAllowOrigins = new ArrayList<>();
accessControlAllowOrigins.add("*"); accessControlAllowOrigins.add("*");
@ -595,15 +692,53 @@ public class APIPublisherServiceImpl implements APIPublisherService {
accessControlAllowMethods.add("OPTIONS"); accessControlAllowMethods.add("OPTIONS");
CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false, CORSConfiguration corsConfiguration = new CORSConfiguration(false, accessControlAllowOrigins, false,
accessControlAllowHeaders, accessControlAllowMethods); accessControlAllowHeaders, accessControlAllowMethods);
api.setCorsConfiguration(corsConfiguration); apiInfo.setCorsConfiguration(corsConfiguration);
api.setAuthorizationHeader("Authorization"); apiInfo.setAuthorizationHeader("Authorization");
List<String> keyManagers = new ArrayList<>(); List<String> keyManagers = new ArrayList<>();
keyManagers.add("all"); keyManagers.add("all");
api.setKeyManagers(keyManagers); apiInfo.setKeyManagers(keyManagers);
api.setEnableStore(true); apiInfo.setEnableSchemaValidation(false);
api.setEnableSchemaValidation(false); apiInfo.setMonetization(null);
api.setMonetizationEnabled(false); apiInfo.setServiceInfo(null);
return api;
return apiInfo;
//TODO: Will be used in WS or dynamic endpoints
// if (config.getEndpointType() != null && "WS".equals(config.getEndpointType())) {
// api.setAsyncApiDefinition(config.getAsyncApiDefinition());
// AsyncApiParser asyncApiParser = new AsyncApiParser();
// try {
// api.setUriTemplates(asyncApiParser.getURITemplates(config.getAsyncApiDefinition(), true));
// } catch (APIManagementException e) {
//
// }
// api.setWsUriMapping(asyncApiParser.buildWSUriMapping(config.getAsyncApiDefinition()));
// } else {
// api.setSwaggerDefinition(APIPublisherUtil.getSwaggerDefinition(config));
//
// Set<URITemplate> uriTemplates = new HashSet<>();
// Iterator<ApiUriTemplate> iterator;
// for (iterator = config.getUriTemplates().iterator(); iterator.hasNext(); ) {
// ApiUriTemplate apiUriTemplate = iterator.next();
// URITemplate uriTemplate = new URITemplate();
// uriTemplate.setAuthType(apiUriTemplate.getAuthType());
// uriTemplate.setHTTPVerb(apiUriTemplate.getHttpVerb());
// uriTemplate.setResourceURI(apiUriTemplate.getResourceURI());
// uriTemplate.setUriTemplate(apiUriTemplate.getUriTemplate());
// if (includeScopes) {
// Scope scope = new Scope();
// if (apiUriTemplate.getScope() != null) {
// scope.setName(apiUriTemplate.getScope().getName());
// scope.setDescription(apiUriTemplate.getScope().getDescription());
// scope.setKey(apiUriTemplate.getScope().getKey());
// scope.setRoles(apiUriTemplate.getScope().getRoles());
// uriTemplate.setScopes(scope);
// }
// }
// uriTemplates.add(uriTemplate);
// }
// api.setUriTemplates(uriTemplates);
// }
} }
} }

Loading…
Cancel
Save