Search in sources :

Example 81 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class APIManagerConfigurationTest method testEnvironmentsConfigWithAdditionalProperties.

@Test
public void testEnvironmentsConfigWithAdditionalProperties() throws XMLStreamException, APIManagementException {
    String envConfig = "<Environment type=\"hybrid\" api-console=\"true\" isDefault=\"true\">\n" + "                <Name>Default</Name>\n" + "                <DisplayName></DisplayName>\n" + "                <Description>This is a hybrid gateway that handles both production and sandbox token traffic.</Description>\n" + "                <!-- Server URL of the API gateway -->\n" + "                <ServerURL>https://localhost:9440/services/</ServerURL>\n" + "                <!-- Admin username for the API gateway. -->\n" + "                <Username>${admin.username}</Username>\n" + "                <!-- Admin password for the API gateway.-->\n" + "                <Password>${admin.password}</Password>\n" + "                <!-- Provider Vendor of the API gateway.-->\n" + "                <Provider>wso2</Provider>\n" + "                <!-- Endpoint URLs for the APIs hosted in this API gateway.-->\n" + "                <GatewayEndpoint>https://localhost:9440,http://localhost:9440</GatewayEndpoint>\n" + "                <!-- Additional properties for External Gateways -->\n" + "                <!-- Endpoint URLs of the WebSocket APIs hosted in this API Gateway -->\n" + "                <GatewayWSEndpoint>ws://localhost:9099,wss://localhost:8099</GatewayWSEndpoint>\n" + "                <!-- Endpoint URLs of the WebSub APIs hosted in this API Gateway -->\n" + "                <GatewayWebSubEndpoint>http://localhost:9021,https://localhost:8021</GatewayWebSubEndpoint>\n" + "                <Properties>\n" + "                    <Property name=\"Organization\">WSO2</Property>\n" + "                    <Property name=\"DisplayName\">Development Environment</Property>\n" + "                    <Property name=\"DevAccountName\">dev-1</Property>\n" + "                </Properties>\n" + "                <VirtualHosts>\n" + "                </VirtualHosts>\n" + "            </Environment>";
    OMElement element = AXIOMUtil.stringToOM(envConfig);
    APIManagerConfiguration config = new APIManagerConfiguration();
    config.setEnvironmentConfig(element);
    Map<String, Environment> environmentsList = config.getGatewayEnvironments();
    Assert.assertFalse(environmentsList.isEmpty());
    Environment defaultEnv = environmentsList.get("Default");
    Assert.assertFalse(defaultEnv.getAdditionalProperties().isEmpty());
}
Also used : Environment(org.wso2.carbon.apimgt.api.model.Environment) OMElement(org.apache.axiom.om.OMElement) Test(org.junit.Test)

Example 82 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPIProductForStateChange.

/**
 * Update API Product in registry for lifecycle state change
 *
 * @param apiProduct    API Product Object
 * @param currentStatus Current state of API Product
 * @param newStatus     New state of API Product
 * @return boolean indicates success or failure
 * @throws APIManagementException if there is an error when updating API Product for lifecycle state
 * @throws FaultGatewaysException if there is an error when updating API Product for lifecycle state
 */
public void updateAPIProductForStateChange(APIProduct apiProduct, String currentStatus, String newStatus) throws APIManagementException, FaultGatewaysException {
    String provider = apiProduct.getId().getProviderName();
    boolean isTenantFlowStarted = false;
    try {
        String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(provider));
        if (tenantDomain != null && !MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            isTenantFlowStarted = true;
            PrivilegedCarbonContext.startTenantFlow();
            PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantDomain, true);
        }
        if (!currentStatus.equals(newStatus)) {
            apiProduct.setState(newStatus);
            // If API status changed to publish we should add it to recently added APIs list
            // this should happen in store-publisher cluster domain if deployment is distributed
            // IF new API published we will add it to recently added APIs
            Caching.getCacheManager(APIConstants.API_MANAGER_CACHE_MANAGER).getCache(APIConstants.RECENTLY_ADDED_API_CACHE_NAME).removeAll();
            if (APIConstants.RETIRED.equals(newStatus)) {
                cleanUpPendingSubscriptionCreationProcessesByAPI(apiProduct.getUuid());
                apiMgtDAO.removeAllSubscriptions(apiProduct.getUuid());
                deleteAPIProductRevisions(apiProduct.getUuid(), tenantDomain);
            }
            PublisherAPIProduct publisherAPIProduct = APIProductMapper.INSTANCE.toPublisherApiProduct(apiProduct);
            try {
                apiPersistenceInstance.updateAPIProduct(new Organization(apiProduct.getOrganization()), publisherAPIProduct);
            } catch (APIPersistenceException e) {
                handleException("Error while persisting the updated API Product", e);
            }
        }
    } finally {
        if (isTenantFlowStarted) {
            PrivilegedCarbonContext.endTenantFlow();
        }
    }
}
Also used : APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) PublisherAPIProduct(org.wso2.carbon.apimgt.persistence.dto.PublisherAPIProduct)

