Search in sources :

Example 86 with Tenant

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

the class ApiMgtDAO method isApplicationExist.

/**
 * Check whether given application name is available under current subscriber or group
 *
 * @param appName  application name
 * @param username subscriber
 * @param groupId  group of the subscriber
 * @param organization identifier of the organization
 * @return true if application is available for the subscriber
 * @throws APIManagementException if failed to get applications for given subscriber
 */
public boolean isApplicationExist(String appName, String username, String groupId, String organization) throws APIManagementException {
    if (username == null) {
        return false;
    }
    Subscriber subscriber = getSubscriber(username);
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;
    int appId = 0;
    String sqlQuery = SQLConstants.GET_APPLICATION_ID_PREFIX;
    String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
    String whereClauseWithGroupIdCaseInsensitive = " AND (APP.GROUP_ID = ? " + "OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
    String whereClauseWithMultiGroupId = " AND  ( (APP.APPLICATION_ID IN (SELECT APPLICATION_ID  FROM " + "AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?))  OR  ( SUB.USER_ID = ? ) " + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
    String whereClauseWithMultiGroupIdCaseInsensitive = " AND  ( (APP.APPLICATION_ID IN  (SELECT APPLICATION_ID " + "FROM AM_APPLICATION_GROUP_MAPPING WHERE GROUP_ID IN ($params) AND TENANT = ?)) " + "OR (LOWER(SUB.USER_ID) = LOWER(?))" + "OR (APP.APPLICATION_ID IN (SELECT APPLICATION_ID FROM AM_APPLICATION WHERE GROUP_ID = ?)))";
    String whereClause = " AND SUB.USER_ID = ? ";
    String whereClauseCaseInsensitive = " AND LOWER(SUB.USER_ID) = LOWER(?) ";
    try {
        connection = APIMgtDBUtil.getConnection();
        if (!StringUtils.isEmpty(groupId)) {
            if (multiGroupAppSharingEnabled) {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithMultiGroupId;
                }
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] grpIdArray = groupId.split(",");
                int noOfParams = grpIdArray.length;
                preparedStatement = fillQueryParams(connection, sqlQuery, grpIdArray, 3);
                preparedStatement.setString(1, appName);
                preparedStatement.setString(2, organization);
                int paramIndex = noOfParams + 2;
                preparedStatement.setString(++paramIndex, tenantDomain);
                preparedStatement.setString(++paramIndex, subscriber.getName());
                preparedStatement.setString(++paramIndex, tenantDomain + '/' + groupId);
            } else {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithGroupId;
                }
                preparedStatement = connection.prepareStatement(sqlQuery);
                preparedStatement.setString(1, appName);
                preparedStatement.setString(2, organization);
                preparedStatement.setString(3, groupId);
                preparedStatement.setString(4, subscriber.getName());
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                sqlQuery += whereClauseCaseInsensitive;
            } else {
                sqlQuery += whereClause;
            }
            preparedStatement = connection.prepareStatement(sqlQuery);
            preparedStatement.setString(1, appName);
            preparedStatement.setString(2, organization);
            preparedStatement.setString(3, subscriber.getName());
        }
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            appId = resultSet.getInt("APPLICATION_ID");
        }
        if (appId > 0) {
            return true;
        }
    } catch (SQLException e) {
        handleException("Error while getting the id  of " + appName + " from the persistence store.", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(preparedStatement, connection, resultSet);
    }
    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 87 with Tenant

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

the class ApiMgtDAO method getAllSharedScopes.

/**
 * Get all shared scopes for tenant.
 *
 * @param tenantDomain Tenant Domain
 * @return shared scope list
 * @throws APIManagementException if an error occurs while getting all shared scopes for tenant
 */
public List<Scope> getAllSharedScopes(String tenantDomain) throws APIManagementException {
    List<Scope> scopeList = null;
    int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQLConstants.GET_SHARED_SCOPE_USAGE_COUNT_BY_TENANT)) {
        statement.setInt(1, tenantId);
        statement.setInt(2, tenantId);
        try (ResultSet rs = statement.executeQuery()) {
            scopeList = new ArrayList<>();
            while (rs.next()) {
                Scope scope = new Scope();
                scope.setId(rs.getString("UUID"));
                scope.setKey(rs.getString("NAME"));
                scope.setUsageCount(rs.getInt("usages"));
                scopeList.add(scope);
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get all Shared Scopes for tenant: " + tenantDomain, e);
    }
    return scopeList;
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 88 with Tenant

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

the class CertificateMgtDAO method addCertificate.

/**
 * Method to add a new certificate to the database.
 *
 * @param alias    : Alias for the new certificate.
 * @param endpoint : The endpoint/ server url which the certificate will be mapped to.
 * @param tenantId : The Id of the tenant who uploaded the certificate.
 * @return : True if the information is added successfully, false otherwise.
 * @throws CertificateManagementException if existing entry is found for the given endpoint or alias.
 */
public boolean addCertificate(String certificate, String alias, String endpoint, int tenantId) throws CertificateManagementException, CertificateAliasExistsException {
    boolean result = false;
    String addCertQuery = SQLConstants.CertificateConstants.INSERT_CERTIFICATE;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        boolean certificateExist = isCertificateExist(connection, alias, tenantId);
        if (certificateExist) {
            if (log.isDebugEnabled()) {
                log.debug("A certificate for the endpoint " + endpoint + " has already added with alias " + alias);
            }
            String message = "Alias or Endpoint exists in the database!";
            throw new CertificateAliasExistsException(message);
        }
        connection.setAutoCommit(false);
        try (PreparedStatement preparedStatement = connection.prepareStatement(addCertQuery)) {
            preparedStatement.setInt(1, tenantId);
            preparedStatement.setString(2, endpoint);
            preparedStatement.setString(3, alias);
            preparedStatement.setBinaryStream(4, getInputStream(certificate));
            result = preparedStatement.executeUpdate() == 1;
            connection.commit();
        } catch (SQLException e) {
            handleConnectionRollBack(connection);
            if (log.isDebugEnabled()) {
                log.debug("Error occurred while adding certificate metadata to database.", e);
            }
            handleException("Error while persisting certificate metadata.", e);
        }
    } catch (SQLException e) {
        handleException("Error while retrieving connection", e);
    }
    return result;
}
Also used : SQLException(java.sql.SQLException) CertificateAliasExistsException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateAliasExistsException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Example 89 with Tenant

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

the class CertificateMgtDAO method getCertificate.

/**
 * Method to retrieve certificate metadata from db for specific tenant which matches alias or endpoint.
 * From alias and endpoint, only one parameter is required.
 *
 * @param tenantId : The id of the tenant which the certificate belongs to.
 * @param alias    : Alias for the certificate. (Optional)
 * @param endpoint : The endpoint/ server url which the certificate is mapped to. (Optional)
 * @return : A CertificateMetadataDTO object if the certificate is retrieved successfully, null otherwise.
 */
public CertificateMetadataDTO getCertificate(String alias, String endpoint, int tenantId) throws CertificateManagementException {
    String getCertQuery;
    getCertQuery = SQLConstants.CertificateConstants.GET_CERTIFICATE_TENANT_ALIAS_ENDPOINT;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(getCertQuery)) {
            preparedStatement.setInt(1, tenantId);
            preparedStatement.setString(2, alias);
            preparedStatement.setString(3, endpoint);
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    CertificateMetadataDTO certificateMetadataDTO = new CertificateMetadataDTO();
                    certificateMetadataDTO.setAlias(resultSet.getString("ALIAS"));
                    certificateMetadataDTO.setEndpoint(resultSet.getString("END_POINT"));
                    try (InputStream certificate = resultSet.getBinaryStream("CERTIFICATE")) {
                        certificateMetadataDTO.setCertificate(APIMgtDBUtil.getStringFromInputStream(certificate));
                    }
                    return certificateMetadataDTO;
                }
            }
        }
    } catch (SQLException | IOException e) {
        handleException("Error while retrieving certificate metadata.", e);
    }
    throw new CertificateManagementException("Certificate didn't exist with alias" + alias);
}
Also used : CertificateMetadataDTO(org.wso2.carbon.apimgt.api.dto.CertificateMetadataDTO) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) CertificateManagementException(org.wso2.carbon.apimgt.impl.certificatemgt.exceptions.CertificateManagementException) PreparedStatement(java.sql.PreparedStatement) IOException(java.io.IOException)

