Search in sources :

Example 56 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-apimgt by wso2.

the class ApiMgtDAO method getSubscriptionPolicies.

/**
 * Get subscription level policies specified by tier names belonging to a specific tenant
 *
 * @param subscriptionTiers subscription tiers
 * @param tenantID          tenantID filters the polices belongs to specific tenant
 * @return subscriptionPolicy array list
 */
public SubscriptionPolicy[] getSubscriptionPolicies(String[] subscriptionTiers, int tenantID) throws APIManagementException {
    List<SubscriptionPolicy> policies = new ArrayList<SubscriptionPolicy>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    List<String> questionMarks = new ArrayList<>(Collections.nCopies(subscriptionTiers.length, "?"));
    String parameterString = String.join(",", questionMarks);
    String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES_BY_POLICY_NAMES_PREFIX + parameterString + SQLConstants.GET_SUBSCRIPTION_POLICIES_BY_POLICY_NAMES_SUFFIX;
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        int i = 1;
        for (String subscriptionTier : subscriptionTiers) {
            ps.setString(i, subscriptionTier);
            i++;
        }
        ps.setInt(i, tenantID);
        rs = ps.executeQuery();
        while (rs.next()) {
            SubscriptionPolicy subPolicy = new SubscriptionPolicy(rs.getString(ThrottlePolicyConstants.COLUMN_NAME));
            setCommonPolicyDetails(subPolicy, rs);
            subPolicy.setRateLimitCount(rs.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
            subPolicy.setRateLimitTimeUnit(rs.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
            subPolicy.setStopOnQuotaReach(rs.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
            subPolicy.setBillingPlan(rs.getString(ThrottlePolicyConstants.COLUMN_BILLING_PLAN));
            subPolicy.setGraphQLMaxDepth(rs.getInt(ThrottlePolicyConstants.COLUMN_MAX_DEPTH));
            subPolicy.setGraphQLMaxComplexity(rs.getInt(ThrottlePolicyConstants.COLUMN_MAX_COMPLEXITY));
            subPolicy.setSubscriberCount(rs.getInt(ThrottlePolicyConstants.COLUMN_CONNECTION_COUNT));
            subPolicy.setMonetizationPlan(rs.getString(ThrottlePolicyConstants.COLUMN_MONETIZATION_PLAN));
            subPolicy.setTierQuotaType(rs.getString(ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE));
            Map<String, String> monetizationPlanProperties = subPolicy.getMonetizationPlanProperties();
            monetizationPlanProperties.put(APIConstants.Monetization.FIXED_PRICE, rs.getString(ThrottlePolicyConstants.COLUMN_FIXED_RATE));
            monetizationPlanProperties.put(APIConstants.Monetization.BILLING_CYCLE, rs.getString(ThrottlePolicyConstants.COLUMN_BILLING_CYCLE));
            monetizationPlanProperties.put(APIConstants.Monetization.PRICE_PER_REQUEST, rs.getString(ThrottlePolicyConstants.COLUMN_PRICE_PER_REQUEST));
            monetizationPlanProperties.put(APIConstants.Monetization.CURRENCY, rs.getString(ThrottlePolicyConstants.COLUMN_CURRENCY));
            subPolicy.setMonetizationPlanProperties(monetizationPlanProperties);
            InputStream binary = rs.getBinaryStream(ThrottlePolicyConstants.COLUMN_CUSTOM_ATTRIB);
            if (binary != null) {
                byte[] customAttrib = APIUtil.toByteArray(binary);
                subPolicy.setCustomAttributes(customAttrib);
            }
            policies.add(subPolicy);
        }
    } catch (SQLException e) {
        handleException("Error while executing SQL", e);
    } catch (IOException e) {
        handleException("Error while converting input stream to byte array", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, conn, rs);
    }
    return policies.toArray(new SubscriptionPolicy[policies.size()]);
}
Also used : SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException) SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) ResultSet(java.sql.ResultSet)

Example 57 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-apimgt by wso2.

the class APIUtil method getDomainMappings.

