Search in sources :

Example 81 with Tenant

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

the class ApiMgtDAO method getSubscriptionBlockCondition.

/**
 * Get details of the subscription block condition by condition value and tenant domain
 *
 * @param conditionValue condition value of the block condition
 * @param tenantDomain   tenant domain of the block condition
 * @return Block condition
 * @throws APIManagementException
 */
public BlockConditionsDTO getSubscriptionBlockCondition(String conditionValue, String tenantDomain) throws APIManagementException {
    Connection connection = null;
    PreparedStatement selectPreparedStatement = null;
    ResultSet resultSet = null;
    BlockConditionsDTO blockCondition = null;
    try {
        String query = SQLConstants.ThrottleSQLConstants.GET_SUBSCRIPTION_BLOCK_CONDITION_BY_VALUE_AND_DOMAIN_SQL;
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(true);
        selectPreparedStatement = connection.prepareStatement(query);
        selectPreparedStatement.setString(1, conditionValue);
        selectPreparedStatement.setString(2, tenantDomain);
        resultSet = selectPreparedStatement.executeQuery();
        if (resultSet.next()) {
            blockCondition = new BlockConditionsDTO();
            blockCondition.setEnabled(resultSet.getBoolean("ENABLED"));
            blockCondition.setConditionType(resultSet.getString("TYPE"));
            blockCondition.setConditionValue(resultSet.getString("BLOCK_CONDITION"));
            blockCondition.setConditionId(resultSet.getInt("CONDITION_ID"));
            blockCondition.setTenantDomain(resultSet.getString("DOMAIN"));
            blockCondition.setUUID(resultSet.getString("UUID"));
        }
    } catch (SQLException e) {
        if (connection != null) {
            try {
                connection.rollback();
            } catch (SQLException ex) {
                handleException("Failed to rollback getting Subscription Block condition with condition value " + conditionValue + " of tenant " + tenantDomain, ex);
            }
        }
        handleException("Failed to get Subscription Block condition with condition value " + conditionValue + " of tenant " + tenantDomain, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(selectPreparedStatement, connection, resultSet);
    }
    return blockCondition;
}
Also used : BlockConditionsDTO(org.wso2.carbon.apimgt.api.model.BlockConditionsDTO) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 82 with Tenant

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

the class ApiMgtDAO method getEnvironment.

/**
 * Returns the Environment for the uuid in the tenant domain.
 *
 * @param tenantDomain the tenant domain to look environment
 * @param uuid         UUID of the environment
 * @return Gateway environment with given UUID
 */
public Environment getEnvironment(String tenantDomain, String uuid) throws APIManagementException {
    Environment env = null;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement prepStmt = connection.prepareStatement(SQLConstants.GET_ENVIRONMENT_BY_ORGANIZATION_AND_UUID_SQL)) {
        prepStmt.setString(1, tenantDomain);
        prepStmt.setString(2, uuid);
        try (ResultSet rs = prepStmt.executeQuery()) {
            if (rs.next()) {
                Integer id = rs.getInt("ID");
                String name = rs.getString("NAME");
                String displayName = rs.getString("DISPLAY_NAME");
                String description = rs.getString("DESCRIPTION");
                String provider = rs.getString("PROVIDER");
                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));
            }
        }
    } catch (SQLException e) {
        handleException("Failed to get Environment in tenant domain:" + tenantDomain, e);
    }
    return env;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) Environment(org.wso2.carbon.apimgt.api.model.Environment) PreparedStatement(java.sql.PreparedStatement)

Example 83 with Tenant

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

the class ApiMgtDAO method getSubscribedAPIs.

/**
 * This method returns the set of APIs for given subscriber, subscribed under the specified application.
 *
 * @param subscriber      subscriber
 * @param applicationName Application Name
 * @return Set<API>
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get SubscribedAPIs
 */
