Search in sources :

Example 96 with Tenant

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

the class ServiceCatalogDAO method addServices.

/**
 * Add list of services to Service Catalog
 * @param services List of Services that needs to be added
 * @param tenantId Tenant ID of the logged-in user
 * @param username Logged-in username
 * @param connection DB Connection
 */
private void addServices(List<ServiceEntry> services, int tenantId, String username, Connection connection) throws SQLException {
    try (PreparedStatement preparedStatement = connection.prepareStatement(SQLConstants.ServiceCatalogConstants.ADD_SERVICE)) {
        for (ServiceEntry service : services) {
            setServiceParams(preparedStatement, service, tenantId, username);
            preparedStatement.addBatch();
        }
        preparedStatement.executeBatch();
    }
}
Also used : PreparedStatement(java.sql.PreparedStatement) ServiceEntry(org.wso2.carbon.apimgt.api.model.ServiceEntry)

Example 97 with Tenant

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

the class ApiMgtDAO method isApplicationGroupCombinationExists.

/**
 * @param applicationName application name
 * @param username username
 * @param groupId group id
 * @return whether a certain application group combination exists or not
 * @throws APIManagementException if failed to assess whether a certain application group combination exists or not
 */
public boolean isApplicationGroupCombinationExists(String applicationName, String username, String groupId) throws APIManagementException {
    if (username == null) {
        return false;
    }
    Subscriber subscriber = getSubscriber(username);
    int appId = 0;
    String sqlQuery = SQLConstants.GET_APPLICATION_ID_PREFIX_FOR_GROUP_COMPARISON;
    String whereClauseWithGroupId = " AND APP.GROUP_ID = ?";
    String whereClauseWithMultiGroupId = " AND (APP.APPLICATION_ID IN (SELECT APPLICATION_ID  FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?))";
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        if (!StringUtils.isEmpty(groupId)) {
            if (multiGroupAppSharingEnabled) {
                sqlQuery += whereClauseWithMultiGroupId;
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] grpIdArray = groupId.split(",");
                int noOfParams = grpIdArray.length;
                try (PreparedStatement preparedStatement = fillQueryParams(connection, sqlQuery, grpIdArray, 2)) {
                    preparedStatement.setString(1, applicationName);
                    int paramIndex = noOfParams + 1;
                    preparedStatement.setString(++paramIndex, tenantDomain);
                    try (ResultSet resultSet = preparedStatement.executeQuery()) {
                        if (resultSet.next()) {
                            appId = resultSet.getInt("APPLICATION_ID");
                        }
                        if (appId > 0) {
                            return true;
                        }
                    }
                }
            } else {
                sqlQuery += whereClauseWithGroupId;
                try (PreparedStatement preparedStatement = connection.prepareStatement(sqlQuery)) {
                    preparedStatement.setString(1, applicationName);
                    preparedStatement.setString(2, groupId);
                    try (ResultSet resultSet = preparedStatement.executeQuery()) {
                        if (resultSet.next()) {
                            appId = resultSet.getInt("APPLICATION_ID");
                        }
                        if (appId > 0) {
                            return true;
                        }
                    }
                }
            }
        }
    } catch (SQLException e) {
        handleException("Error while getting application group combination data for application: " + applicationName, e);
    }
    return false;
}
Also used : Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 98 with Tenant

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

the class ApiMgtDAO method updateGlobalPolicy.

/**
 * Updates global throttle policy in database
 *
 * @param policy updated policy obejct
 * @throws APIManagementException
 */