Example 90 with Tenant

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

the class CertificateMgtDAO method updateClientCertificate.

/**
 * To update an already existing client certificate.
 *
 * @param certificate : Specific certificate.
 * @param alias       : Alias of the certificate.
 * @param tier        : Name of tier related with the certificate.
 * @param tenantId    : ID of the tenant.
 * @param organization : Organization
 * @return true if the update succeeds, unless false.
 * @throws CertificateManagementException Certificate Management Exception.
 */
public boolean updateClientCertificate(String certificate, String alias, String tier, int tenantId, String organization) throws CertificateManagementException {
    List<ClientCertificateDTO> clientCertificateDTOList = getClientCertificates(tenantId, alias, null, organization);
    ClientCertificateDTO clientCertificateDTO;
    if (clientCertificateDTOList.size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("Client certificate update request is received for a non-existing alias " + alias + " of " + "tenant " + tenantId);
        }
        return false;
    }
    clientCertificateDTO = clientCertificateDTOList.get(0);
    if (StringUtils.isNotEmpty(certificate)) {
        clientCertificateDTO.setCertificate(certificate);
    }
    if (StringUtils.isNotEmpty(tier)) {
        clientCertificateDTO.setTierName(tier);
    }
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try {
            connection.setAutoCommit(false);
            deleteClientCertificate(connection, null, alias, tenantId);
            addClientCertificate(connection, clientCertificateDTO.getCertificate(), clientCertificateDTO.getApiIdentifier(), alias, clientCertificateDTO.getTierName(), tenantId, organization);
            connection.commit();
        } catch (SQLException e) {
            handleConnectionRollBack(connection);
            handleException("Error while updating client certificate for the API for the alias " + alias, e);
        }
    } catch (SQLException e) {
        handleException("Error while updating client certificate for the API for the alias " + alias, e);
    }
    return true;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ClientCertificateDTO(org.wso2.carbon.apimgt.api.dto.ClientCertificateDTO)

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