Search in sources :

Example 11 with APIRevision

use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.

the class ApiMgtDAO method getURITemplatesOfAPI.

public Set<URITemplate> getURITemplatesOfAPI(String uuid) throws APIManagementException {
    String currentApiUuid;
    APIRevision apiRevision = checkAPIUUIDIsARevisionUUID(uuid);
    if (apiRevision != null && apiRevision.getApiUUID() != null) {
        currentApiUuid = apiRevision.getApiUUID();
    } else {
        currentApiUuid = uuid;
    }
    Map<Integer, URITemplate> uriTemplates = new LinkedHashMap<>();
    Map<Integer, Set<String>> scopeToURITemplateId = new HashMap<>();
    // Check If the API is a Revision
    if (apiRevision != null) {
        try (Connection conn = APIMgtDBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(SQLConstants.GET_URL_TEMPLATES_OF_API_REVISION_SQL)) {
            ps.setString(1, currentApiUuid);
            ps.setString(2, uuid);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Integer uriTemplateId = rs.getInt("URL_MAPPING_ID");
                    String scopeName = rs.getString("SCOPE_NAME");
                    if (scopeToURITemplateId.containsKey(uriTemplateId) && !StringUtils.isEmpty(scopeName) && !scopeToURITemplateId.get(uriTemplateId).contains(scopeName) && uriTemplates.containsKey(uriTemplateId)) {
                        Scope scope = new Scope();
                        scope.setKey(scopeName);
                        scopeToURITemplateId.get(uriTemplateId).add(scopeName);
                        uriTemplates.get(uriTemplateId).setScopes(scope);
                        continue;
                    }
                    String urlPattern = rs.getString("URL_PATTERN");
                    String verb = rs.getString("HTTP_METHOD");
                    URITemplate uriTemplate = new URITemplate();
                    uriTemplate.setUriTemplate(urlPattern);
                    uriTemplate.setHTTPVerb(verb);
                    uriTemplate.setHttpVerbs(verb);
                    uriTemplate.setId(uriTemplateId);
                    String authType = rs.getString("AUTH_SCHEME");
                    String throttlingTier = rs.getString("THROTTLING_TIER");
                    if (StringUtils.isNotEmpty(scopeName)) {
                        Scope scope = new Scope();
                        scope.setKey(scopeName);
                        uriTemplate.setScope(scope);
                        uriTemplate.setScopes(scope);
                        Set<String> templateScopes = new HashSet<>();
                        templateScopes.add(scopeName);
                        scopeToURITemplateId.put(uriTemplateId, templateScopes);
                    }
                    uriTemplate.setAuthType(authType);
                    uriTemplate.setAuthTypes(authType);
                    uriTemplate.setThrottlingTier(throttlingTier);
                    uriTemplate.setThrottlingTiers(throttlingTier);
                    uriTemplate.setId(uriTemplateId);
                    InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
                    if (mediationScriptBlob != null) {
                        String script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
                        uriTemplate.setMediationScript(script);
                        uriTemplate.setMediationScripts(verb, script);
                    }
                    uriTemplates.put(uriTemplateId, uriTemplate);
                }
            }
            setAssociatedAPIProducts(currentApiUuid, uriTemplates);
            setOperationPolicies(apiRevision.getRevisionUUID(), uriTemplates);
        } catch (SQLException e) {
            handleException("Failed to get URI Templates of API with UUID " + uuid, e);
        }
    } else {
        try (Connection conn = APIMgtDBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(SQLConstants.GET_URL_TEMPLATES_OF_API_SQL)) {
            ps.setString(1, currentApiUuid);
            try (ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    Integer uriTemplateId = rs.getInt("URL_MAPPING_ID");
                    String scopeName = rs.getString("SCOPE_NAME");
                    if (scopeToURITemplateId.containsKey(uriTemplateId) && !StringUtils.isEmpty(scopeName) && !scopeToURITemplateId.get(uriTemplateId).contains(scopeName) && uriTemplates.containsKey(uriTemplateId)) {
                        Scope scope = new Scope();
                        scope.setKey(scopeName);
                        scopeToURITemplateId.get(uriTemplateId).add(scopeName);
                        uriTemplates.get(uriTemplateId).setScopes(scope);
                        continue;
                    }
                    String urlPattern = rs.getString("URL_PATTERN");
                    String verb = rs.getString("HTTP_METHOD");
                    URITemplate uriTemplate = new URITemplate();
                    uriTemplate.setUriTemplate(urlPattern);
                    uriTemplate.setHTTPVerb(verb);
                    uriTemplate.setHttpVerbs(verb);
                    String authType = rs.getString("AUTH_SCHEME");
                    String throttlingTier = rs.getString("THROTTLING_TIER");
                    if (StringUtils.isNotEmpty(scopeName)) {
                        Scope scope = new Scope();
                        scope.setKey(scopeName);
                        uriTemplate.setScope(scope);
                        uriTemplate.setScopes(scope);
                        Set<String> templateScopes = new HashSet<>();
                        templateScopes.add(scopeName);
                        scopeToURITemplateId.put(uriTemplateId, templateScopes);
                    }
                    uriTemplate.setAuthType(authType);
                    uriTemplate.setAuthTypes(authType);
                    uriTemplate.setThrottlingTier(throttlingTier);
                    uriTemplate.setThrottlingTiers(throttlingTier);
                    uriTemplate.setId(uriTemplateId);
                    InputStream mediationScriptBlob = rs.getBinaryStream("MEDIATION_SCRIPT");
                    if (mediationScriptBlob != null) {
                        String script = APIMgtDBUtil.getStringFromInputStream(mediationScriptBlob);
                        uriTemplate.setMediationScript(script);
                        uriTemplate.setMediationScripts(verb, script);
                    }
                    uriTemplates.put(uriTemplateId, uriTemplate);
                }
            }
            setAssociatedAPIProducts(currentApiUuid, uriTemplates);
            setOperationPolicies(currentApiUuid, uriTemplates);
        } catch (SQLException e) {
            handleException("Failed to get URI Templates of API with UUID " + currentApiUuid, e);
        }
    }
    return new LinkedHashSet<>(uriTemplates.values());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) ResultSet(java.sql.ResultSet) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) URITemplate(org.wso2.carbon.apimgt.api.model.URITemplate) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) LinkedHashMap(java.util.LinkedHashMap) Scope(org.wso2.carbon.apimgt.api.model.Scope) ResultSet(java.sql.ResultSet) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet)