public void updateGlobalPolicy(GlobalPolicy policy) throws APIManagementException {
    Connection connection = null;
    PreparedStatement updateStatement = null;
    InputStream siddhiQueryInputStream;
    try {
        byte[] byteArray = policy.getSiddhiQuery().getBytes(Charset.defaultCharset());
        int lengthOfBytes = byteArray.length;
        siddhiQueryInputStream = new ByteArrayInputStream(byteArray);
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_SQL);
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateStatement = connection.prepareStatement(SQLConstants.UPDATE_GLOBAL_POLICY_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.setString(1, policy.getDescription());
        updateStatement.setBinaryStream(2, siddhiQueryInputStream, lengthOfBytes);
        updateStatement.setString(3, policy.getKeyTemplate());
        if (!StringUtils.isBlank(policy.getPolicyName()) && policy.getTenantId() != -1) {
            updateStatement.setString(4, policy.getPolicyName());
            updateStatement.setInt(5, policy.getTenantId());
        } else if (!StringUtils.isBlank(policy.getUUID())) {
            updateStatement.setString(4, 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 Global Policy: " + policy.toString(), ex);
            }
        }
        handleException("Failed to update global policy: " + policy.getPolicyName() + '-' + policy.getTenantId(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(updateStatement, connection, null);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ByteArrayInputStream(java.io.ByteArrayInputStream) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 99 with Tenant

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

the class ApiMgtDAO method getAPIProviderByNameAndVersion.

/**
 * This method is used to get the API provider by giving API name, API version and tenant domain
 *
 * @param apiName    API name
 * @param apiVersion API version
 * @param tenant     tenant domain
 * @return API provider
 * @throws APIManagementException if failed to get the API provider by giving API name, API version, tenant domain
 */
public String getAPIProviderByNameAndVersion(String apiName, String apiVersion, String tenant) throws APIManagementException {
    if (StringUtils.isBlank(apiName) || StringUtils.isBlank(apiVersion) || StringUtils.isBlank(tenant)) {
        String msg = "API name, version, tenant cannot be null when fetching provider";
        log.error(msg);
        throw new APIManagementException(msg);
    }
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    String apiProvider = null;
    String getAPIProviderQuery = null;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        if (MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenant)) {
            // in this case, the API should be fetched from super tenant
            getAPIProviderQuery = SQLConstants.GET_API_PROVIDER_WITH_NAME_VERSION_FOR_SUPER_TENANT;
            prepStmt = connection.prepareStatement(getAPIProviderQuery);
        } else {
            // in this case, the API should be fetched from the respective tenant
            getAPIProviderQuery = SQLConstants.GET_API_PROVIDER_WITH_NAME_VERSION_FOR_GIVEN_TENANT;
            prepStmt = connection.prepareStatement(getAPIProviderQuery);
            prepStmt.setString(3, "%" + tenant + "%");
        }
        prepStmt.setString(1, apiName);
        prepStmt.setString(2, apiVersion);
        rs = prepStmt.executeQuery();
        if (rs.next()) {
            apiProvider = rs.getString("API_PROVIDER");
        }
        if (StringUtils.isBlank(apiProvider)) {
            String msg = "Unable to find provider for API: " + apiName + " in the database";
            log.warn(msg);
        }
    } catch (SQLException e) {
        handleException("Error while locating API: " + apiName + " from the database", e);
    }
    return apiProvider;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 100 with Tenant

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

the class APIProviderImplTest method testGetCustomApiInSequences.

@Test
public void testGetCustomApiInSequences() throws Exception {
    APIIdentifier apiId = new APIIdentifier("admin", "API1", "1.0.1");
    APIProviderImplWrapper apiProvider = new APIProviderImplWrapper(apimgtDAO, scopesDAO);
    mockSequences(APIConstants.API_CUSTOM_INSEQUENCE_LOCATION, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN, apiId);
    List<String> sequenceList = apiProvider.getCustomApiInSequences(apiId);
    Assert.assertEquals(1, sequenceList.size());
    // OMException when building OMElement
    PowerMockito.when(APIUtil.buildOMElement(any(InputStream.class))).thenThrow(new OMException());
    apiProvider.getCustomApiInSequences(apiId);
    // org.wso2.carbon.registry.api.RegistryException
    ServiceReferenceHolder sh = PowerMockito.mock(ServiceReferenceHolder.class);
    PowerMockito.when(ServiceReferenceHolder.getInstance()).thenReturn(sh);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    PowerMockito.when(sh.getRegistryService()).thenReturn(registryService);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenReturn(registry);
    Mockito.when(registry.resourceExists(APIUtil.getSequencePath(apiId, APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN))).thenThrow(org.wso2.carbon.registry.api.RegistryException.class);
    String msg = "Error while processing the " + APIConstants.API_CUSTOM_SEQUENCE_TYPE_IN + " sequences of " + apiId + " in the registry";
    try {
        apiProvider.getCustomApiInSequences(apiId);
    } catch (APIManagementException e) {
        Assert.assertEquals(msg, e.getMessage());
    }
    // Registry Exception
    PowerMockito.when(registryService.getGovernanceSystemRegistry(Matchers.anyInt())).thenThrow(RegistryException.class);
    String msg1 = "Error while retrieving registry for tenant -1";
    try {
        apiProvider.getCustomApiInSequences(apiId);
    } catch (APIManagementException e) {
        Assert.assertEquals(msg1, e.getMessage());
    }
}
Also used : ServiceReferenceHolder(org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder) InputStream(java.io.InputStream) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) RegistryService(org.wso2.carbon.registry.core.service.RegistryService) OMException(org.apache.axiom.om.OMException) Test(org.junit.Test) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest)

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