Search in sources :

Example 71 with Provider

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

the class PublisherCommonUtils method prepareToCreateAPIByDTO.

/**
 * Prepares the API Model object to be created using the DTO object.
 *
 * @param body        APIDTO of the API
 * @param apiProvider API Provider
 * @param username    Username
 * @param organization  Organization Identifier
 * @return API object to be created
 * @throws APIManagementException Error while creating the API
 */
public static API prepareToCreateAPIByDTO(APIDTO body, APIProvider apiProvider, String username, String organization) throws APIManagementException {
    String context = body.getContext();
    // Make sure context starts with "/". ex: /pizza
    context = context.startsWith("/") ? context : ("/" + context);
    if (body.getAccessControlRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateUserRoles(body.getAccessControlRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    if (body.getAdditionalProperties() != null) {
        String errorMessage = PublisherCommonUtils.validateAdditionalProperties(body.getAdditionalProperties());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.from(ExceptionCodes.INVALID_ADDITIONAL_PROPERTIES, body.getName(), body.getVersion()));
        }
    }
    if (body.getContext() == null) {
        throw new APIManagementException("Parameter: \"context\" cannot be null", ExceptionCodes.PARAMETER_NOT_PROVIDED);
    } else if (body.getContext().endsWith("/")) {
        throw new APIManagementException("Context cannot end with '/' character", ExceptionCodes.INVALID_CONTEXT);
    }
    if (apiProvider.isApiNameWithDifferentCaseExist(body.getName())) {
        throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists.", ExceptionCodes.from(ExceptionCodes.API_NAME_ALREADY_EXISTS, body.getName()));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIUtil.getOAuthConfigurationFromAPIMConfig(APIConstants.AUTHORIZATION_HEADER));
    }
    if (body.getAuthorizationHeader() == null) {
        body.setAuthorizationHeader(APIConstants.AUTHORIZATION_HEADER_DEFAULT);
    }
    if (body.getVisibility() == APIDTO.VisibilityEnum.RESTRICTED && body.getVisibleRoles().isEmpty()) {
        throw new APIManagementException("Valid roles should be added under 'visibleRoles' to restrict " + "the visibility", ExceptionCodes.USER_ROLES_CANNOT_BE_NULL);
    }
    if (body.getVisibleRoles() != null) {
        String errorMessage = PublisherCommonUtils.validateRoles(body.getVisibleRoles());
        if (!errorMessage.isEmpty()) {
            throw new APIManagementException(errorMessage, ExceptionCodes.INVALID_USER_ROLES);
        }
    }
    // Get all existing versions of  api been adding
    List<String> apiVersions = apiProvider.getApiVersionsMatchingApiNameAndOrganization(body.getName(), username, organization);
    if (apiVersions.size() > 0) {
        // If any previous version exists
        for (String version : apiVersions) {
            if (version.equalsIgnoreCase(body.getVersion())) {
                // If version already exists
                if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
                    throw new APIManagementException("Error occurred while " + "adding the API. A duplicate API already exists for " + context + " in the organization : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                } else {
                    throw new APIManagementException("Error occurred while adding API. API with name " + body.getName() + " already exists with different context" + context + " in the organization" + " : " + organization, ExceptionCodes.API_ALREADY_EXISTS);
                }
            }
        }
    } else {
        // If no any previous version exists
        if (apiProvider.isDuplicateContextTemplateMatchingOrganization(context, organization)) {
            throw new APIManagementException("Error occurred while adding the API. A duplicate API context already exists for " + context + " in the organization" + " : " + organization, ExceptionCodes.from(ExceptionCodes.API_CONTEXT_ALREADY_EXISTS, context));
        }
    }
    // Check if the user has admin permission before applying a different provider than the current user
    String provider = body.getProvider();
    if (!StringUtils.isBlank(provider) && !provider.equals(username)) {
        if (!APIUtil.hasPermission(username, APIConstants.Permissions.APIM_ADMIN)) {
            if (log.isDebugEnabled()) {
                log.debug("User " + username + " does not have admin permission (" + APIConstants.Permissions.APIM_ADMIN + ") hence provider (" + provider + ") overridden with current user (" + username + ")");
            }
            provider = username;
        } else {
            if (!APIUtil.isUserExist(provider)) {
                throw new APIManagementException("Specified provider " + provider + " not exist.", ExceptionCodes.PARAMETER_NOT_PROVIDED);
            }
        }
    } else {
        // Set username in case provider is null or empty
        provider = username;
    }
    List<String> tiersFromDTO = body.getPolicies();
    // check whether the added API's tiers are all valid
    Set<Tier> definedTiers = apiProvider.getTiers();
    List<String> invalidTiers = getInvalidTierNames(definedTiers, tiersFromDTO);
    if (invalidTiers.size() > 0) {
        throw new APIManagementException("Specified tier(s) " + Arrays.toString(invalidTiers.toArray()) + " are invalid", ExceptionCodes.TIER_NAME_INVALID);
    }
    APIPolicy apiPolicy = apiProvider.getAPIPolicy(username, body.getApiThrottlingPolicy());
    if (apiPolicy == null && body.getApiThrottlingPolicy() != null) {
        throw new APIManagementException("Specified policy " + body.getApiThrottlingPolicy() + " is invalid", ExceptionCodes.UNSUPPORTED_THROTTLE_LIMIT_TYPE);
    }
    API apiToAdd = APIMappingUtil.fromDTOtoAPI(body, provider);
    // only allow CREATED as the stating state for the new api if not status is PROTOTYPED
    if (!APIConstants.PROTOTYPED.equals(apiToAdd.getStatus())) {
        apiToAdd.setStatus(APIConstants.CREATED);
    }
    if (!apiToAdd.isAdvertiseOnly() || StringUtils.isBlank(apiToAdd.getApiOwner())) {
        // we are setting the api owner as the logged in user until we support checking admin privileges and
        // assigning the owner as a different user
        apiToAdd.setApiOwner(provider);
    }
    if (body.getKeyManagers() instanceof List) {
        apiToAdd.setKeyManagers((List<String>) body.getKeyManagers());
    } else if (body.getKeyManagers() == null) {
        apiToAdd.setKeyManagers(Collections.singletonList(APIConstants.KeyManager.API_LEVEL_ALL_KEY_MANAGERS));
    } else {
        throw new APIManagementException("KeyManagers value need to be an array");
    }
    // Set default gatewayVendor
    if (body.getGatewayVendor() == null) {
        apiToAdd.setGatewayVendor(APIConstants.WSO2_GATEWAY_ENVIRONMENT);
    }
    apiToAdd.setOrganization(organization);
    return apiToAdd;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Tier(org.wso2.carbon.apimgt.api.model.Tier) API(org.wso2.carbon.apimgt.api.model.API) List(java.util.List) ArrayList(java.util.ArrayList) APIPolicy(org.wso2.carbon.apimgt.api.model.policy.APIPolicy)

Example 72 with Provider

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

the class ImportUtils method getValidatedDeploymentsList.

/**
 * This method is used to validate the Gateway environments from the deployment environments file. Gateway
 * environments will be validated with a set of all the labels and environments of the tenant domain. If
 * environment is not found in this set, it will be skipped with an error message in the console. This method is
 * common to both APIs and API Products
 *
 * @param deploymentInfoArray Deployment environment array found in the import artifact
 * @param tenantDomain        Tenant domain
 * @param apiProvider         Provider of the API/ API Product
 * @return a list of API/API Product revision deployments ready to be deployed.
 * @throws APIManagementException If an error occurs when validating the deployments list
 */
private static List<APIRevisionDeployment> getValidatedDeploymentsList(JsonArray deploymentInfoArray, String tenantDomain, APIProvider apiProvider, String organization) throws APIManagementException {
    List<APIRevisionDeployment> apiRevisionDeployments = new ArrayList<>();
    if (deploymentInfoArray != null && deploymentInfoArray.size() > 0) {
        Map<String, Environment> gatewayEnvironments = APIUtil.getEnvironments(organization);
        for (int i = 0; i < deploymentInfoArray.size(); i++) {
            JsonObject deploymentJson = deploymentInfoArray.get(i).getAsJsonObject();
            JsonElement deploymentNameElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_NAME);
            if (deploymentNameElement != null) {
                String deploymentName = deploymentNameElement.getAsString();
                Environment gatewayEnvironment = gatewayEnvironments.get(deploymentName);
                if (gatewayEnvironment != null) {
                    JsonElement deploymentVhostElement = deploymentJson.get(ImportExportConstants.DEPLOYMENT_VHOST);
                    String deploymentVhost;
                    if (deploymentVhostElement != null) {
                        deploymentVhost = deploymentVhostElement.getAsString();
                    } else {
                        // set the default vhost of the given environment
                        if (gatewayEnvironment.getVhosts().isEmpty()) {
                            throw new APIManagementException("No VHosts defined for the environment: " + deploymentName);
                        }
                        deploymentVhost = gatewayEnvironment.getVhosts().get(0).getHost();
                    }
                    // resolve vhost to null if it is the default vhost of read only environment
                    deploymentVhost = VHostUtils.resolveIfDefaultVhostToNull(deploymentName, deploymentVhost);
                    JsonElement displayOnDevportalElement = deploymentJson.get(ImportExportConstants.DISPLAY_ON_DEVPORTAL_OPTION);
                    boolean displayOnDevportal = displayOnDevportalElement == null || displayOnDevportalElement.getAsBoolean();
                    APIRevisionDeployment apiRevisionDeployment = new APIRevisionDeployment();
                    apiRevisionDeployment.setDeployment(deploymentName);
                    apiRevisionDeployment.setVhost(deploymentVhost);
                    apiRevisionDeployment.setDisplayOnDevportal(displayOnDevportal);
                    apiRevisionDeployments.add(apiRevisionDeployment);
                } else {
                    throw new APIManagementException("Label " + deploymentName + " is not a defined gateway environment. Hence " + "skipped without deployment", ExceptionCodes.from(ExceptionCodes.GATEWAY_ENVIRONMENT_NOT_FOUND, String.format("label '%s'", deploymentName)));
                }
            }
        }
    }
    return apiRevisionDeployments;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) ArrayList(java.util.ArrayList) Environment(org.wso2.carbon.apimgt.api.model.Environment) JsonObject(com.google.gson.JsonObject) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)