Example 83 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class APIProviderImpl method updateAPI.

/**
 * Updates an existing API
 *
 * @param api API
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to update API
 * @throws org.wso2.carbon.apimgt.api.FaultGatewaysException on Gateway Failure
 */
@Override
public void updateAPI(API api) throws APIManagementException, FaultGatewaysException {
    boolean isValid = isAPIUpdateValid(api);
    if (!isValid) {
        throw new APIManagementException(" User doesn't have permission for update");
    }
    API oldApi = getAPIbyUUID(api.getUuid(), api.getOrganization());
    String organization = api.getOrganization();
    if (!oldApi.getStatus().equals(api.getStatus())) {
        // Use changeAPIStatus for that kind of updates.
        throw new APIManagementException("Invalid API update operation involving API status changes");
    }
    validateKeyManagers(api);
    Gson gson = new Gson();
    Map<String, String> oldMonetizationProperties = gson.fromJson(oldApi.getMonetizationProperties().toString(), HashMap.class);
    if (oldMonetizationProperties != null && !oldMonetizationProperties.isEmpty()) {
        Map<String, String> newMonetizationProperties = gson.fromJson(api.getMonetizationProperties().toString(), HashMap.class);
        if (newMonetizationProperties != null) {
            for (Map.Entry<String, String> entry : oldMonetizationProperties.entrySet()) {
                String newValue = newMonetizationProperties.get(entry.getKey());
                if (StringUtils.isAllBlank(newValue)) {
                    newMonetizationProperties.put(entry.getKey(), entry.getValue());
                }
            }
            JSONParser parser = new JSONParser();
            try {
                JSONObject jsonObj = (JSONObject) parser.parse(gson.toJson(newMonetizationProperties));
                api.setMonetizationProperties(jsonObj);
            } catch (ParseException e) {
                throw new APIManagementException("Error when parsing monetization properties ", e);
            }
        }
    }
    String publishedDefaultVersion = getPublishedDefaultVersion(api.getId());
    // Update WSDL in the registry
    if (api.getWsdlUrl() != null && api.getWsdlResource() == null) {
        updateWsdlFromUrl(api);
    }
    if (api.getWsdlResource() != null) {
        updateWsdlFromResourceFile(api);
    }
    boolean updatePermissions = false;
    if (APIUtil.isAccessControlEnabled()) {
        if (!oldApi.getAccessControl().equals(api.getAccessControl()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getAccessControl()) && !api.getAccessControlRoles().equals(oldApi.getAccessControlRoles())) || !oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
            updatePermissions = true;
        }
    } else if (!oldApi.getVisibility().equals(api.getVisibility()) || (APIConstants.API_RESTRICTED_VISIBILITY.equals(oldApi.getVisibility()) && !api.getVisibleRoles().equals(oldApi.getVisibleRoles()))) {
        updatePermissions = true;
    }
    updateEndpointSecurity(oldApi, api);
    String apiUUid = updateApiArtifact(api, true, updatePermissions);
    api.setUuid(apiUUid);
    if (!oldApi.getContext().equals(api.getContext())) {
        api.setApiHeaderChanged(true);
    }
    int tenantId;
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(api.getId().getProviderName()));
    try {
        tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new APIManagementException("Error in retrieving Tenant Information while updating api :" + api.getId().getApiName(), e);
    }
    validateResourceThrottlingTiers(api, tenantDomain);
    // get product resource mappings on API before updating the API. Update uri templates on api will remove all
    // product mappings as well.
    List<APIProductResource> productResources = apiMgtDAO.getProductMappingsForAPI(api);
    updateAPI(api, tenantId, userNameWithoutChange);
    updateProductResourceMappings(api, organization, productResources);
    if (log.isDebugEnabled()) {
        log.debug("Successfully updated the API: " + api.getId() + " in the database");
    }
    JSONObject apiLogObject = new JSONObject();
    apiLogObject.put(APIConstants.AuditLogConstants.NAME, api.getId().getApiName());
    apiLogObject.put(APIConstants.AuditLogConstants.CONTEXT, api.getContext());
    apiLogObject.put(APIConstants.AuditLogConstants.VERSION, api.getId().getVersion());
    apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, api.getId().getProviderName());
    APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API, apiLogObject.toString(), APIConstants.AuditLogConstants.UPDATED, this.username);
    // update doc visibility
    List<Documentation> docsList = getAllDocumentation(api.getId());
    if (docsList != null) {
        Iterator it = docsList.iterator();
        while (it.hasNext()) {
            Object docsObject = it.next();
            Documentation docs = (Documentation) docsObject;
            updateDocVisibility(api, docs);
        }
    }
    // notify key manager with API update
    registerOrUpdateResourceInKeyManager(api, tenantDomain);
    int apiId = apiMgtDAO.getAPIID(api.getUuid());
    if (publishedDefaultVersion != null) {
        if (api.isPublishedDefaultVersion() && !api.getId().getVersion().equals(publishedDefaultVersion)) {
            APIIdentifier previousDefaultVersionIdentifier = new APIIdentifier(api.getId().getProviderName(), api.getId().getApiName(), publishedDefaultVersion);
            sendUpdateEventToPreviousDefaultVersion(previousDefaultVersionIdentifier, organization);
        }
    }
    APIEvent apiEvent = new APIEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.API_UPDATE.name(), tenantId, tenantDomain, api.getId().getApiName(), apiId, api.getUuid(), api.getId().getVersion(), api.getType(), api.getContext(), APIUtil.replaceEmailDomainBack(api.getId().getProviderName()), api.getStatus());
    APIUtil.sendNotification(apiEvent, APIConstants.NotifierType.API.name());
    // Extracting API details for the recommendation system
    if (recommendationEnvironment != null) {
        RecommenderEventPublisher extractor = new RecommenderDetailsExtractor(api, tenantDomain, APIConstants.ADD_API);
        Thread recommendationThread = new Thread(extractor);
        recommendationThread.start();
    }
}
Also used : RecommenderDetailsExtractor(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderDetailsExtractor) Documentation(org.wso2.carbon.apimgt.api.model.Documentation) Gson(com.google.gson.Gson) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) APIEvent(org.wso2.carbon.apimgt.impl.notifier.events.APIEvent) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) UserStoreException(org.wso2.carbon.user.api.UserStoreException) Iterator(java.util.Iterator) RecommenderEventPublisher(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommenderEventPublisher) 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) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) ParseException(org.json.simple.parser.ParseException) Map(java.util.Map) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 84 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class APIProviderImpl method deleteAPIProduct.

