Search in sources :

Example 31 with Add

use of org.wso2.siddhi.query.api.expression.math.Add in project carbon-apimgt by wso2.

the class PolicyDAOImpl method setHeaderConditions.

/**
 * Add Header conditions of pipeline with pipeline Id: <code>pipelineId</code> to a
 * provided {@link Condition} array
 *
 * @param connection Connection of the database
 * @param pipelineId Id of the pipeline
 * @param conditions condition array to populate
 * @throws SQLException
 */
private void setHeaderConditions(int pipelineId, ArrayList<Condition> conditions, Connection connection) throws SQLException {
    final String query = "SELECT " + "HEADER_FIELD_NAME, " + "HEADER_FIELD_VALUE , IS_HEADER_FIELD_MAPPING " + " FROM " + "AM_HEADER_FIELD_CONDITION " + "WHERE " + "CONDITION_GROUP_ID =?";
    try (PreparedStatement preparedStatement = connection.prepareStatement(query)) {
        preparedStatement.setInt(1, pipelineId);
        try (ResultSet resultSet = preparedStatement.executeQuery()) {
            while (resultSet.next()) {
                HeaderCondition headerCondition = new HeaderCondition();
                headerCondition.setHeader(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_HEADER_FIELD_NAME));
                headerCondition.setValue(resultSet.getString(APIMgtConstants.ThrottlePolicyConstants.COLUMN_HEADER_FIELD_VALUE));
                headerCondition.setInvertCondition(resultSet.getBoolean(APIMgtConstants.ThrottlePolicyConstants.COLUMN_IS_HEADER_FIELD_MAPPING));
                conditions.add(headerCondition);
            }
        }
    }
}
Also used : HeaderCondition(org.wso2.carbon.apimgt.core.models.policy.HeaderCondition) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 32 with Add

use of org.wso2.siddhi.query.api.expression.math.Add 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 33 with Add

use of org.wso2.siddhi.query.api.expression.math.Add in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method getScopeOfResourcePath.

@Override
public String getScopeOfResourcePath(String resourceConfigsJSON, Request request, ServiceMethodInfo serviceMethodInfo) throws APIManagementException {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(resourceConfigsJSON);
    String basepath = swagger.getBasePath();
    String verb = (String) request.getProperty(APIMgtConstants.HTTP_METHOD);
    // TODO change to this if msf4j2.3.0-m2 or higher
    // Method resourceMethod = (Method) request.getProperty("method");
    Method resourceMethod = serviceMethodInfo.getMethod();
    if (resourceMethod == null || verb == null) {
        String message = "Could not read required properties from HTTP Request. HTTP_METHOD=" + verb + " resourceTemplate=" + resourceMethod;
        log.error(message);
        throw new APIManagementException(message, ExceptionCodes.SWAGGER_URL_MALFORMED);
    }
    String apiPrefix = resourceMethod.getDeclaringClass().getAnnotation(javax.ws.rs.ApplicationPath.class).value();
    String pathTemplate = "";
    if (resourceMethod.getAnnotation(javax.ws.rs.Path.class) != null) {
        pathTemplate = resourceMethod.getAnnotation(javax.ws.rs.Path.class).value();
    }
    String nameSpace = getNamespaceFromBasePath(basepath);
    if (basepath.contains(APIMgtConstants.APPType.PUBLISHER)) {
        nameSpace = APIMgtConstants.NAMESPACE_PUBLISHER_API;
    } else if (basepath.contains(APIMgtConstants.APPType.STORE)) {
        nameSpace = APIMgtConstants.NAMESPACE_STORE_API;
    } else if (basepath.contains(APIMgtConstants.APPType.ADMIN)) {
        nameSpace = APIMgtConstants.NAMESPACE_ADMIN_API;
    } else if (basepath.contains(APIMgtConstants.APPType.ANALYTICS)) {
        nameSpace = APIMgtConstants.NAMESPACE_ANALYTICS_API;
    }
    // if namespace is not available in local cache add it.
    if (nameSpace != null && !localConfigMap.containsKey(nameSpace)) {
        localConfigMap.put(nameSpace, new ConcurrentHashMap<>());
    }
    if (nameSpace != null && localConfigMap.containsKey(nameSpace) && localConfigMap.get(nameSpace).isEmpty()) {
        populateConfigMapForScopes(swagger, nameSpace);
    }
    String resourceConfig = verb + "_" + apiPrefix + pathTemplate;
    if (localConfigMap.get(nameSpace).containsKey(resourceConfig)) {
        return localConfigMap.get(nameSpace).get(resourceConfig).toString();
    }
    return null;
}
Also used : SwaggerParser(io.swagger.parser.SwaggerParser) Path(io.swagger.models.Path) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Swagger(io.swagger.models.Swagger) Method(java.lang.reflect.Method) HttpMethod(io.swagger.models.HttpMethod)

Example 34 with Add

use of org.wso2.siddhi.query.api.expression.math.Add in project carbon-apimgt by wso2.

the class APIGatewayPublisherImpl method addPolicy.

@Override
public void addPolicy(PolicyValidationData policyValidationData) throws GatewayException {
    if (policyValidationData != null) {
        PolicyEvent policyEvent = new PolicyEvent(APIMgtConstants.GatewayEventTypes.POLICY_CREATE);
        policyEvent.setId(policyValidationData.getId());
        policyEvent.setName(policyValidationData.getName());
        policyEvent.setStopOnQuotaReach(policyValidationData.isStopOnQuotaReach());
        publishToThrottleTopic(policyEvent);
        if (log.isDebugEnabled()) {
            log.debug("Policy : " + policyValidationData.getName() + " add event has been successfully published " + "to broker");
        }
    }
}
Also used : PolicyEvent(org.wso2.carbon.apimgt.core.models.events.PolicyEvent)

Example 35 with Add

use of org.wso2.siddhi.query.api.expression.math.Add in project carbon-apimgt by wso2.

the class APIMgtAdminServiceImpl method addApiPolicy.

@Override
public String addApiPolicy(APIPolicy policy) throws APIManagementException {
    try {
        String policyUuid = policy.getUuid();
        if (policyUuid == null) {
            if (log.isDebugEnabled()) {
                log.debug("Policy id is null, hence generating a new UUID for the policy with name: " + policy.getPolicyName());
            }
            policyUuid = UUID.randomUUID().toString();
            policy.setUuid(policyUuid);
        }
        policyDAO.addApiPolicy(policy);
        PolicyValidationData policyValidationData = new PolicyValidationData(policyUuid, policy.getPolicyName(), false);
        apiGateway.addPolicy(policyValidationData);
        return policyUuid;
    } catch (APIMgtDAOException e) {
        String errorMessage = "Couldn't add API policy for uuid: " + policy.getUuid();
        log.error(errorMessage, e);
        throw new APIManagementException(errorMessage, e, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) PolicyValidationData(org.wso2.carbon.apimgt.core.models.PolicyValidationData)

Aggregations

Test (org.testng.annotations.Test)134 API (org.wso2.carbon.apimgt.core.models.API)63 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)60 ArrayList (java.util.ArrayList)57 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)55 HashMap (java.util.HashMap)51 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)44 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)43 Application (org.wso2.carbon.apimgt.core.models.Application)37 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)35 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)33 Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)30 ApplicationDAO (org.wso2.carbon.apimgt.core.dao.ApplicationDAO)29 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)26 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)26 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)25 APISubscriptionDAO (org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO)23 APIPolicy (org.wso2.carbon.apimgt.core.models.policy.APIPolicy)22 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)22 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)22