Example 12 with APIRevision

use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.

the class ApiMgtDAO method checkAPIUUIDIsARevisionUUID.

/**
 * Get a provided api uuid is in the revision db table
 *
 * @return String apiUUID
 * @throws APIManagementException if an error occurs while checking revision table
 */
public APIRevision checkAPIUUIDIsARevisionUUID(String apiUUID) throws APIManagementException {
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQLConstants.APIRevisionSqlConstants.GET_REVISION_APIID_BY_REVISION_UUID)) {
        statement.setString(1, apiUUID);
        try (ResultSet rs = statement.executeQuery()) {
            if (rs.next()) {
                APIRevision apiRevision = new APIRevision();
                apiRevision.setApiUUID(rs.getString("API_UUID"));
                apiRevision.setId(rs.getInt("ID"));
                apiRevision.setRevisionUUID(apiUUID);
                return apiRevision;
            }
        }
    } catch (SQLException e) {
        handleException("Failed to search UUID: " + apiUUID + " in the revision db table", e);
    }
    return null;
}
Also used : DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 13 with APIRevision

use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.

the class APIProviderImplTest method testGetAPIRevisions.

/**
 * This method tests adding a new API Revision and then retrieving API Revisions by API UUID
 *
 * @throws APIManagementException
 */
@Test
public void testGetAPIRevisions() throws APIManagementException, APIPersistenceException, ArtifactSynchronizerException {
    ImportExportAPI importExportAPI = Mockito.mock(ImportExportAPI.class);
    ArtifactSaver artifactSaver = Mockito.mock(ArtifactSaver.class);
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apiPersistenceInstance, apimgtDAO, importExportAPI, gatewayArtifactsMgtDAO, artifactSaver);
    APIIdentifier apiId = new APIIdentifier("admin", "PizzaShackAPI", "1.0.0", "63e1e37e-a5b8-4be6-86a5-d6ae0749f131");
    API api = new API(apiId);
    api.setContext("/test");
    api.setStatus(APIConstants.CREATED);
    String apiPath = "/apimgt/applicationdata/provider/admin/PizzaShackAPI/1.0.0/api";
    APIRevision apiRevision = new APIRevision();
    apiRevision.setApiUUID("63e1e37e-a5b8-4be6-86a5-d6ae0749f131");
    apiRevision.setDescription("test description revision 1");
    Mockito.when(apimgtDAO.getRevisionCountByAPI(Mockito.anyString())).thenReturn(0);
    Mockito.when(apimgtDAO.getMostRecentRevisionId(Mockito.anyString())).thenReturn(0);
    Mockito.when(APIUtil.getAPIIdentifierFromUUID(Mockito.anyString())).thenReturn(apiId);
    Mockito.when(APIUtil.getAPIPath(apiId)).thenReturn(apiPath);
    Mockito.when(APIUtil.getTenantConfig(Mockito.anyString())).thenReturn(new JSONObject());
    PowerMockito.when(apiPersistenceInstance.addAPIRevision(any(Organization.class), Mockito.anyString(), Mockito.anyInt())).thenReturn("b55e0fc3-9829-4432-b99e-02056dc91838");
    try {
        apiProvider.addAPIRevision(apiRevision, superTenantDomain);
        apiProvider.getAPIRevisions("63e1e37e-a5b8-4be6-86a5-d6ae0749f131");
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
Also used : ArtifactSaver(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.ArtifactSaver) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) JSONObject(org.json.simple.JSONObject) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) XMLStreamException(javax.xml.stream.XMLStreamException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) BlockConditionNotFoundException(org.wso2.carbon.apimgt.api.BlockConditionNotFoundException) FaultGatewaysException(org.wso2.carbon.apimgt.api.FaultGatewaysException) DuplicateAPIException(org.wso2.carbon.apimgt.api.model.DuplicateAPIException) IOException(java.io.IOException) APIMgtResourceAlreadyExistsException(org.wso2.carbon.apimgt.api.APIMgtResourceAlreadyExistsException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException) UserStoreException(org.wso2.carbon.user.api.UserStoreException) GovernanceException(org.wso2.carbon.governance.api.exception.GovernanceException) OMException(org.apache.axiom.om.OMException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

Example 14 with APIRevision

use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.

the class APIProviderImpl method addAPIRevision.

/**
 * Adds a new APIRevision to an existing API
 *
 * @param apiRevision APIRevision
 * @throws APIManagementException if failed to add APIRevision
 */
@Override
public String addAPIRevision(APIRevision apiRevision, String organization) throws APIManagementException {
    int revisionCountPerAPI = apiMgtDAO.getRevisionCountByAPI(apiRevision.getApiUUID());
    int maxRevisionCount = getMaxRevisionCount(organization);
    if (revisionCountPerAPI >= maxRevisionCount) {
        String errorMessage = "Maximum number of revisions per API has reached. " + "Need to remove stale revision to create a new Revision for API with API UUID:" + apiRevision.getApiUUID();
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.MAXIMUM_REVISIONS_REACHED, apiRevision.getApiUUID()));
    }
    int revisionId = apiMgtDAO.getMostRecentRevisionId(apiRevision.getApiUUID()) + 1;
    apiRevision.setId(revisionId);
    APIIdentifier apiId = APIUtil.getAPIIdentifierFromUUID(apiRevision.getApiUUID());
    if (apiId == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiRevision.getApiUUID(), ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiRevision.getApiUUID()));
    }
    apiId.setUuid(apiRevision.getApiUUID());
    String revisionUUID;
    try {
        revisionUUID = apiPersistenceInstance.addAPIRevision(new Organization(organization), apiId.getUUID(), revisionId);
    } catch (APIPersistenceException e) {
        String errorMessage = "Failed to add revision registry artifacts";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.ERROR_CREATING_API_REVISION, apiRevision.getApiUUID()));
    }
    if (StringUtils.isEmpty(revisionUUID)) {
        String errorMessage = "Failed to retrieve revision uuid";
        throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
    }
    apiRevision.setRevisionUUID(revisionUUID);
    apiMgtDAO.addAPIRevision(apiRevision);
    if (importExportAPI != null) {
        try {
            File artifact = importExportAPI.exportAPI(apiRevision.getApiUUID(), revisionUUID, true, ExportFormat.JSON, false, true, organization);
            // Keeping the organization as tenant domain since MG does not support organization-wise deployment
            // Artifacts will be deployed in ST for all organizations
            gatewayArtifactsMgtDAO.addGatewayAPIArtifactAndMetaData(apiRevision.getApiUUID(), apiId.getApiName(), apiId.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, APIConstants.HTTP_PROTOCOL, artifact);
            if (artifactSaver != null) {
                // Keeping the organization as tenant domain since MG does not support organization-wise deployment
                // Artifacts will be deployed in ST for all organizations
                artifactSaver.saveArtifact(apiRevision.getApiUUID(), apiId.getApiName(), apiId.getVersion(), apiRevision.getRevisionUUID(), tenantDomain, artifact);
            }
        } catch (APIImportExportException | ArtifactSynchronizerException e) {
            throw new APIManagementException("Error while Store the Revision Artifact", ExceptionCodes.from(ExceptionCodes.API_REVISION_UUID_NOT_FOUND));
        }
    }
    return revisionUUID;
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ArtifactSynchronizerException(org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.exception.ArtifactSynchronizerException) APIImportExportException(org.wso2.carbon.apimgt.impl.importexport.APIImportExportException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) File(java.io.File)