public void deleteAPIProduct(APIProduct apiProduct) throws APIManagementException {
    APIProductIdentifier identifier = apiProduct.getId();
    try {
        // int apiId = apiMgtDAO.getAPIID(identifier, null);
        long subsCount = apiMgtDAO.getAPISubscriptionCountByAPI(identifier);
        if (subsCount > 0) {
            // Logging as a WARN since this isn't an error scenario.
            String message = "Cannot remove the API Product as active subscriptions exist.";
            log.warn(message);
            throw new APIManagementException(message);
        }
        // gatewayType check is required when API Management is deployed on
        // other servers to avoid synapse
        deleteAPIProductRevisions(apiProduct.getUuid(), apiProduct.getOrganization());
        apiPersistenceInstance.deleteAPIProduct(new Organization(apiProduct.getOrganization()), apiProduct.getUuid());
        apiMgtDAO.deleteAPIProduct(identifier);
        cleanUpPendingAPIStateChangeTask(apiProduct.getProductId(), true);
        if (log.isDebugEnabled()) {
            String logMessage = "API Product Name: " + identifier.getName() + ", API Product Version " + identifier.getVersion() + " successfully removed from the database.";
            log.debug(logMessage);
        }
        JSONObject apiLogObject = new JSONObject();
        apiLogObject.put(APIConstants.AuditLogConstants.NAME, identifier.getName());
        apiLogObject.put(APIConstants.AuditLogConstants.VERSION, identifier.getVersion());
        apiLogObject.put(APIConstants.AuditLogConstants.PROVIDER, identifier.getProviderName());
        APIUtil.logAuditMessage(APIConstants.AuditLogConstants.API_PRODUCT, apiLogObject.toString(), APIConstants.AuditLogConstants.DELETED, this.username);
        GatewayArtifactsMgtDAO.getInstance().deleteGatewayArtifacts(apiProduct.getUuid());
    } catch (APIPersistenceException e) {
        handleException("Failed to remove the API product", e);
    } catch (WorkflowException e) {
        handleException("Error while removing the pending workflows of API Product", e);
    }
}
Also used : APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) APIPersistenceException(org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException) Organization(org.wso2.carbon.apimgt.persistence.dto.Organization) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONObject(org.json.simple.JSONObject) WorkflowException(org.wso2.carbon.apimgt.impl.workflow.WorkflowException)

