Skip to content

Commit

Permalink
Changed: REST API of Custom Backend update
Browse files Browse the repository at this point in the history
  • Loading branch information
BLasan committed Sep 3, 2024
1 parent 118e958 commit 8ea3663
Show file tree
Hide file tree
Showing 17 changed files with 250 additions and 45 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
Expand Down Expand Up @@ -315,6 +316,9 @@ List<SubscribedAPI> getSubscriptionsOfAPI(String apiName, String apiVersion, Str
*/
API updateAPI(API api, API existingAPI) throws APIManagementException, FaultGatewaysException;

void updateCustomBackend(API api,String type, InputStream sequence, String fileName) throws APIManagementException;
void updateCustomBackendByRevisionID(API api, String type, InputStream sequence, String revision, String fileName) throws APIManagementException;

/**
* Create a new version of the <code>api</code>, with version <code>newVersion</code>
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ private void unDeployAPI(APIGatewayAdmin apiGatewayAdmin, DeployAPIInGatewayEven
}

GatewayUtils.setCustomSequencesToBeRemoved(api, gatewayAPIDTO);
GatewayUtils.setCustomBackendToBeRemoved(api, gatewayAPIDTO);
}
gatewayAPIDTO.setLocalEntriesToBeRemove(
GatewayUtils
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1543,6 +1543,8 @@ private OAuthConstants() {
public static final String MEDIATION_SEQUENCE_ELEM = "sequence";
public static final String MEDIATION_CONFIG_EXT = ".xml";
public static final String API_CUSTOM_SEQ_IN_EXT = "--In";

public static final String API_CUSTOM_BACKEND_SEQ_EXT = "--Custom_Backend";
public static final String API_CUSTOM_SEQ_OUT_EXT = "--Out";
public static final String API_CUSTOM_SEQ_FAULT_EXT = "--Fault";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,18 @@ private void updateAPIPolicies(API api, String tenantDomain) throws APIManagemen
apiMgtDAO.updateAPIPoliciesMapping(api.getUuid(), api.getUriTemplates(), api.getApiPolicies(), tenantDomain);
}

@Override
public void updateCustomBackend(API api, String type, InputStream sequence, String fileName)
throws APIManagementException {
apiMgtDAO.updateCustomBackend(api.getUuid(), fileName, sequence, type);
}

@Override
public void updateCustomBackendByRevisionID(API api, String type, InputStream sequence,
String revision, String fileName) throws APIManagementException {
apiMgtDAO.updateCustomBackendByRevision(api.getUuid(), fileName, sequence, type, revision);
}

private void validateKeyManagers(API api) throws APIManagementException {

Map<String, KeyManagerDto> tenantKeyManagers = KeyManagerHolder.getGlobalAndTenantKeyManagers(tenantDomain);
Expand Down Expand Up @@ -6065,6 +6077,9 @@ public void deployAPIRevision(String apiId, String apiRevisionUUID,
}
}
apiMgtDAO.addAPIRevisionDeployment(apiRevisionUUID, apiRevisionDeployments);

// update AM_API_CUSTOM_BACKEND table

WorkflowExecutor revisionDeploymentWFExecutor = getWorkflowExecutor(
WorkflowConstants.WF_TYPE_AM_REVISION_DEPLOYMENT);

Expand Down Expand Up @@ -6444,6 +6459,7 @@ public void deleteAPIRevision(String apiId, String apiRevisionId, String organiz
ERROR_DELETING_API_REVISION,apiRevision.getApiUUID()));
}
apiMgtDAO.deleteAPIRevision(apiRevision);
apiMgtDAO.deleteCustomBackend(apiId, apiRevisionId);
gatewayArtifactsMgtDAO.deleteGatewayArtifact(apiRevision.getApiUUID(), apiRevision.getRevisionUUID());
if (artifactSaver != null) {
try {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11167,6 +11167,58 @@ public List<String> retrieveSavedEmailList(String userName, String stakeHolder)

}

/**
*
* @param apiUUID UUID of API
* @param revisionUUID Revision ID of the API
* @return A HashMap with Custom Backend data
* @throws APIManagementException
*/
public Map<String, Object> retrieveCustomBackendOfAPIRevision(String apiUUID, String revisionUUID) throws APIManagementException {
String sqlQuery = SQLConstants.CustomBackendConstants.GET_CUSTOM_BACKEND_OF_API_REVISION;
Map<String, Object> map = new HashMap<>();
ResultSet resultSet = null;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement ps = connection.prepareStatement(sqlQuery)) {
ps.setString(1, apiUUID);
ps.setString(2, revisionUUID);
resultSet = ps.executeQuery();
while (resultSet.next()) {
map.put("sequence", resultSet.getString("SEQUENCE"));
map.put("endpoint_type", resultSet.getString("TYPE"));
map.put("sequence_name", resultSet.getString("NAME"));
}
} catch (SQLException ex) {
handleException("Error retrieving Custom Backend of an API: " + apiUUID, ex);
}
return map;
}