public Set<SubscribedAPI> getSubscribedAPIs(Subscriber subscriber, String applicationName, String groupingId) throws APIManagementException {
    Set<SubscribedAPI> subscribedAPIs = new LinkedHashSet<SubscribedAPI>();
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    String sqlQuery = SQLConstants.GET_SUBSCRIBED_APIS_SQL;
    String whereClauseWithGroupId = " AND (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?))";
    String whereClauseWithGroupIdorceCaseInsensitiveComp = " AND (APP.GROUP_ID = ?" + " OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL) AND LOWER(SUB.USER_ID) = LOWER(?)))";
    String whereClause = " AND SUB.USER_ID = ? ";
    String whereClauseCaseSensitive = " 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 = ? ))";
    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" + "(?) ))";
    try {
        connection = APIMgtDBUtil.getConnection();
        if (groupingId != null && !"null".equals(groupingId) && !groupingId.isEmpty()) {
            if (multiGroupAppSharingEnabled) {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithMultiGroupIdCaseInsensitive;
                } else {
                    sqlQuery += whereClauseWithMultiGroupId;
                }
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                String[] groupIdArr = groupingId.split(",");
                ps = fillQueryParams(connection, sqlQuery, groupIdArr, 3);
                int tenantId = APIUtil.getTenantId(subscriber.getName());
                ps.setInt(1, tenantId);
                ps.setString(2, applicationName);
                int paramIndex = groupIdArr.length + 2;
                ps.setString(++paramIndex, tenantDomain);
                ps.setString(++paramIndex, subscriber.getName());
            } else {
                if (forceCaseInsensitiveComparisons) {
                    sqlQuery += whereClauseWithGroupIdorceCaseInsensitiveComp;
                } else {
                    sqlQuery += whereClauseWithGroupId;
                }
                ps = connection.prepareStatement(sqlQuery);
                int tenantId = APIUtil.getTenantId(subscriber.getName());
                ps.setInt(1, tenantId);
                ps.setString(2, applicationName);
                ps.setString(3, groupingId);
                ps.setString(4, subscriber.getName());
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                sqlQuery += whereClauseCaseSensitive;
            } else {
                sqlQuery += whereClause;
            }
            ps = connection.prepareStatement(sqlQuery);
            int tenantId = APIUtil.getTenantId(subscriber.getName());
            ps.setInt(1, tenantId);
            ps.setString(2, applicationName);
            ps.setString(3, subscriber.getName());
        }
        result = ps.executeQuery();
        while (result.next()) {
            APIIdentifier apiIdentifier = new APIIdentifier(APIUtil.replaceEmailDomain(result.getString("API_PROVIDER")), result.getString("API_NAME"), result.getString("API_VERSION"));
            apiIdentifier.setUuid(result.getString("API_UUID"));
            SubscribedAPI subscribedAPI = new SubscribedAPI(subscriber, apiIdentifier);
            subscribedAPI.setSubscriptionId(result.getInt("SUBS_ID"));
            subscribedAPI.setSubStatus(result.getString("SUB_STATUS"));
            subscribedAPI.setSubCreatedStatus(result.getString("SUBS_CREATE_STATE"));
            subscribedAPI.setUUID(result.getString("SUB_UUID"));
            subscribedAPI.setTier(new Tier(result.getString(APIConstants.SUBSCRIPTION_FIELD_TIER_ID)));
            Application application = new Application(result.getString("APP_NAME"), subscriber);
            application.setUUID(result.getString("APP_UUID"));
            subscribedAPI.setApplication(application);
            subscribedAPIs.add(subscribedAPI);
        }
    } catch (SQLException e) {
        handleException("Failed to get SubscribedAPI of :" + subscriber.getName(), e);
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, result);
    }
    return subscribedAPIs;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) ResultSet(java.sql.ResultSet) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 84 with Tenant

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

the class ApiMgtDAO method getApplicationByName.

/**
 * Fetches an Application by name.
 *
 * @param applicationName Name of the Application
 * @param userId          Name of the User.
 * @param groupId         Group ID
 * @throws APIManagementException
 */