Example 73 with Provider

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

the class WebhooksUtils method publishAnalyticsData.

public static void publishAnalyticsData(MessageContext messageContext) {
    org.apache.axis2.context.MessageContext axisCtx = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
    axisCtx.setProperty(PassThroughConstants.SYNAPSE_ARTIFACT_TYPE, APIConstants.API_TYPE_WEBSUB);
    WebhooksAnalyticsDataProvider provider = new WebhooksAnalyticsDataProvider(messageContext);
    GenericRequestDataCollector dataCollector = new GenericRequestDataCollector(provider);
    try {
        dataCollector.collectData();
    } catch (AnalyticsException e) {
        log.error("Error occurred when collecting data", e);
    }
}
Also used : WebhooksAnalyticsDataProvider(org.wso2.carbon.apimgt.gateway.handlers.streaming.webhook.WebhooksAnalyticsDataProvider) GenericRequestDataCollector(org.wso2.carbon.apimgt.common.analytics.collectors.impl.GenericRequestDataCollector) AnalyticsException(org.wso2.carbon.apimgt.common.analytics.exceptions.AnalyticsException) Axis2MessageContext(org.apache.synapse.core.axis2.Axis2MessageContext)

Example 74 with Provider

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

the class SystemScopesIssuer method configureForJWTGrant.