/**
*
* @param apiUUID API UUID
* @return HashMap with Custom Backend data
* @throws APIManagementException
*/
public Map<String, Object> retrieveCustomBackendOfAPI(String apiUUID) throws APIManagementException {
String sqlQuery = SQLConstants.CustomBackendConstants.GET_CUSTOM_BACKEND_OF_API_DEFAULT_REVISION;
Map<String, Object> map = new HashMap<>();
ResultSet resultSet = null;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement ps = connection.prepareStatement(sqlQuery)) {
ps.setString(1, apiUUID);
resultSet = ps.executeQuery();
while (resultSet.next()) {
map.put("sequence", resultSet.getString("SEQUENCE"));
map.put("endpoint_type", resultSet.getString("TYPE"));
map.put("sequence_name", resultSet.getString("NAME"));
}
} catch (SQLException ex) {
handleException("Error retrieving Custom Backend of an API: " + apiUUID, ex);
}
return map;
}

/**
* This method will delete all email alert subscriptions details from tables
*
Expand Down Expand Up @@ -20742,6 +20794,64 @@ public void updateAPIPoliciesMapping(String apiUUID, Set<URITemplate> uriTemplat
}
}

public void updateCustomBackend(String apiUUID, String sequenceName, InputStream sequence, String type) throws APIManagementException {
String deleteCustomBackedQuery = SQLConstants.CustomBackendConstants.DELETE_CUSTOM_BACKEND;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement prepStmt = connection.prepareStatement(deleteCustomBackedQuery)) {
connection.setAutoCommit(false);
prepStmt.setString(1, apiUUID);
prepStmt.executeUpdate();
addCustomBackend(apiUUID, sequenceName, null, sequence, type, connection);
connection.commit();
} catch (SQLException e) {
handleException("Error while adding Custom Backend for API : " + apiUUID, e);
}
}

public void deleteCustomBackend(String apiUUID, String revisionId) throws APIManagementException {
String deleteCustomBackedQuery = SQLConstants.CustomBackendConstants.DELETE_CUSTOM_BACKEND_BY_REVISION;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement prepStmt = connection.prepareStatement(deleteCustomBackedQuery)) {
connection.setAutoCommit(false);
prepStmt.setString(1, apiUUID);
prepStmt.setString(2, revisionId);
prepStmt.executeUpdate();
connection.commit();
} catch (SQLException e) {
handleException("Error while deleting Custom Backend for API : " + apiUUID, e);
}
}

public void updateCustomBackendByRevision(String apiUUID, String sequenceName, InputStream sequence, String type, String revision) throws APIManagementException {
String deleteCustomBackedQuery = SQLConstants.CustomBackendConstants.DELETE_CUSTOM_BACKEND_BY_REVISION;
try (Connection connection = APIMgtDBUtil.getConnection();
PreparedStatement prepStmt = connection.prepareStatement(deleteCustomBackedQuery)) {
connection.setAutoCommit(false);
prepStmt.setString(1, apiUUID);
prepStmt.setString(2, revision);
prepStmt.executeUpdate();
addCustomBackend(apiUUID, sequenceName, revision, sequence, type, connection);
connection.commit();
} catch (SQLException e) {
handleException("Error while adding Custom Backend for API : " + apiUUID, e);
}
}

public void addCustomBackend(String apiUUID, String sequenceName, String revision, InputStream sequence, String type, Connection connection) throws APIManagementException {
String insertCustomBackendQuery = SQLConstants.CustomBackendConstants.ADD_CUSTOM_BACKEND;
try (PreparedStatement prepStmt = connection.prepareStatement(insertCustomBackendQuery)) {
connection.setAutoCommit(false);
prepStmt.setString(1, apiUUID);
prepStmt.setBinaryStream(2, sequence);
prepStmt.setString(3, type);
prepStmt.setString(4, revision);
prepStmt.setString(5, sequenceName);
prepStmt.executeUpdate();
} catch (SQLException e) {
handleException("Error while adding Custom Backend for API : " + apiUUID, e);
}
}

/**
* This method will add API level policy mappings to the database.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4401,4 +4401,14 @@ public static class SystemConfigsConstants {
+ "SET CONFIGURATION = ? WHERE ORGANIZATION = ? AND CONFIG_TYPE = ?";
}

public static class CustomBackendConstants {
public static final String ADD_CUSTOM_BACKEND =
"INSERT INTO AM_API_CUSTOM_BACKEND (API_UUID,SEQUENCE,TYPE,REVISION_UUID,NAME) " + "VALUES (?,?,?,?,?)";
public static final String DELETE_CUSTOM_BACKEND = "DELETE FROM AM_API_CUSTOM_BACKEND WHERE API_UUID = ? AND REVISION_UUID IS NULL";
public static final String DELETE_CUSTOM_BACKEND_BY_REVISION = "DELETE FROM AM_API_CUSTOM_BACKEND WHERE API_UUID = ? AND REVISION_UUID = ?";
public static final String DELETE_CUSTOM_BACKEND_BY_API = "DELETE FROM AM_API_CUSTOM_BACKEND WHERE API_UUID = ?";
public static final String GET_CUSTOM_BACKEND_OF_API_REVISION = "SELECT NAME, SEQUENCE, TYPE FROM AM_API_CUSTOM_BACKEND WHERE API_UUID = ? AND REVISION_UUID = ?";
public static final String GET_CUSTOM_BACKEND_OF_API_DEFAULT_REVISION = "SELECT NAME, SEQUENCE, TYPE FROM AM_API_CUSTOM_BACKEND WHERE API_UUID = ? AND REVISION_UUID IS NULL";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,11 @@ public static void setCustomSequencesToBeRemoved(API api, GatewayAPIDTO gatewayA
gatewayAPIDTO.setSequencesToBeRemove(addStringToList(faultSequence, gatewayAPIDTO.getSequencesToBeRemove()));
}

public static void setCustomBackendToBeRemoved(API api, GatewayAPIDTO gatewayAPIDTO) {
String sequence = APIUtil.getSequenceExtensionName(api) + APIConstants.API_CUSTOM_SEQ_IN_EXT + APIConstants.API_CUSTOM_BACKEND_SEQ_EXT;
gatewayAPIDTO.setSequencesToBeRemove(addStringToList(sequence, gatewayAPIDTO.getSequencesToBeRemove()));
}

public static String[] addStringToList(String key, String[] keys) {

if (keys == null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -487,13 +487,13 @@ paths:
-H "Content-Type: application/json" -d @data.json
"https://127.0.0.1:9443/api/am/publisher/v4/apis/7a2298c4-c905-403f-8fac-38c73301631f/topics"'

/apis/{apiId}/custom-sequence:
/apis/{apiId}/custom-backend:
put:
tags:
- APIs
summary: Upload Custom Sequence as the Endpoint of the API
description: This operation can be used to change the endpoint of the API to Custom Sequence
operationId: customSequenceUpdate
operationId: customBackendUpdate
parameters:
- $ref: '#/components/parameters/apiId'
- $ref: '#/components/parameters/If-Match'
Expand All @@ -509,9 +509,6 @@ paths:
type:
type: string
description: Type of the Endpoint
apiData:
type: string
description: API Data to be updated
responses:
200:
description: |
Expand Down Expand Up @@ -561,7 +558,7 @@ paths:
x-code-samples:
- lang: Curl
source: 'curl -k -X PUT -H "Authorization: Bearer ae4eae22-3f65-387b-a171-d37eaa366fa8"
-H "Content-Type: application/json" -d @data.json "https://127.0.0.1:9443/api/am/publisher/v4/apis/7a2298c4-c905-403f-8fac-38c73301631f/custom-sequence"'
-H "Content-Type: application/json" -d @data.json "https://127.0.0.1:9443/api/am/publisher/v4/apis/7a2298c4-c905-403f-8fac-38c73301631f/custom-backend"'


/apis/{apiId}/reimport-service:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
*/
package org.wso2.carbon.apimgt.rest.api.publisher.v1.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.apache.axiom.om.OMElement;
import org.apache.commons.io.FileUtils;
Expand All @@ -38,6 +39,7 @@
import org.wso2.carbon.apimgt.api.model.SwaggerData;
import org.wso2.carbon.apimgt.api.model.graphql.queryanalysis.GraphqlComplexityInfo;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.dao.ApiMgtDAO;
import org.wso2.carbon.apimgt.impl.definitions.GraphQLSchemaDefinition;
import org.wso2.carbon.apimgt.impl.definitions.OAS3Parser;
import org.wso2.carbon.apimgt.impl.dto.APIRuntimeArtifactDto;
Expand All @@ -46,6 +48,7 @@
import org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.GatewayArtifactGenerator;
import org.wso2.carbon.apimgt.impl.importexport.utils.CommonUtil;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.impl.utils.GatewayUtils;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.common.mappings.APIMappingUtil;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.common.mappings.ImportUtils;
import org.wso2.carbon.apimgt.rest.api.publisher.v1.dto.APIDTO;
Expand All @@ -57,10 +60,15 @@
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;