Example 85 with Organization

use of org.wso2.carbon.apimgt.persistence.dto.Organization in project carbon-apimgt by wso2.

the class APIProviderImpl method calculateVersionTimestamp.

private String calculateVersionTimestamp(String provider, String name, String version, String org) throws APIManagementException {
    if (StringUtils.isEmpty(provider) || StringUtils.isEmpty(name) || StringUtils.isEmpty(org)) {
        throw new APIManagementException("Invalid API information, name=" + name + " provider=" + provider + " organization=" + org);
    }
    TreeMap<String, API> apiSortedMap = new TreeMap<>();
    List<API> apiList = getAPIVersionsByProviderAndName(provider, name, org);
    for (API mappedAPI : apiList) {
        apiSortedMap.put(mappedAPI.getVersionTimestamp(), mappedAPI);
    }
    APIVersionStringComparator comparator = new APIVersionStringComparator();
    String latestVersion = version;
    long previousTimestamp = 0L;
    String latestTimestamp = "";
    for (API tempAPI : apiSortedMap.values()) {
        if (comparator.compare(tempAPI.getId().getVersion(), latestVersion) > 0) {
            latestTimestamp = String.valueOf((previousTimestamp + Long.valueOf(tempAPI.getVersionTimestamp())) / 2);
            break;
        } else {
            previousTimestamp = Long.valueOf(tempAPI.getVersionTimestamp());
        }
    }
    if (StringUtils.isEmpty(latestTimestamp)) {
        latestTimestamp = String.valueOf(System.currentTimeMillis());
    }
    return latestTimestamp;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) 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) APIVersionStringComparator(org.wso2.carbon.apimgt.impl.utils.APIVersionStringComparator) TreeMap(java.util.TreeMap)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)304 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)106 API (org.wso2.carbon.apimgt.api.model.API)100 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)89 ArrayList (java.util.ArrayList)79 APIPersistenceException (org.wso2.carbon.apimgt.persistence.exceptions.APIPersistenceException)72 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)70 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)65 Organization (org.wso2.carbon.apimgt.persistence.dto.Organization)64 IOException (java.io.IOException)61 Registry (org.wso2.carbon.registry.core.Registry)58 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)57 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)56 HashMap (java.util.HashMap)54 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)53 Resource (org.wso2.carbon.registry.core.Resource)51 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)49 JSONObject (org.json.simple.JSONObject)45 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)44 URISyntaxException (java.net.URISyntaxException)42