Search in sources :

Example 61 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class ApiMgtDAO method updateApplicationPolicy.

/**
 * Updates Application level policy.
 * <p>policy name and tenant id should be specified in <code>policy</code></p>
 *
 * @param policy updated policy object
 * @throws APIManagementException
 */
public void updateApplicationPolicy(ApplicationPolicy policy) throws APIManagementException {
    Connection connection = null;
    PreparedStatement updateStatement = null;
    boolean hasCustomAttrib = false;
    String updateQuery;
    if (policy.getTenantId() == -1 || StringUtils.isEmpty(policy.getPolicyName())) {
        String errorMsg = "Policy object doesn't contain mandatory parameters. Name: " + policy.getPolicyName() + ", Tenant Id: " + policy.getTenantId();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg);
    }
    try {
        if (policy.getCustomAttributes() != null) {
            hasCustomAttrib = true;
        }
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_SQL;
            if (hasCustomAttrib) {
                updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_WITH_CUSTOM_ATTRIBUTES_SQL;
            }
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_BY_UUID_SQL;
            if (hasCustomAttrib) {
                updateQuery = SQLConstants.UPDATE_APPLICATION_POLICY_WITH_CUSTOM_ATTRIBUTES_BY_UUID_SQL;
            }
        } else {
            String errorMsg = "Policy object doesn't contain mandatory parameters. At least UUID or Name,Tenant Id" + " should be provided. Name: " + policy.getPolicyName() + ", Tenant Id: " + policy.getTenantId() + ", UUID: " + policy.getUUID();
            log.error(errorMsg);
            throw new APIManagementException(errorMsg);
        }
        updateStatement = connection.prepareStatement(updateQuery);
        if (!StringUtils.isEmpty(policy.getDisplayName())) {
            updateStatement.setString(1, policy.getDisplayName());
        } else {
            updateStatement.setString(1, policy.getPolicyName());
        }
        updateStatement.setString(2, policy.getDescription());
        updateStatement.setString(3, policy.getDefaultQuotaPolicy().getType());
        if (PolicyConstants.REQUEST_COUNT_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
            RequestCountLimit limit = (RequestCountLimit) policy.getDefaultQuotaPolicy().getLimit();
            updateStatement.setLong(4, limit.getRequestCount());
            updateStatement.setString(5, null);
        } else if (PolicyConstants.BANDWIDTH_TYPE.equalsIgnoreCase(policy.getDefaultQuotaPolicy().getType())) {
            BandwidthLimit limit = (BandwidthLimit) policy.getDefaultQuotaPolicy().getLimit();
            updateStatement.setLong(4, limit.getDataAmount());
            updateStatement.setString(5, limit.getDataUnit());
        }
        updateStatement.setLong(6, policy.getDefaultQuotaPolicy().getLimit().getUnitTime());
        updateStatement.setString(7, policy.getDefaultQuotaPolicy().getLimit().getTimeUnit());
        if (hasCustomAttrib) {
            updateStatement.setBlob(8, new ByteArrayInputStream(policy.getCustomAttributes()));
            if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
                updateStatement.setString(9, policy.getPolicyName());
                updateStatement.setInt(10, policy.getTenantId());
            } else if (!StringUtils.isBlank(policy.getUUID())) {
                updateStatement.setString(9, policy.getUUID());
            }
        } else {
            if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
                updateStatement.setString(8, policy.getPolicyName());
                updateStatement.setInt(9, policy.getTenantId());
            } else if (!StringUtils.isBlank(policy.getUUID())) {
                updateStatement.setString(8, policy.getUUID());
            }
        }
        updateStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                // Rollback failed. Exception will be thrown later for upper exception
                log.error("Failed to rollback the update Application Policy: " + policy.toString(), ex);
            }
        }
        handleException("Failed to update application policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
    }
}
Also used : RequestCountLimit(org.wso2.carbon.apimgt.api.model.policy.RequestCountLimit) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) BandwidthLimit(org.wso2.carbon.apimgt.api.model.policy.BandwidthLimit)

Example 62 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class ApiMgtDAO method getAllEnvironments.

/**
 * Returns the Environments List for the TenantId.
 *
 * @param tenantDomain The tenant domain.
 * @return List of Environments.
 */
