Search in sources :

Example 1 with APITemplateException

use of org.wso2.carbon.apimgt.core.template.APITemplateException in project carbon-apimgt by wso2.

the class APIPublisherImpl method addAPI.

/**
 * Adds a new API to the system
 *
 * @param apiBuilder API model object
 * @return UUID of the added API.
 * @throws APIManagementException if failed to add API
 */
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    API createdAPI;
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    if (StringUtils.isEmpty(apiBuilder.getId())) {
        apiBuilder.id(UUID.randomUUID().toString());
    }
    LocalDateTime localDateTime = LocalDateTime.now();
    apiBuilder.createdTime(localDateTime);
    apiBuilder.lastUpdatedTime(localDateTime);
    apiBuilder.createdBy(getUsername());
    apiBuilder.updatedBy(getUsername());
    if (apiBuilder.getLabels().isEmpty()) {
        List<String> labelSet = new ArrayList<>();
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
        apiBuilder.labels(labelSet);
    }
    Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
    validateEndpoints(apiEndpointMap, false);
    try {
        if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
            LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
            apiBuilder.associateLifecycle(lifecycleState);
            createUriTemplateList(apiBuilder, false);
            List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
            List<TemplateBuilderDTO> resourceList = new ArrayList<>();
            validateApiPolicy(apiBuilder.getApiPolicy());
            validateSubscriptionPolicies(apiBuilder);
            for (UriTemplate uriTemplate : list) {
                TemplateBuilderDTO dto = new TemplateBuilderDTO();
                dto.setTemplateId(uriTemplate.getTemplateId());
                dto.setUriTemplate(uriTemplate.getUriTemplate());
                dto.setHttpVerb(uriTemplate.getHttpVerb());
                Map<String, Endpoint> map = uriTemplate.getEndpoint();
                if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
                    dto.setProductionEndpoint(endpoint);
                }
                if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
                    dto.setSandboxEndpoint(endpoint);
                }
                resourceList.add(dto);
            }
            GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
            APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
            gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
            String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
            if (log.isDebugEnabled()) {
                log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
            }
            apiBuilder.gatewayConfig(gatewayConfig);
            if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
                apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
            }
            if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                Map<String, Integer> roleNamePermissionList;
                roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                apiBuilder.permissionMap(roleNamePermissionList);
            }
            createdAPI = apiBuilder.build();
            APIUtils.validate(createdAPI);
            // Add API to gateway
            gateway.addAPI(createdAPI);
            if (log.isDebugEnabled()) {
                log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
            }
            Set<String> apiRoleList;
            // if the API has role based visibility, add the API with role checking
            if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
                getApiDAO().addAPI(createdAPI);
            } else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
                // get all the roles in the system
                Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                // get the roles needed to be associated with the API
                apiRoleList = createdAPI.getVisibleRoles();
                if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                    getApiDAO().addAPI(createdAPI);
                }
            }
            APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created " + "successfully.", log);
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException | ParseException e) {
        String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (APITemplateException e) {
        String message = "Error generating API configuration for API " + apiBuilder.getName();
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
    return apiBuilder.getId();
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) TemplateBuilderDTO(org.wso2.carbon.apimgt.core.template.dto.TemplateBuilderDTO) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 2 with APITemplateException

use of org.wso2.carbon.apimgt.core.template.APITemplateException in project carbon-apimgt by wso2.

the class APIPublisherImpl method updateApiGatewayConfig.

/**
 * {@inheritDoc}
 */
@Override
public void updateApiGatewayConfig(String apiId, String configString) throws APIManagementException {
    API api = getAPIbyUUID(apiId);
    GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
    APIConfigContext apiConfigContext = new APIConfigContext(api, config.getGatewayPackageName());
    gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
    try {
        String swagger = gatewaySourceGenerator.getSwaggerFromGatewayConfig(configString);
        getApiDAO().updateApiDefinition(apiId, swagger, getUsername());
        getApiDAO().updateGatewayConfig(apiId, configString, getUsername());
    } catch (APIMgtDAOException e) {
        log.error("Couldn't update configuration for apiId " + apiId, e);
        throw new APIManagementException("Couldn't update configuration for apiId " + apiId, e.getErrorHandler());
    } catch (APITemplateException e) {
        log.error("Error generating swagger from gateway config " + apiId, e);
        throw new APIManagementException("Error generating swagger from gateway config " + apiId, ExceptionCodes.TEMPLATE_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 3 with APITemplateException

use of org.wso2.carbon.apimgt.core.template.APITemplateException in project carbon-apimgt by wso2.

the class APIThrottlePolicyTemplateBuilder method getThrottlePolicyTemplateForPipelines.

/**
 * Generate policy for api level throttling
 *
 * @return throttle policies for api level
 * @throws APITemplateException throws if generation failure occur
 */
public Map<String, String> getThrottlePolicyTemplateForPipelines() throws APITemplateException {
    if (log.isDebugEnabled()) {
        log.debug("Generating Siddhi App for apiLevel :" + apiPolicy.toString());
    }
    // get velocity template for API policy pipeline and generate the template
    Map<String, String> policyArray = new HashMap<String, String>();
    StringWriter writer;
    VelocityContext context;
    VelocityEngine velocityengine = initVelocityEngine();
    Template template = velocityengine.getTemplate(getTemplatePathForAPI());
    // Generate template for pipeline conditions if pipelines not null
    if (apiPolicy.getPipelines() != null) {
        for (Pipeline pipeline : apiPolicy.getPipelines()) {
            // set values for velocity context
            context = new VelocityContext();
            setConstantContext(context);
            context.put(PIPELINE_ITEM, pipeline);
            context.put(POLICY, apiPolicy);
            context.put(QUOTA_POLICY, pipeline.getQuotaPolicy());
            context.put(PIPELINE, CONDITION + UNDERSCORE + pipeline.getId());
            String conditionString = getPolicyCondition(pipeline.getConditions());
            context.put(CONDITION, AND + conditionString);
            writer = new StringWriter();
            template.merge(context, writer);
            if (log.isDebugEnabled()) {
                log.debug("Generated Siddhi App : " + writer.toString());
            }
            String policyName = PolicyConstants.POLICY_LEVEL_RESOURCE + UNDERSCORE + apiPolicy.getPolicyName() + UNDERSCORE + CONDITION + UNDERSCORE + pipeline.getId();
            policyArray.put(policyName, writer.toString());
        }
    }
    return policyArray;
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) StringWriter(java.io.StringWriter) HashMap(java.util.HashMap) VelocityContext(org.apache.velocity.VelocityContext) Template(org.apache.velocity.Template) Pipeline(org.wso2.carbon.apimgt.core.models.policy.Pipeline)

Example 4 with APITemplateException

use of org.wso2.carbon.apimgt.core.template.APITemplateException in project carbon-apimgt by wso2.

the class APIPublisherImplTestCase method testAddApi.

@Test(description = "Test add api with production endpoint")
public void testAddApi() throws APIManagementException, LifecycleException {
    /**
     * this test method verify the API Add with correct API object get invoked correctly
     */
    API.APIBuilder apiBuilder = SampleTestObjectCreator.createDefaultAPI().id("").endpoint(SampleTestObjectCreator.getMockEndpointMap());
    ApiDAO apiDAO = Mockito.mock(ApiDAO.class);
    LabelDAO labelDao = Mockito.mock(LabelDAO.class);
    GatewaySourceGenerator gatewaySourceGenerator = Mockito.mock(GatewaySourceGenerator.class);
    APILifecycleManager apiLifecycleManager = Mockito.mock(APILifecycleManager.class);
    Mockito.when(apiLifecycleManager.addLifecycle(APIMgtConstants.API_LIFECYCLE, USER)).thenReturn(new LifecycleState());
    APIGateway gateway = Mockito.mock(APIGateway.class);
    PolicyDAO policyDAO = Mockito.mock(PolicyDAO.class);
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.api, APIMgtConstants.DEFAULT_API_POLICY)).thenReturn(new APIPolicy(APIMgtConstants.DEFAULT_API_POLICY));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, GOLD_TIER)).thenReturn(new SubscriptionPolicy(GOLD_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, SILVER_TIER)).thenReturn(new SubscriptionPolicy(SILVER_TIER));
    Mockito.when(policyDAO.getSimplifiedPolicyByLevelAndName(APIMgtAdminService.PolicyLevel.subscription, BRONZE_TIER)).thenReturn(new SubscriptionPolicy(BRONZE_TIER));
    APIPublisherImpl apiPublisher = getApiPublisherImpl(null, apiDAO, null, null, policyDAO, apiLifecycleManager, labelDao, null, null, null, gatewaySourceGenerator, gateway);
    String endpointId = apiBuilder.getEndpoint().get("production").getId();
    Endpoint endpoint = new Endpoint.Builder().id(endpointId).name("testEndpoint").build();
    Mockito.when(apiDAO.getEndpoint(endpointId)).thenReturn(endpoint);
    apiPublisher.addAPI(apiBuilder);
    Mockito.verify(apiDAO, Mockito.times(1)).addAPI(apiBuilder.build());
    Mockito.verify(apiLifecycleManager, Mockito.times(1)).addLifecycle(APIMgtConstants.API_LIFECYCLE, USER);
    // Error path
    // When an APIMgtDAOException is being thrown when the API is created
    Mockito.doThrow(APIMgtDAOException.class).when(apiDAO).addAPI(apiBuilder.build());
    try {
        apiPublisher.addAPI(apiBuilder);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while creating the API - " + apiBuilder.getName());
    }
    // Error path
    // When an GatewayException is being thrown when an error occurred while adding API to the Gateway
    Mockito.doThrow(GatewayException.class).when(gateway).addAPI(apiBuilder.build());
    try {
        apiPublisher.addAPI(apiBuilder);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error occurred while adding API - " + apiBuilder.getName() + " to gateway");
    }
    // Error path
    // When an APITemplateException is being thrown when generating API configuration for API
    Mockito.when(gatewaySourceGenerator.getConfigStringFromTemplate(Mockito.any())).thenThrow(APITemplateException.class);
    try {
        apiPublisher.addAPI(apiBuilder);
    } catch (APIManagementException e) {
        Assert.assertEquals(e.getMessage(), "Error generating API configuration for API " + apiBuilder.getName());
    }
}
Also used : APIBuilder(org.wso2.carbon.apimgt.core.models.API.APIBuilder) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) LabelDAO(org.wso2.carbon.apimgt.core.dao.LabelDAO) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) APILifecycleManager(org.wso2.carbon.apimgt.core.api.APILifecycleManager) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) SubscriptionPolicy(org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) APIPolicy(org.wso2.carbon.apimgt.core.models.policy.APIPolicy) ApiDAO(org.wso2.carbon.apimgt.core.dao.ApiDAO) PolicyDAO(org.wso2.carbon.apimgt.core.dao.PolicyDAO) Test(org.testng.annotations.Test)