public Application getApplicationByName(String applicationName, String userId, String groupId) throws APIManagementException {
    // mysql> select APP.APPLICATION_ID, APP.NAME, APP.SUBSCRIBER_ID,APP.APPLICATION_TIER,APP.CALLBACK_URL,APP
    // .DESCRIPTION,
    // APP.APPLICATION_STATUS from AM_SUBSCRIBER as SUB,AM_APPLICATION as APP
    // where SUB.user_id='admin' AND APP.name='DefaultApplication' AND SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID;
    Connection connection = null;
    PreparedStatement prepStmt = null;
    ResultSet rs = null;
    int applicationId = 0;
    Application application = null;
    try {
        connection = APIMgtDBUtil.getConnection();
        String query = SQLConstants.GET_APPLICATION_BY_NAME_PREFIX;
        String whereClause = "  WHERE SUB.USER_ID =? AND APP.NAME=? AND SUB.SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
        String whereClauseCaseInSensitive = "  WHERE LOWER(SUB.USER_ID) =LOWER(?) AND APP.NAME=? AND SUB" + "" + ".SUBSCRIBER_ID=APP.SUBSCRIBER_ID";
        String whereClauseWithGroupId = "  WHERE  (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND SUB.USER_ID = ?)) AND " + "APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        String whereClauseWithGroupIdCaseInSensitive = "  WHERE  (APP.GROUP_ID = ? OR ((APP.GROUP_ID='' OR APP.GROUP_ID IS NULL)" + " AND LOWER(SUB.USER_ID) = LOWER(?))) AND " + "APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        String whereClauseWithMultiGroupId = "  WHERE  ((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 = ?))) " + "AND APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        String whereClauseWithMultiGroupIdCaseInSensitive = "  WHERE  ((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 = " + "?))) " + "AND APP.NAME = ? AND SUB.SUBSCRIBER_ID = APP.SUBSCRIBER_ID";
        if (groupId != null && !"null".equals(groupId) && !groupId.isEmpty()) {
            if (multiGroupAppSharingEnabled) {
                Subscriber subscriber = getSubscriber(userId);
                String tenantDomain = MultitenantUtils.getTenantDomain(subscriber.getName());
                if (forceCaseInsensitiveComparisons) {
                    query = query + whereClauseWithMultiGroupIdCaseInSensitive;
                } else {
                    query = query + whereClauseWithMultiGroupId;
                }
                String[] groupIds = groupId.split(",");
                int parameterIndex = groupIds.length;
                prepStmt = fillQueryParams(connection, query, groupIds, 1);
                prepStmt.setString(++parameterIndex, tenantDomain);
                prepStmt.setString(++parameterIndex, userId);
                prepStmt.setString(++parameterIndex, tenantDomain + '/' + groupId);
                prepStmt.setString(++parameterIndex, applicationName);
            } else {
                if (forceCaseInsensitiveComparisons) {
                    query = query + whereClauseWithGroupIdCaseInSensitive;
                } else {
                    query = query + whereClauseWithGroupId;
                }
                prepStmt = connection.prepareStatement(query);
                prepStmt.setString(1, groupId);
                prepStmt.setString(2, userId);
                prepStmt.setString(3, applicationName);
            }
        } else {
            if (forceCaseInsensitiveComparisons) {
                query = query + whereClauseCaseInSensitive;
            } else {
                query = query + whereClause;
            }
            prepStmt = connection.prepareStatement(query);
            prepStmt.setString(1, userId);
            prepStmt.setString(2, applicationName);
        }
        rs = prepStmt.executeQuery();
        while (rs.next()) {
            String subscriberId = rs.getString("SUBSCRIBER_ID");
            String subscriberName = rs.getString("USER_ID");
            Subscriber subscriber = new Subscriber(subscriberName);
            subscriber.setId(Integer.parseInt(subscriberId));
            application = new Application(applicationName, subscriber);
            application.setOwner(rs.getString("CREATED_BY"));
            application.setDescription(rs.getString("DESCRIPTION"));
            application.setStatus(rs.getString("APPLICATION_STATUS"));
            application.setCallbackUrl(rs.getString("CALLBACK_URL"));
            applicationId = rs.getInt("APPLICATION_ID");
            application.setId(applicationId);
            application.setTier(rs.getString("APPLICATION_TIER"));
            application.setUUID(rs.getString("UUID"));
            application.setGroupId(rs.getString("GROUP_ID"));
            application.setOwner(rs.getString("CREATED_BY"));
            application.setTokenType(rs.getString("TOKEN_TYPE"));
            if (multiGroupAppSharingEnabled) {
                setGroupIdInApplication(connection, application);
            }
            if (application != null) {
                Map<String, String> applicationAttributes = getApplicationAttributes(connection, applicationId);
                application.setApplicationAttributes(applicationAttributes);
            }
        }
    } catch (SQLException e) {
        handleException("Error while obtaining details of the Application : " + applicationName, e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
    }
    return application;
}
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) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 85 with Tenant

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

