Search in sources :

Example 81 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class APIMappingUtil method fromAPIRevisionToEndpoints.

private static APIEndpointURLsDTO fromAPIRevisionToEndpoints(APIDTO apidto, Environment environment, String host, String customGatewayUrl, String tenantDomain) throws APIManagementException {
    // Deployed VHost
    VHost vHost;
    String context = apidto.getContext();
    if (StringUtils.isEmpty(customGatewayUrl)) {
        vHost = VHostUtils.getVhostFromEnvironment(environment, host);
    } else {
        if (!StringUtils.contains(customGatewayUrl, "://")) {
            customGatewayUrl = APIConstants.HTTPS_PROTOCOL_URL_PREFIX + customGatewayUrl;
        }
        vHost = VHost.fromEndpointUrls(new String[] { customGatewayUrl });
        context = context.replace("/t/" + tenantDomain, "");
    }
    APIEndpointURLsDTO apiEndpointURLsDTO = new APIEndpointURLsDTO();
    apiEndpointURLsDTO.setEnvironmentName(environment.getName());
    apiEndpointURLsDTO.setEnvironmentDisplayName(environment.getDisplayName());
    apiEndpointURLsDTO.setEnvironmentType(environment.getType());
    APIURLsDTO apiurLsDTO = new APIURLsDTO();
    boolean isWs = StringUtils.equalsIgnoreCase("WS", apidto.getType());
    boolean isGQLSubscription = StringUtils.equalsIgnoreCase(APIConstants.GRAPHQL_API, apidto.getType()) && isGraphQLSubscriptionsAvailable(apidto);
    if (!isWs) {
        if (apidto.getTransport().contains(APIConstants.HTTP_PROTOCOL)) {
            apiurLsDTO.setHttp(vHost.getHttpUrl() + context);
        }
        if (apidto.getTransport().contains(APIConstants.HTTPS_PROTOCOL)) {
            apiurLsDTO.setHttps(vHost.getHttpsUrl() + context);
        }
    }
    if (isWs || isGQLSubscription) {
        apiurLsDTO.setWs(vHost.getWsUrl() + context);
        apiurLsDTO.setWss(vHost.getWssUrl() + context);
    }
    apiEndpointURLsDTO.setUrLs(apiurLsDTO);
    APIDefaultVersionURLsDTO apiDefaultVersionURLsDTO = new APIDefaultVersionURLsDTO();
    if (apidto.isIsDefaultVersion() != null && apidto.isIsDefaultVersion()) {
        String defaultContext = context.replaceAll("/" + apidto.getVersion() + "$", "");
        if (!isWs) {
            if (apidto.getTransport().contains(APIConstants.HTTP_PROTOCOL)) {
                apiDefaultVersionURLsDTO.setHttp(vHost.getHttpUrl() + defaultContext);
            }
            if (apidto.getTransport().contains(APIConstants.HTTPS_PROTOCOL)) {
                apiDefaultVersionURLsDTO.setHttps(vHost.getHttpsUrl() + defaultContext);
            }
        }
        if (isWs || isGQLSubscription) {
            apiDefaultVersionURLsDTO.setWs(vHost.getWsUrl() + defaultContext);
            apiDefaultVersionURLsDTO.setWss(vHost.getWssUrl() + defaultContext);
        }
    }
    apiEndpointURLsDTO.setDefaultVersionURLs(apiDefaultVersionURLsDTO);
    return apiEndpointURLsDTO;
}
Also used : VHost(org.wso2.carbon.apimgt.api.model.VHost) APIURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIURLsDTO) APIDefaultVersionURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIDefaultVersionURLsDTO) APIEndpointURLsDTO(org.wso2.carbon.apimgt.rest.api.store.v1.dto.APIEndpointURLsDTO)

Example 82 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method getWSDLOfAPI.

@Override
public Response getWSDLOfAPI(String apiId, String environmentName, String ifNoneMatch, String xWSO2Tenant, MessageContext messageContext) throws APIManagementException {
    String organization = RestApiUtil.getValidatedOrganization(messageContext);
    APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
    API api = apiConsumer.getLightweightAPIByUUID(apiId, organization);
    APIIdentifier apiIdentifier = api.getId();
    List<Environment> environments = APIUtil.getEnvironmentsOfAPI(api);
    if (environments != null && environments.size() > 0) {
        if (StringUtils.isEmpty(environmentName)) {
            environmentName = api.getEnvironments().iterator().next();
        }
        Environment selectedEnvironment = null;
        for (Environment environment : environments) {
            if (environment.getName().equals(environmentName)) {
                selectedEnvironment = environment;
                break;
            }
        }
        if (selectedEnvironment == null) {
            throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.INVALID_GATEWAY_ENVIRONMENT, environmentName));
        }
        ResourceFile wsdl = apiConsumer.getWSDL(api, selectedEnvironment.getName(), selectedEnvironment.getType(), organization);
        return RestApiUtil.getResponseFromResourceFile(apiIdentifier.toString(), wsdl);
    } else {
        throw new APIManagementException(ExceptionCodes.from(ExceptionCodes.NO_GATEWAY_ENVIRONMENTS_ADDED, apiIdentifier.toString()));
    }
}
Also used : ResourceFile(org.wso2.carbon.apimgt.api.model.ResourceFile) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Environment(org.wso2.carbon.apimgt.api.model.Environment) API(org.wso2.carbon.apimgt.api.model.API) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 83 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class ApisApiServiceImpl method apisApiIdSwaggerGet.