Example 15 with APIRevision

use of org.wso2.carbon.apimgt.api.model.APIRevision in project carbon-apimgt by wso2.

the class APIProviderImpl method undeployAPIRevisionDeployment.

/**
 * Remove a new APIRevisionDeployment to an existing API
 *
 * @param apiId API UUID
 * @param apiRevisionId API Revision UUID
 * @param apiRevisionDeployments List of APIRevisionDeployment objects
 * @param organization
 * @throws APIManagementException if failed to add APIRevision
 */
@Override
public void undeployAPIRevisionDeployment(String apiId, String apiRevisionId, List<APIRevisionDeployment> apiRevisionDeployments, String organization) throws APIManagementException {
    APIIdentifier apiIdentifier = APIUtil.getAPIIdentifierFromUUID(apiId);
    if (apiIdentifier == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API with API UUID: " + apiId, ExceptionCodes.from(ExceptionCodes.API_NOT_FOUND, apiId));
    }
    APIRevision apiRevision = apiMgtDAO.getRevisionByRevisionUUID(apiRevisionId);
    if (apiRevision == null) {
        throw new APIMgtResourceNotFoundException("Couldn't retrieve existing API Revision with Revision UUID: " + apiRevisionId, ExceptionCodes.from(ExceptionCodes.API_REVISION_NOT_FOUND, apiRevisionId));
    }
    API api = getAPIbyUUID(apiId, apiRevision, organization);
    removeFromGateway(api, new HashSet<>(apiRevisionDeployments), Collections.emptySet());
    apiMgtDAO.removeAPIRevisionDeployment(apiRevisionId, apiRevisionDeployments);
    GatewayArtifactsMgtDAO.getInstance().removePublishedGatewayLabels(apiId, apiRevisionId);
}
Also used : DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) API(org.wso2.carbon.apimgt.api.model.API) ImportExportAPI(org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)

Aggregations

APIRevision (org.wso2.carbon.apimgt.api.model.APIRevision)48 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)28 DeployedAPIRevision (org.wso2.carbon.apimgt.api.model.DeployedAPIRevision)23 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)18 ArrayList (java.util.ArrayList)16 Connection (java.sql.Connection)15 PreparedStatement (java.sql.PreparedStatement)15 ResultSet (java.sql.ResultSet)14 SQLException (java.sql.SQLException)13 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 API (org.wso2.carbon.apimgt.api.model.API)12 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)12 HashSet (java.util.HashSet)11 LinkedHashSet (java.util.LinkedHashSet)11 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)11 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)11 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)11 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)10