public List<Environment> getAllEnvironments(String tenantDomain) throws APIManagementException {
    List<Environment> envList = new ArrayList<>();
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement prepStmt = connection.prepareStatement(SQLConstants.GET_ENVIRONMENT_BY_ORGANIZATION_SQL)) {
        prepStmt.setString(1, tenantDomain);
        try (ResultSet rs = prepStmt.executeQuery()) {
            while (rs.next()) {
                Integer id = rs.getInt("ID");
                String uuid = rs.getString("UUID");
                String name = rs.getString("NAME");
                String displayName = rs.getString("DISPLAY_NAME");
                String description = rs.getString("DESCRIPTION");
                String provider = rs.getString("PROVIDER");
                Environment env = new Environment();
                env.setId(id);
                env.setUuid(uuid);
                env.setName(name);
                env.setDisplayName(displayName);
                env.setDescription(description);
                env.setProvider(provider);
                env.setVhosts(getVhostGatewayEnvironments(connection, id));
                envList.add(env);
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get Environments in tenant domain: " + tenantDomain, e);
    }
    return envList;
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) Environment(org.wso2.carbon.apimgt.api.model.Environment) PreparedStatement(java.sql.PreparedStatement)

Example 63 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class ApiMgtDAO method getSubscriber.

/**
 * returns a subscriber record for given username,tenant Id
 *
 * @param username   UserName
 * @param tenantId   Tenant Id
 * @param connection
 * @return Subscriber
 * @throws APIManagementException if failed to get subscriber
 */
private Subscriber getSubscriber(String username, int tenantId, Connection connection) throws APIManagementException {
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    Subscriber subscriber = null;
    String sqlQuery;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.GET_SUBSCRIBER_CASE_INSENSITIVE_SQL;
    } else {
        sqlQuery = SQLConstants.GET_SUBSCRIBER_DETAILS_SQL;
    }
    try {
        prepStmt = connection.prepareStatement(sqlQuery);
        prepStmt.setString(1, username);
        prepStmt.setInt(2, tenantId);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            subscriber = new Subscriber(rs.getString("USER_ID"));
            subscriber.setEmail(rs.getString("EMAIL_ADDRESS"));
            subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
            subscriber.setSubscribedDate(rs.getDate("DATE_SUBSCRIBED"));
            subscriber.setTenantId(rs.getInt("TENANT_ID"));
            return subscriber;
        }
    } catch (SQLException e) {
        handleException("Error when reading the application information from" + " the persistence store.", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, null, rs);
    }
    return subscriber;
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 64 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class ApiMgtDAO method getApplicationsWithPagination.

/**
 * Retrieve the applications by user/application name
 *
 * @param user
 * @param owner
 * @param tenantId
 * @param limit
 * @param offset
 * @param sortBy
 * @param sortOrder
 * @param appName
 * @return
 * @throws APIManagementException
 */
public Application[] getApplicationsWithPagination(String user, String owner, int tenantId, int limit, int offset, String sortBy, String sortOrder, String appName) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    String sqlQuery = null;
    List<Application> applicationList = new ArrayList<>();
    sqlQuery = SQLConstantManagerFactory.getSQlString("GET_APPLICATIONS_BY_TENANT_ID");
    Application[] applications = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        String driverName = connection.getMetaData().getDriverName();
        if (driverName.contains("Oracle")) {
            limit = offset + limit;
        }
        sqlQuery = sqlQuery.replace("$1", sortBy);
        sqlQuery = sqlQuery.replace("$2", sortOrder);
        prepStmt = connection.prepareStatement(sqlQuery);
        prepStmt.setInt(1, tenantId);
        prepStmt.setString(2, "%" + owner + "%");
        prepStmt.setString(3, "%" + appName + "%");
        prepStmt.setInt(4, offset);
        prepStmt.setInt(5, limit);
        rs = prepStmt.executeQuery();
        Application application;
        while (rs.next()) {
            String applicationName = rs.getString("NAME");
            String subscriberName = rs.getString("CREATED_BY");
            Subscriber subscriber = new Subscriber(subscriberName);
            application = new Application(applicationName, subscriber);
            application.setName(applicationName);
            application.setId(rs.getInt("APPLICATION_ID"));
            application.setUUID(rs.getString("UUID"));
            application.setGroupId(rs.getString("GROUP_ID"));
            subscriber.setTenantId(rs.getInt("TENANT_ID"));
            subscriber.setId(rs.getInt("SUBSCRIBER_ID"));
            application.setStatus(rs.getString("APPLICATION_STATUS"));
            application.setOwner(subscriberName);
            applicationList.add(application);
        }
        applications = applicationList.toArray(new Application[applicationList.size()]);
    } catch (SQLException e) {
        handleException("Error while obtaining details of the Application for tenant id : " + tenantId, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
    return applications;
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 65 with Tenant

use of org.wso2.carbon.user.api.Tenant in project carbon-apimgt by wso2.

the class ApiMgtDAO method getSubscriptionPolicies.

/**
 * Get all subscription level policeis belongs to specific tenant
 *
 * @param tenantID tenantID filters the polices belongs to specific tenant
 * @return subscriptionPolicy array list
 */
public SubscriptionPolicy[] getSubscriptionPolicies(int tenantID) throws APIManagementException {
    List<SubscriptionPolicy> policies = new ArrayList<SubscriptionPolicy>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES;
    if (forceCaseInsensitiveComparisons) {
        sqlQuery = SQLConstants.GET_SUBSCRIPTION_POLICIES;
    }
    try {
        conn = APIMgtDBUtil.getConnection();
        ps = conn.prepareStatement(sqlQuery);
        ps.setInt(1, 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.setSubscriberCount(rs.getInt(ThrottlePolicyConstants.COLUMN_CONNECTION_COUNT));
            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.setMonetizationPlan(rs.getString(ThrottlePolicyConstants.COLUMN_MONETIZATION_PLAN));
            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 : SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.policy.SubscriptionPolicy) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)180 UserStoreException (org.wso2.carbon.user.api.UserStoreException)88 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)83 ArrayList (java.util.ArrayList)79 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)70 PreparedStatement (java.sql.PreparedStatement)51 SQLException (java.sql.SQLException)50 IOException (java.io.IOException)49 Connection (java.sql.Connection)49 HashMap (java.util.HashMap)44 ResultSet (java.sql.ResultSet)43 JSONObject (org.json.simple.JSONObject)41 Resource (org.wso2.carbon.registry.core.Resource)40 Registry (org.wso2.carbon.registry.core.Registry)38 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)34 API (org.wso2.carbon.apimgt.api.model.API)34 Test (org.junit.Test)33 File (java.io.File)32 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)32 APIMgtResourceNotFoundException (org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException)30