/**
 * Retrieves the swagger document of an API
 *
 * @param apiId API identifier
 * @param environmentName name of the gateway environment
 * @param ifNoneMatch If-None-Match header value
 * @param xWSO2Tenant requested tenant domain for cross tenant invocations
 * @param messageContext CXF message context
 * @return Swagger document of the API for the given cluster or gateway environment
 */
@Override
public Response apisApiIdSwaggerGet(String apiId, String environmentName, String ifNoneMatch, String xWSO2Tenant, MessageContext messageContext) {
    try {
        String organization = RestApiUtil.getValidatedOrganization(messageContext);
        APIConsumer apiConsumer = RestApiCommonUtil.getLoggedInUserConsumer();
        API api = apiConsumer.getLightweightAPIByUUID(apiId, organization);
        if (api.getUuid() == null) {
            api.setUuid(apiId);
        }
        if (api.getSwaggerDefinition() != null) {
            api.setSwaggerDefinition(APIUtil.removeXMediationScriptsFromSwagger(api.getSwaggerDefinition()));
        } else {
            api.setSwaggerDefinition(apiConsumer.getOpenAPIDefinition(apiId, organization));
        }
        // gets the first available environment if environment is not provided
        if (StringUtils.isEmpty(environmentName)) {
            Map<String, Environment> existingEnvironments = APIUtil.getEnvironments(organization);
            // then the old gateway environment name becomes invalid
            for (String environmentNameOfApi : api.getEnvironments()) {
                if (existingEnvironments.get(environmentNameOfApi) != null) {
                    environmentName = environmentNameOfApi;
                    break;
                }
            }
            // if all environment of API are invalid or there are no environments (i.e. empty)
            if (StringUtils.isEmpty(environmentName)) {
                // This is to make sure the swagger doesn't have invalid endpoints
                if (!existingEnvironments.keySet().isEmpty()) {
                    environmentName = existingEnvironments.keySet().iterator().next();
                }
            }
        }
        String apiSwagger = null;
        if (StringUtils.isNotEmpty(environmentName)) {
            try {
                apiSwagger = apiConsumer.getOpenAPIDefinitionForEnvironment(api, environmentName);
            } catch (APIManagementException e) {
                // handle gateway not found exception otherwise pass it
                if (RestApiUtil.isDueToResourceNotFound(e)) {
                    RestApiUtil.handleResourceNotFoundError("Gateway environment '" + environmentName + "' not found", e, log);
                    return null;
                }
                throw e;
            }
        } else {
            apiSwagger = api.getSwaggerDefinition();
        }
        return Response.ok().entity(apiSwagger).header("Content-Disposition", "attachment; filename=\"" + "swagger.json" + "\"").build();
    } catch (APIManagementException e) {
        if (RestApiUtil.isDueToAuthorizationFailure(e)) {
            RestApiUtil.handleAuthorizationFailure(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else if (RestApiUtil.isDueToResourceNotFound(e)) {
            RestApiUtil.handleResourceNotFoundError(RestApiConstants.RESOURCE_API, apiId, e, log);
        } else {
            String errorMessage = "Error while retrieving swagger of API : " + apiId;
            RestApiUtil.handleInternalServerError(errorMessage, e, log);
        }
    }
    return null;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) Environment(org.wso2.carbon.apimgt.api.model.Environment) API(org.wso2.carbon.apimgt.api.model.API) APIConsumer(org.wso2.carbon.apimgt.api.APIConsumer)

Example 84 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-apimgt by wso2.

the class AuthenticatorServiceTestCase method testGetTokens.

@Test
public void testGetTokens() throws Exception {
    // Happy Path - 200 - Authorization code grant type
    APIMConfigurationService apimConfigurationService = Mockito.mock(APIMConfigurationService.class);
    EnvironmentConfigurations environmentConfigurations = new EnvironmentConfigurations();
    Mockito.when(apimConfigurationService.getEnvironmentConfigurations()).thenReturn(environmentConfigurations);
    APIMAppConfigurationService apimAppConfigurationService = Mockito.mock(APIMAppConfigurationService.class);
    APIMAppConfigurations apimAppConfigurations = new APIMAppConfigurations();
    Mockito.when(apimAppConfigurationService.getApimAppConfigurations()).thenReturn(apimAppConfigurations);
    // // Mocked response from DCR endpoint
    OAuthApplicationInfo oAuthApplicationInfo = new OAuthApplicationInfo();
    oAuthApplicationInfo.setClientId("xxx-client-id-xxx");
    oAuthApplicationInfo.setClientSecret("xxx-client-secret-xxx");
    // // Expected response object from KeyManager
    AccessTokenInfo tokenInfo = new AccessTokenInfo();
    tokenInfo.setAccessToken("xxx-access-token-xxx");
    tokenInfo.setScopes("apim:subscribe openid");
    tokenInfo.setRefreshToken("xxx-refresh-token-xxx");
    tokenInfo.setIdToken("xxx-id-token-xxx");
    tokenInfo.setValidityPeriod(-2L);
    KeyManager keyManager = Mockito.mock(KeyManager.class);
    SystemApplicationDao systemApplicationDao = Mockito.mock(SystemApplicationDao.class);
    Mockito.when(systemApplicationDao.isConsumerKeyExistForApplication("store")).thenReturn(false);
    MultiEnvironmentOverview multiEnvironmentOverview = new MultiEnvironmentOverview();
    environmentConfigurations.setMultiEnvironmentOverview(multiEnvironmentOverview);
    AuthenticatorService authenticatorService = new AuthenticatorService(keyManager, systemApplicationDao, apimConfigurationService, apimAppConfigurationService);
    Mockito.when(keyManager.createApplication(Mockito.any())).thenReturn(oAuthApplicationInfo);
    // // Actual response - When authorization code is not null
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForValidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, "xxx-auth-code-xxx", null, null);
    Assert.assertEquals(tokenInfoResponseForValidAuthCode, tokenInfo);
    // Error Path - 500 - Authorization code grant type
    // // When an error occurred - Eg: Access denied
    AccessTokenInfo emptyTokenInfo = new AccessTokenInfo();
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(emptyTokenInfo);
    AccessTokenInfo tokenInfoResponseForInvalidAuthCode = new AccessTokenInfo();
    try {
        tokenInfoResponseForInvalidAuthCode = authenticatorService.getTokens("store", "authorization_code", null, null, null, 0, null, null, null);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "No Authorization Code available.");
        Assert.assertEquals(tokenInfoResponseForInvalidAuthCode, emptyTokenInfo);
    }
    // Happy Path - 200 - Password grant type
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForPasswordGrant = authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
    Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
    // Error Path - When token generation fails and throws APIManagementException
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenThrow(KeyManagementException.class).thenReturn(tokenInfo);
    try {
        authenticatorService.getTokens("store", "password", "admin", "admin", null, 0, null, null, null);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error while receiving tokens for OAuth application : store");
    }
    // Happy Path - 200 - Refresh grant type
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForRefreshGrant = authenticatorService.getTokens("store", "refresh_token", null, null, null, 0, null, null, null);
    Assert.assertEquals(tokenInfoResponseForPasswordGrant, tokenInfo);
    // Happy Path - 200 - JWT grant type
    // Multi-Environment Overview configuration
    multiEnvironmentOverview.setEnabled(true);
    IdentityProvider identityProvider = Mockito.mock(IdentityProvider.class);
    String userFromIdentityProvider = "admin-user";
    Mockito.when(identityProvider.getIdOfUser(Mockito.anyString())).thenThrow(IdentityProviderException.class);
    Mockito.doReturn("xxx-admin-user-id-xxx").when(identityProvider).getIdOfUser(userFromIdentityProvider);
    // A valid jwt with user "admin-user"
    String idTokenWith_adminUser = "xxx+header+xxx.eyJzdWIiOiJhZG1pbi11c2VyIn0.xxx+signature+xxx";
    tokenInfo.setIdToken(idTokenWith_adminUser);
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    AccessTokenInfo tokenInfoResponseForValidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
    Assert.assertEquals(tokenInfoResponseForValidJWTGrant, tokenInfo);
    // Error Path - When invalid user in JWT Token
    // A valid jwt with user "John"
    String idTokenWith_johnUser = "xxx+header+xxx.eyJzdWIiOiJKb2huIn0.xxx+signature+xxx";
    tokenInfo.setIdToken(idTokenWith_johnUser);
    Mockito.when(keyManager.getNewAccessToken(Mockito.any())).thenReturn(tokenInfo);
    try {
        AccessTokenInfo tokenInfoResponseForInvalidJWTGrant = authenticatorService.getTokens("store", "urn:ietf:params:oauth:grant-type:jwt-bearer", null, null, null, 0, null, "xxx-assertion-xxx", identityProvider);
        Assert.assertEquals(tokenInfoResponseForInvalidJWTGrant, tokenInfo);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "User John does not exists in this environment.");
    }
}
Also used : IdentityProvider(org.wso2.carbon.apimgt.core.api.IdentityProvider) APIMAppConfigurationService(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.APIMAppConfigurationService) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) AccessTokenInfo(org.wso2.carbon.apimgt.core.models.AccessTokenInfo) EnvironmentConfigurations(org.wso2.carbon.apimgt.core.configuration.models.EnvironmentConfigurations) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) OAuthApplicationInfo(org.wso2.carbon.apimgt.core.models.OAuthApplicationInfo) APIMAppConfigurations(org.wso2.carbon.apimgt.rest.api.authenticator.configuration.models.APIMAppConfigurations) SystemApplicationDao(org.wso2.carbon.apimgt.core.dao.SystemApplicationDao) MultiEnvironmentOverview(org.wso2.carbon.apimgt.core.configuration.models.MultiEnvironmentOverview) KeyManager(org.wso2.carbon.apimgt.core.api.KeyManager) APIMConfigurationService(org.wso2.carbon.apimgt.core.configuration.APIMConfigurationService) Test(org.junit.Test)