protected void configureForJWTGrant(OAuthTokenReqMessageContext tokReqMsgCtx) {
    SignedJWT signedJWT = null;
    JWTClaimsSet claimsSet = null;
    String[] roles = null;
    try {
        signedJWT = getSignedJWT(tokReqMsgCtx);
    } catch (IdentityOAuth2Exception e) {
        log.error("Couldn't retrieve signed JWT", e);
    }
    if (signedJWT != null) {
        claimsSet = getClaimSet(signedJWT);
    }
    String jwtIssuer = claimsSet != null ? claimsSet.getIssuer() : null;
    String tenantDomain = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain();
    try {
        identityProvider = IdentityProviderManager.getInstance().getIdPByName(jwtIssuer, tenantDomain);
        if (identityProvider != null) {
            if (StringUtils.equalsIgnoreCase(identityProvider.getIdentityProviderName(), "default")) {
                identityProvider = this.getResidentIDPForIssuer(tenantDomain, jwtIssuer);
                if (identityProvider == null) {
                    log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
                }
            }
        } else {
            log.error("No Registered IDP found for the JWT with issuer name : " + jwtIssuer);
        }
    } catch (IdentityProviderManagementException | IdentityOAuth2Exception e) {
        log.error("Couldn't initiate identity provider instance", e);
    }
    try {
        roles = claimsSet != null ? claimsSet.getStringArrayClaim(identityProvider.getClaimConfig().getRoleClaimURI()) : null;
    } catch (ParseException e) {
        log.error("Couldn't retrieve roles:", e);
    }
    List<String> updatedRoles = new ArrayList<>();
    if (roles != null) {
        for (String role : roles) {
            String updatedRoleClaimValue = getUpdatedRoleClaimValue(identityProvider, role);
            if (updatedRoleClaimValue != null) {
                updatedRoles.add(updatedRoleClaimValue);
            } else {
                updatedRoles.add(role);
            }
        }
    }
    AuthenticatedUser user = tokReqMsgCtx.getAuthorizedUser();
    Map<ClaimMapping, String> userAttributes = user.getUserAttributes();
    String roleClaim = identityProvider.getClaimConfig().getRoleClaimURI();
    if (roleClaim != null) {
        userAttributes.put(ClaimMapping.build(roleClaim, roleClaim, null, false), updatedRoles.toString().replace(" ", ""));
        tokReqMsgCtx.addProperty(APIConstants.SystemScopeConstants.ROLE_CLAIM, roleClaim);
    }
    user.setUserAttributes(userAttributes);
    tokReqMsgCtx.setAuthorizedUser(user);
}
Also used : SignedJWT(com.nimbusds.jwt.SignedJWT) AuthenticatedUser(org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser) IdentityOAuth2Exception(org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception) JWTClaimsSet(com.nimbusds.jwt.JWTClaimsSet) ParseException(java.text.ParseException) IdentityProviderManagementException(org.wso2.carbon.idp.mgt.IdentityProviderManagementException)