/**
 * Returns a map of gateway / store domains for the tenant
 *
 * @return a Map of domain names for tenant
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if an error occurs when loading tiers from the registry
 */
public static Map<String, String> getDomainMappings(String tenantDomain, String appType) throws APIManagementException {
    Map<String, String> domains = new HashMap<String, String>();
    String resourcePath;
    try {
        Registry registry = ServiceReferenceHolder.getInstance().getRegistryService().getGovernanceSystemRegistry();
        resourcePath = APIConstants.API_DOMAIN_MAPPINGS.replace(APIConstants.API_DOMAIN_MAPPING_TENANT_ID_IDENTIFIER, tenantDomain);
        if (registry.resourceExists(resourcePath)) {
            Resource resource = registry.get(resourcePath);
            String content = new String((byte[]) resource.getContent(), Charset.defaultCharset());
            JSONParser parser = new JSONParser();
            JSONObject mappings = (JSONObject) parser.parse(content);
            if (mappings.get(appType) != null) {
                mappings = (JSONObject) mappings.get(appType);
                for (Object o : mappings.entrySet()) {
                    Entry thisEntry = (Entry) o;
                    String key = (String) thisEntry.getKey();
                    // to allow users to add multiple URLs if needed
                    if (!StringUtils.isEmpty(key) && key.startsWith(APIConstants.CUSTOM_URL)) {
                        String value = (String) thisEntry.getValue();
                        domains.put(key, value);
                    }
                }
            }
        }
    } catch (RegistryException e) {
        String msg = "Error while retrieving gateway domain mappings from registry";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    } catch (ClassCastException e) {
        String msg = "Invalid JSON found in the gateway tenant domain mappings";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    } catch (ParseException e) {
        String msg = "Malformed JSON found in the gateway tenant domain mappings";
        log.error(msg, e);
        throw new APIManagementException(msg, e);
    }
    return domains;
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) Resource(org.wso2.carbon.registry.core.Resource) APIProductResource(org.wso2.carbon.apimgt.api.model.APIProductResource) APIResource(org.wso2.carbon.apimgt.api.doc.model.APIResource) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) Entry(java.util.Map.Entry) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) JsonObject(com.google.gson.JsonObject) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Example 58 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-apimgt by wso2.

the class APIConsumerImpl method getHostWithSchemeMappingForEnvironment.

/**
 * Get host names with transport scheme mapping from Gateway Environments in api-manager.xml or from the tenant
 * custom url config in registry.
 *
 * @param apiTenantDomain Tenant domain
 * @param environmentName Environment name
 * @return Host name to transport scheme mapping
 * @throws APIManagementException if an error occurs when getting host names with schemes
 */