the class ApiMgtDAO method getworkflowReferenceByExternalWorkflowReferenceID.

/**
 * Get the Pending workflow Request using ExternalWorkflowReference for a particular tenant
 *
 * @param externelWorkflowRef of pending workflow request
 * @param status              workflow status of workflow pending process
 * @param tenantDomain        tenant domain of user
 * @return workflow pending request
 */
public Workflow getworkflowReferenceByExternalWorkflowReferenceID(String externelWorkflowRef, String status, String tenantDomain) throws APIManagementException {
    ResultSet rs = null;
    Workflow workflow = new Workflow();
    String sqlQuery = SQLConstants.GET_ALL_WORKFLOW_DETAILS_BY_EXTERNAL_WORKFLOW_REFERENCE;
    try (Connection connection = APIMgtDBUtil.getConnection();
        PreparedStatement prepStmt = connection.prepareStatement(sqlQuery)) {
        try {
            prepStmt.setString(1, externelWorkflowRef);
            prepStmt.setString(2, status);
            prepStmt.setString(3, tenantDomain);
            rs = prepStmt.executeQuery();
            while (rs.next()) {
                workflow.setWorkflowId(rs.getInt("WF_ID"));
                workflow.setWorkflowReference(rs.getString("WF_REFERENCE"));
                workflow.setWorkflowType(rs.getString("WF_TYPE"));
                String workflowstatus = rs.getString("WF_STATUS");
                workflow.setStatus(org.wso2.carbon.apimgt.api.WorkflowStatus.valueOf(workflowstatus));
                workflow.setCreatedTime(rs.getTimestamp("WF_CREATED_TIME").toString());
                workflow.setUpdatedTime(rs.getTimestamp("WF_UPDATED_TIME").toString());
                workflow.setWorkflowDescription(rs.getString("WF_STATUS_DESC"));
                workflow.setTenantId(rs.getInt("TENANT_ID"));
                workflow.setTenantDomain(rs.getString("TENANT_DOMAIN"));
                workflow.setExternalWorkflowReference(rs.getString("WF_EXTERNAL_REFERENCE"));
                InputStream targetStream = rs.getBinaryStream("WF_METADATA");
                InputStream propertiesTargetStream = rs.getBinaryStream("WF_PROPERTIES");
                if (targetStream != null) {
                    String metadata = APIMgtDBUtil.getStringFromInputStream(targetStream);
                    Gson metadataGson = new Gson();
                    JSONObject metadataJson = metadataGson.fromJson(metadata, JSONObject.class);
                    workflow.setMetadata(metadataJson);
                } else {
                    JSONObject metadataJson = new JSONObject();
                    workflow.setMetadata(metadataJson);
                }
                if (propertiesTargetStream != null) {
                    String properties = APIMgtDBUtil.getStringFromInputStream(propertiesTargetStream);
                    Gson propertiesGson = new Gson();
                    JSONObject propertiesJson = propertiesGson.fromJson(properties, JSONObject.class);
                    workflow.setProperties(propertiesJson);
                } else {
                    JSONObject propertiesJson = new JSONObject();
                    workflow.setProperties(propertiesJson);
                }
            }
        } catch (SQLException e) {
            handleException("Error when retriving the workflow details. ", e);
        } finally {
            APIMgtDBUtil.closeAllConnections(prepStmt, connection, rs);
        }
    } catch (SQLException e) {
        handleException("Error when retriving the workflow details. ", e);
    }
    return workflow;
}
Also used : JSONObject(org.json.simple.JSONObject) SQLException(java.sql.SQLException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ResultSet(java.sql.ResultSet) Connection(java.sql.Connection) Workflow(org.wso2.carbon.apimgt.api.model.Workflow) Gson(com.google.gson.Gson) PreparedStatement(java.sql.PreparedStatement)

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