import static org.wso2.carbon.apimgt.impl.utils.APIUtil.handleException;

/**
* This class used to generate Synapse Artifact.
*/
Expand All @@ -73,6 +81,7 @@ public class SynapseArtifactGenerator implements GatewayArtifactGenerator {

private static final Log log = LogFactory.getLog(SynapseArtifactGenerator.class);
private static final String GATEWAY_EXT_SEQUENCE_PREFIX = "WSO2AMGW--Ext";
private static final ApiMgtDAO apiMgtDao = ApiMgtDAO.getInstance();

@Override
public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> apiRuntimeArtifactDtoList)
Expand Down Expand Up @@ -105,7 +114,10 @@ public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> ap
tenantDomain, extractedFolderPath);
} else {
APIDTO apidto = ImportUtils.retrievedAPIDto(extractedFolderPath);
// Update the EndpointConfig if it's a Custom Backend
updateCustomBackendOfAPI(apidto, runTimeArtifact.getRevision());
API api = APIMappingUtil.fromDTOtoAPI(apidto, apidto.getProvider());

api.setUUID(apidto.getId());
if (APIConstants.APITransportType.GRAPHQL.toString().equals(api.getType())) {
APIDefinition parser = new OAS3Parser();
Expand Down Expand Up @@ -170,6 +182,28 @@ public RuntimeArtifactDto generateGatewayArtifact(List<APIRuntimeArtifactDto> ap
return runtimeArtifactDto;
}

private void updateCustomBackendOfAPI(APIDTO apidto, String revisionID) throws APIManagementException {
Object endpointConfig = apidto.getEndpointConfig();
// update the sequence name generated
if (endpointConfig != null) {
if (endpointConfig instanceof HashMap) {
if (APIConstants.ENDPOINT_TYPE_SEQUENCE.equals(
((HashMap) endpointConfig).get(APIConstants.API_ENDPOINT_CONFIG_PROTOCOL_TYPE))) {
// Get Endpoint Configurations from the DB
Map<String, Object> conf = apiMgtDao.retrieveCustomBackendOfAPIRevision(apidto.getId(), revisionID);
if (conf == null) {
throw new APIManagementException(
"Cannot find the Custom Backend for the API: " + apidto.getId() + " , Revision: "
+ revisionID);
}
((HashMap) endpointConfig).put("sequence", conf.get("sequence"));
((HashMap) endpointConfig).put("type", conf.get("type"));
}
}
apidto.setEndpointConfig(endpointConfig);
}
}

/**
* Generate gateway policy artifact.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public static String generatePolicySequenceForUriTemplateSet(Set<URITemplate> ur
}

public static String generateBackendSequenceForCustomSequence(API api, String sequenceName, String flow,
String sequence) throws APIManagementException, IOException {
String sequence, String endpointType) throws APIManagementException, IOException {
Map<String, Object> configMap = new HashMap<>();
boolean render = false;
String customBackendTemplate = FileUtil.readFileToString(CUSTOM_BACKEND_SEQUENCE_TEMPLATE_LOCATION)
Expand All @@ -120,6 +120,7 @@ public static String generateBackendSequenceForCustomSequence(API api, String se
throw new APIManagementException("Error when preparing the sequence: " + sequenceName);
}
configMap.put("custom_sequence", sanitizedSequence);
configMap.put("endpoint_type", endpointType);
render = true;
}
if (render) {
Expand Down
Loading

0 comments on commit 8ea3663

Please sign in to comment.