private Map<String, String> getHostWithSchemeMappingForEnvironment(API api, String apiTenantDomain, String environmentName) throws APIManagementException {
    Map<String, String> domains = getTenantDomainMappings(apiTenantDomain, APIConstants.API_DOMAIN_MAPPINGS_GATEWAY);
    Map<String, String> hostsWithSchemes = new HashMap<>();
    String organization = api.getOrganization();
    if (!domains.isEmpty()) {
        String customUrl = domains.get(APIConstants.CUSTOM_URL);
        if (customUrl.startsWith(APIConstants.HTTP_PROTOCOL_URL_PREFIX)) {
            hostsWithSchemes.put(APIConstants.HTTP_PROTOCOL, customUrl);
        } else {
            hostsWithSchemes.put(APIConstants.HTTPS_PROTOCOL, customUrl);
        }
    } else {
        Map<String, Environment> allEnvironments = APIUtil.getEnvironments(organization);
        Environment environment = allEnvironments.get(environmentName);
        if (environment == null) {
            handleResourceNotFoundException("Could not find provided environment '" + environmentName + "'");
        }
        List<APIRevisionDeployment> deploymentList = getAPIRevisionDeploymentListOfAPI(api.getUuid());
        String host = "";
        for (APIRevisionDeployment deployment : deploymentList) {
            if (!deployment.isDisplayOnDevportal()) {
                continue;
            }
            if (StringUtils.equals(deployment.getDeployment(), environmentName)) {
                host = deployment.getVhost();
            }
        }
        if (StringUtils.isEmpty(host)) {
            // returns empty server urls
            hostsWithSchemes.put(APIConstants.HTTP_PROTOCOL, "");
            return hostsWithSchemes;
        }
        VHost vhost = VHostUtils.getVhostFromEnvironment(environment, host);
        if (StringUtils.containsIgnoreCase(api.getTransports(), APIConstants.HTTP_PROTOCOL)) {
            hostsWithSchemes.put(APIConstants.HTTP_PROTOCOL, vhost.getHttpUrl());
        }
        if (StringUtils.containsIgnoreCase(api.getTransports(), APIConstants.HTTPS_PROTOCOL)) {
            hostsWithSchemes.put(APIConstants.HTTPS_PROTOCOL, vhost.getHttpsUrl());
        }
    }
    return hostsWithSchemes;
}
Also used : VHost(org.wso2.carbon.apimgt.api.model.VHost) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Environment(org.wso2.carbon.apimgt.api.model.Environment) RecommendationEnvironment(org.wso2.carbon.apimgt.impl.recommendationmgt.RecommendationEnvironment) APIRevisionDeployment(org.wso2.carbon.apimgt.api.model.APIRevisionDeployment)

Example 59 with Names

use of org.wso2.ballerinalang.compiler.util.Names in project carbon-apimgt by wso2.

the class PolicyUtil method undeployPolicies.

/**
 * Undeploy the throttle policies passed as a list from the Traffic Manager.
 *
 * @param policyFileNames list of policy file names
 */
private static void undeployPolicies(List<String> policyFileNames) {
    try {
        PrivilegedCarbonContext.startTenantFlow();
        PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(APIConstants.SUPER_TENANT_DOMAIN, true);
        EventProcessorService eventProcessorService = ServiceReferenceHolder.getInstance().getEventProcessorService();
        for (String policyFileName : policyFileNames) {
            String executionPlan = null;
            try {
                executionPlan = eventProcessorService.getActiveExecutionPlan(policyFileName);
            } catch (ExecutionPlanConfigurationException e) {
            // Do nothing when execution plan not found
            }
            if (executionPlan != null) {
                eventProcessorService.undeployActiveExecutionPlan(policyFileName);
            }
        }
    } catch (ExecutionPlanConfigurationException e) {
        log.error("Error in removing execution plan", e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}
Also used : ExecutionPlanConfigurationException(org.wso2.carbon.event.processor.core.exception.ExecutionPlanConfigurationException) EventProcessorService(org.wso2.carbon.event.processor.core.EventProcessorService)

Aggregations

ArrayList (java.util.ArrayList)14 Query (javax.persistence.Query)8 TaskStatus (org.wso2.carbon.humantask.core.dao.TaskStatus)8 HashMap (java.util.HashMap)7 Test (org.testng.annotations.Test)6 Name (org.wso2.ballerinalang.compiler.util.Name)5 IOException (java.io.IOException)4 Map (java.util.Map)4 BLangVariable (org.wso2.ballerinalang.compiler.tree.BLangVariable)4 BLangXMLQName (org.wso2.ballerinalang.compiler.tree.expressions.BLangXMLQName)4 CompilerContext (org.wso2.ballerinalang.compiler.util.CompilerContext)4 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)4 Iterator (java.util.Iterator)3 OMElement (org.apache.axiom.om.OMElement)3 HTTPTestRequest (org.ballerinalang.test.services.testutils.HTTPTestRequest)3 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)3 BLangRecordLiteral (org.wso2.ballerinalang.compiler.tree.expressions.BLangRecordLiteral)3 BLangAssignment (org.wso2.ballerinalang.compiler.tree.statements.BLangAssignment)3 Tier (org.wso2.carbon.apimgt.api.model.Tier)3 JsonObject (com.google.gson.JsonObject)2