Example 5 with APITemplateException

use of org.wso2.carbon.apimgt.core.template.APITemplateException in project carbon-apimgt by wso2.

the class GatewaySourceGeneratorImpl method getConfigStringFromTemplate.

@Override
public String getConfigStringFromTemplate(List<TemplateBuilderDTO> apiResources) throws APITemplateException {
    StringWriter writer = new StringWriter();
    String templatePath = "resources" + File.separator + "template" + File.separator + "template.xml";
    try {
        // build the context for template and apply the necessary decorators
        apiConfigContext.validate();
        ConfigContext configContext = new ResourceConfigContext(apiConfigContext, apiResources);
        VelocityContext context = configContext.getContext();
        VelocityEngine velocityengine = new VelocityEngine();
        velocityengine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        velocityengine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        velocityengine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute());
        velocityengine.init();
        Template template = velocityengine.getTemplate(templatePath);
        template.merge(context, writer);
    } catch (ResourceNotFoundException e) {
        log.error("Template " + templatePath + " not Found", e);
        throw new APITemplateException("Template " + templatePath + " not Found", ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (ParseErrorException e) {
        log.error("Syntax error in " + templatePath, e);
        throw new APITemplateException("Syntax error in " + templatePath, ExceptionCodes.TEMPLATE_EXCEPTION);
    }
    return writer.toString();
}
Also used : VelocityEngine(org.apache.velocity.app.VelocityEngine) CommonsLogLogChute(org.apache.velocity.runtime.log.CommonsLogLogChute) StringWriter(java.io.StringWriter) VelocityContext(org.apache.velocity.VelocityContext) ResourceConfigContext(org.wso2.carbon.apimgt.core.template.ResourceConfigContext) ParseErrorException(org.apache.velocity.exception.ParseErrorException) ClasspathResourceLoader(org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) ResourceNotFoundException(org.apache.velocity.exception.ResourceNotFoundException) CompositeAPIConfigContext(org.wso2.carbon.apimgt.core.template.CompositeAPIConfigContext) ConfigContext(org.wso2.carbon.apimgt.core.template.ConfigContext) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext) ResourceConfigContext(org.wso2.carbon.apimgt.core.template.ResourceConfigContext) Template(org.apache.velocity.Template)

Aggregations

Test (org.testng.annotations.Test)9 HashMap (java.util.HashMap)6 API (org.wso2.carbon.apimgt.core.models.API)6 StringWriter (java.io.StringWriter)5 Template (org.apache.velocity.Template)5 VelocityContext (org.apache.velocity.VelocityContext)5 VelocityEngine (org.apache.velocity.app.VelocityEngine)5 APITemplateException (org.wso2.carbon.apimgt.core.template.APITemplateException)5 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)4 APIConfigContext (org.wso2.carbon.apimgt.core.template.APIConfigContext)4 ParseErrorException (org.apache.velocity.exception.ParseErrorException)3 ResourceNotFoundException (org.apache.velocity.exception.ResourceNotFoundException)3 ClasspathResourceLoader (org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader)3 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)3 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)3 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)3 CompositeAPIConfigContext (org.wso2.carbon.apimgt.core.template.CompositeAPIConfigContext)3 ArrayList (java.util.ArrayList)2 HashSet (java.util.HashSet)2 CommonsLogLogChute (org.apache.velocity.runtime.log.CommonsLogLogChute)2