Example 85 with Environment

use of org.wso2.carbon.apimgt.impl.gatewayartifactsynchronizer.environmentspecificproperty.Environment in project carbon-business-process by wso2.

the class BPELBindingContextImpl method publishAxisService.

private BPELProcessProxy publishAxisService(ProcessConf processConfiguration, QName serviceName, String portName) throws AxisFault {
    // TODO: Need to fix this to suite multi-tenant environment
    // TODO: There is a problem in this, in this manner we can't have two axis services with
    // same QName
    BPELProcessProxy processProxy = new BPELProcessProxy(processConfiguration, bpelServer, serviceName, portName);
    ConfigurationContext tenantConfigCtx = getConfigurationContextFromProcessConfiguration(processConfiguration);
    AxisService axisService;
    try {
        axisService = AxisServiceUtils.createAxisService(tenantConfigCtx.getAxisConfiguration(), processProxy);
        EndpointConfiguration endpointConfig = ((ProcessConfigurationImpl) processConfiguration).getEndpointConfiguration(new WSDL11Endpoint(serviceName, portName));
        ServiceConfigurationUtil.configureService(axisService, endpointConfig, tenantConfigCtx);
    } catch (AxisFault e) {
        log.error("Error occurred creating the axis service " + serviceName.toString());
        throw new DeploymentException("BPEL Package deployment failed.", e);
    }
    processProxy.setAxisService(axisService);
    removeBPELProcessProxyAndAxisService(processConfiguration.getDeployer(), serviceName, portName);
    services.put(processConfiguration.getDeployer(), serviceName, portName, processProxy);
    ArrayList<AxisService> serviceList = new ArrayList<AxisService>();
    serviceList.add(axisService);
    DeploymentEngine.addServiceGroup(createServiceGroupForService(axisService), serviceList, null, null, tenantConfigCtx.getAxisConfiguration());
    // 
    if (log.isDebugEnabled()) {
        log.debug("BPELProcessProxy created for process " + processConfiguration.getProcessId());
        log.debug("AxisService " + serviceName + " created for BPEL process " + processConfiguration.getProcessId());
    }
    return processProxy;
}
Also used : WSDL11Endpoint(org.apache.ode.bpel.epr.WSDL11Endpoint) AxisFault(org.apache.axis2.AxisFault) ConfigurationContext(org.apache.axis2.context.ConfigurationContext) AxisService(org.apache.axis2.description.AxisService) ArrayList(java.util.ArrayList) DeploymentException(org.apache.axis2.deployment.DeploymentException) EndpointConfiguration(org.wso2.carbon.bpel.common.config.EndpointConfiguration) ProcessConfigurationImpl(org.wso2.carbon.bpel.core.ode.integration.store.ProcessConfigurationImpl)

Aggregations

Environment (org.wso2.carbon.apimgt.api.model.Environment)67 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)53 ArrayList (java.util.ArrayList)35 HashMap (java.util.HashMap)25 API (org.wso2.carbon.apimgt.api.model.API)22 IOException (java.io.IOException)19 APIRevisionDeployment (org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)19 Map (java.util.Map)15 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)13 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)12 JsonObject (com.google.gson.JsonObject)10 PreparedStatement (java.sql.PreparedStatement)10 SQLException (java.sql.SQLException)10 HashSet (java.util.HashSet)10 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)10 SolaceAdminApis (org.wso2.carbon.apimgt.solace.SolaceAdminApis)10 Gson (com.google.gson.Gson)9 JSONObject (org.json.simple.JSONObject)9 Test (org.junit.Test)9 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)9