Example 75 with Provider

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

the class SequenceUtilsTestCase method testUpdateRestToSoapConvertedSequences.

@Test
public void testUpdateRestToSoapConvertedSequences() throws Exception {
    String provider = "admin";
    String apiName = "test-api";
    String version = "1.0.0";
    String seqType = "in";
    String sequence = "{\"test\":{\"method\":\"post\",\"content\":\"<header></header>\"}}";
    Resource resource = Mockito.mock(Resource.class);
    PowerMockito.when(MultitenantUtils.getTenantDomain(Mockito.anyString())).thenReturn("carbon.super");
    PowerMockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(userRegistry.resourceExists(Mockito.anyString())).thenReturn(true);
    Mockito.when(userRegistry.get(Mockito.anyString())).thenReturn(resource);
    Mockito.when(tenantManager.getTenantId(Mockito.anyString())).thenReturn(-1);
    try {
        SequenceUtils.updateRestToSoapConvertedSequences(apiName, version, provider, seqType, sequence);
    } catch (APIManagementException e) {
        Assert.fail("Failed to update the sequence in the registry");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Resource(org.wso2.carbon.registry.core.Resource) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)82 ArrayList (java.util.ArrayList)70 API (org.wso2.carbon.apimgt.api.model.API)64 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)50 Test (org.junit.Test)49 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)45 HashMap (java.util.HashMap)40 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)36 IOException (java.io.IOException)35 Resource (org.wso2.carbon.registry.core.Resource)34 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)32 HashSet (java.util.HashSet)30 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)29 UserStoreException (org.wso2.carbon.user.api.UserStoreException)29 PreparedStatement (java.sql.PreparedStatement)28 Connection (java.sql.Connection)27 SQLException (java.sql.SQLException)27 ResultSet (java.sql.ResultSet)25 QName (javax.xml.namespace.QName)25 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)25