Search in sources :

Example 1 with ApiTypeWrapper

use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.

the class AbstractAPIManager method getAPIorAPIProductByUUID.

/**
 * Get API or APIProduct by registry artifact id
 *
 * @param uuid                  Registry artifact id
 * @param requestedTenantDomain tenantDomain for the registry
 * @return ApiTypeWrapper wrapping the API or APIProduct of the provided artifact id
 * @throws APIManagementException
 */
public ApiTypeWrapper getAPIorAPIProductByUUID(String uuid, String requestedTenantDomain) throws APIManagementException {
    boolean tenantFlowStarted = false;
    try {
        Registry registry;
        if (requestedTenantDomain != null) {
            int id = getTenantManager().getTenantId(requestedTenantDomain);
            startTenantFlow(requestedTenantDomain);
            tenantFlowStarted = true;
            if (APIConstants.WSO2_ANONYMOUS_USER.equals(this.username)) {
                registry = getRegistryService().getGovernanceUserRegistry(this.username, id);
            } else if (this.tenantDomain != null && !this.tenantDomain.equals(requestedTenantDomain)) {
                registry = getRegistryService().getGovernanceSystemRegistry(id);
            } else {
                registry = this.registry;
            }
        } else {
            registry = this.registry;
        }
        GenericArtifactManager artifactManager = getAPIGenericArtifactManagerFromUtil(registry, APIConstants.API_KEY);
        GenericArtifact apiArtifact = artifactManager.getGenericArtifact(uuid);
        if (apiArtifact != null) {
            String type = apiArtifact.getAttribute(APIConstants.API_OVERVIEW_TYPE);
            if (APIConstants.API_PRODUCT.equals(type)) {
                APIProduct apiProduct = getApiProduct(registry, apiArtifact);
                String productTenantDomain = getTenantDomain(apiProduct.getId());
                if (APIConstants.API_GLOBAL_VISIBILITY.equals(apiProduct.getVisibility())) {
                    return new ApiTypeWrapper(apiProduct);
                }
                if (this.tenantDomain == null || !this.tenantDomain.equals(productTenantDomain)) {
                    throw new APIManagementException("User " + username + " does not have permission to view API Product : " + apiProduct.getId().getName());
                }
                return new ApiTypeWrapper(apiProduct);
            } else {
                API api = getApiForPublishing(registry, apiArtifact);
                String apiTenantDomain = getTenantDomain(api.getId());
                if (APIConstants.API_GLOBAL_VISIBILITY.equals(api.getVisibility())) {
                    return new ApiTypeWrapper(api);
                }
                if (this.tenantDomain == null || !this.tenantDomain.equals(apiTenantDomain)) {
                    throw new APIManagementException("User " + username + " does not have permission to view API : " + api.getId().getApiName());
                }
                return new ApiTypeWrapper(api);
            }
        } else {
            String msg = "Failed to get API. API artifact corresponding to artifactId " + uuid + " does not exist";
            throw new APIMgtResourceNotFoundException(msg);
        }
    } catch (RegistryException | org.wso2.carbon.user.api.UserStoreException e) {
        String msg = "Failed to get API";
        throw new APIManagementException(msg, e);
    } finally {
        if (tenantFlowStarted) {
            endTenantFlow();
        }
    }
}
Also used : GenericArtifact(org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact) GenericArtifactManager(org.wso2.carbon.governance.api.generic.GenericArtifactManager) ApiTypeWrapper(org.wso2.carbon.apimgt.api.model.ApiTypeWrapper) UserRegistry(org.wso2.carbon.registry.core.session.UserRegistry) Registry(org.wso2.carbon.registry.core.Registry) APIMgtResourceNotFoundException(org.wso2.carbon.apimgt.api.APIMgtResourceNotFoundException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) APIProduct(org.wso2.carbon.apimgt.api.model.APIProduct) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) PublisherAPI(org.wso2.carbon.apimgt.persistence.dto.PublisherAPI) API(org.wso2.carbon.apimgt.api.model.API)

Example 2 with ApiTypeWrapper

use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.

the class ApiMgtDAO method addSubscription.

private int addSubscription(Connection connection, ApiTypeWrapper apiTypeWrapper, Application application, String subscriptionStatus, String subscriber) throws APIManagementException, SQLException {
    final boolean isProduct = apiTypeWrapper.isAPIProduct();
    int subscriptionId = -1;
    int id = -1;
    String apiUUID;
    Identifier identifier;
    String tier;
    // Query to check if this subscription already exists
    String checkDuplicateQuery = SQLConstants.CHECK_EXISTING_SUBSCRIPTION_API_SQL;
    if (!isProduct) {
        identifier = apiTypeWrapper.getApi().getId();
        apiUUID = apiTypeWrapper.getApi().getUuid();
        if (apiUUID != null) {
            id = getAPIID(apiUUID);
        }
        if (id == -1) {
            id = identifier.getId();
        }
    } else {
        identifier = apiTypeWrapper.getApiProduct().getId();
        id = apiTypeWrapper.getApiProduct().getProductId();
        apiUUID = apiTypeWrapper.getApiProduct().getUuid();
    }
    int tenantId = APIUtil.getTenantId(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
    try (PreparedStatement ps = connection.prepareStatement(checkDuplicateQuery)) {
        ps.setInt(1, id);
        ps.setInt(2, application.getId());
        try (ResultSet resultSet = ps.executeQuery()) {
            // If the subscription already exists
            if (resultSet.next()) {
                String subStatus = resultSet.getString("SUB_STATUS");
                String subCreationStatus = resultSet.getString("SUBS_CREATE_STATE");
                if ((APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.ON_HOLD.equals(subStatus) || APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) && APIConstants.SubscriptionCreatedStatus.SUBSCRIBE.equals(subCreationStatus)) {
                    // Throw error saying subscription already exists.
                    log.error(String.format("Subscription already exists for API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
                    throw new SubscriptionAlreadyExistingException(String.format("Subscription already exists for" + " API/API Prouct %s in Application %s", apiTypeWrapper.getName(), application.getName()));
                } else if (APIConstants.SubscriptionStatus.UNBLOCKED.equals(subStatus) && APIConstants.SubscriptionCreatedStatus.UN_SUBSCRIBE.equals(subCreationStatus)) {
                    deleteSubscriptionByApiIDAndAppID(id, application.getId(), connection);
                } else if (APIConstants.SubscriptionStatus.BLOCKED.equals(subStatus) || APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equals(subStatus)) {
                    log.error(String.format(String.format("Subscription to API/API Prouct %%s through application" + " %%s was blocked"), apiTypeWrapper.getName(), application.getName()));
                    throw new SubscriptionBlockedException(String.format("Subscription to API/API Product %s " + "through application %s was blocked", apiTypeWrapper.getName(), application.getName()));
                } else if (APIConstants.SubscriptionStatus.REJECTED.equals(subStatus)) {
                    throw new SubscriptionBlockedException("Subscription to API " + apiTypeWrapper.getName() + " through application " + application.getName() + " was rejected");
                }
            }
        }
    }
    // This query to update the AM_SUBSCRIPTION table
    String sqlQuery = SQLConstants.ADD_SUBSCRIPTION_SQL;
    // Adding data to the AM_SUBSCRIPTION table
    // ps = conn.prepareStatement(sqlQuery, Statement.RETURN_GENERATED_KEYS);
    String subscriptionIDColumn = "SUBSCRIPTION_ID";
    String subscriptionUUID = UUID.randomUUID().toString();
    if (connection.getMetaData().getDriverName().contains("PostgreSQL")) {
        subscriptionIDColumn = "subscription_id";
    }
    try (PreparedStatement preparedStForInsert = connection.prepareStatement(sqlQuery, new String[] { subscriptionIDColumn })) {
        if (!isProduct) {
            tier = apiTypeWrapper.getApi().getId().getTier();
            preparedStForInsert.setString(1, tier);
            preparedStForInsert.setString(10, tier);
        } else {
            tier = apiTypeWrapper.getApiProduct().getId().getTier();
            preparedStForInsert.setString(1, tier);
            preparedStForInsert.setString(10, tier);
        }
        preparedStForInsert.setInt(2, id);
        preparedStForInsert.setInt(3, application.getId());
        preparedStForInsert.setString(4, subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED);
        preparedStForInsert.setString(5, APIConstants.SubscriptionCreatedStatus.SUBSCRIBE);
        preparedStForInsert.setString(6, subscriber);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        preparedStForInsert.setTimestamp(7, timestamp);
        preparedStForInsert.setTimestamp(8, timestamp);
        preparedStForInsert.setString(9, subscriptionUUID);
        preparedStForInsert.executeUpdate();
        try (ResultSet rs = preparedStForInsert.getGeneratedKeys()) {
            while (rs.next()) {
                // subscriptionId = rs.getInt(1);
                subscriptionId = Integer.parseInt(rs.getString(1));
            }
        }
    }
    String tenantDomain = MultitenantUtils.getTenantDomain(APIUtil.replaceEmailDomainBack(identifier.getProviderName()));
    SubscriptionEvent subscriptionEvent = new SubscriptionEvent(UUID.randomUUID().toString(), System.currentTimeMillis(), APIConstants.EventType.SUBSCRIPTIONS_CREATE.name(), tenantId, tenantDomain, subscriptionId, subscriptionUUID, id, apiUUID, application.getId(), application.getUUID(), tier, (subscriptionStatus != null ? subscriptionStatus : APIConstants.SubscriptionStatus.UNBLOCKED));
    return subscriptionId;
}
Also used : SubscriptionBlockedException(org.wso2.carbon.apimgt.api.SubscriptionBlockedException) SubscriptionEvent(org.wso2.carbon.apimgt.impl.notifier.events.SubscriptionEvent) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) ResultSet(java.sql.ResultSet) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 3 with ApiTypeWrapper

use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.

the class ApiMgtDAO method makeKeysForwardCompatible.

public void makeKeysForwardCompatible(ApiTypeWrapper apiTypeWrapper, List<API> oldAPIVersions) throws APIManagementException {
    // if there are no previous versions, there is no need to copy subscriptions
    if (oldAPIVersions == null || oldAPIVersions.isEmpty()) {
        return;
    }
    String getSubscriptionDataQuery = SQLConstants.GET_SUBSCRIPTION_DATA_SQL.replaceAll("_API_VERSION_LIST_", String.join(",", Collections.nCopies(oldAPIVersions.size(), "?")));
    APIIdentifier apiIdentifier = apiTypeWrapper.getApi().getId();
    try {
        // Retrieve all the existing subscription for the old version
        try (Connection connection = APIMgtDBUtil.getConnection()) {
            connection.setAutoCommit(false);
            try (PreparedStatement prepStmt = connection.prepareStatement(getSubscriptionDataQuery)) {
                prepStmt.setString(1, APIUtil.replaceEmailDomainBack(apiIdentifier.getProviderName()));
                prepStmt.setString(2, apiIdentifier.getApiName());
                int index = 3;
                for (API oldAPI : oldAPIVersions) {
                    prepStmt.setString(index++, oldAPI.getId().getVersion());
                }
                try (ResultSet rs = prepStmt.executeQuery()) {
                    List<SubscriptionInfo> subscriptionData = new ArrayList<SubscriptionInfo>();
                    while (rs.next() && !(APIConstants.SubscriptionStatus.ON_HOLD.equals(rs.getString("SUB_STATUS")))) {
                        int subscriptionId = rs.getInt("SUBSCRIPTION_ID");
                        String tierId = rs.getString("TIER_ID");
                        int applicationId = rs.getInt("APPLICATION_ID");
                        String apiVersion = rs.getString("VERSION");
                        String subscriptionStatus = rs.getString("SUB_STATUS");
                        SubscriptionInfo info = new SubscriptionInfo(subscriptionId, tierId, applicationId, apiVersion, subscriptionStatus);
                        subscriptionData.add(info);
                    }
                    // To keep track of already added subscriptions (apps)
                    List<Integer> addedApplications = new ArrayList<>();
                    for (int i = oldAPIVersions.size() - 1; i >= 0; i--) {
                        API oldAPI = oldAPIVersions.get(i);
                        for (SubscriptionInfo info : subscriptionData) {
                            try {
                                if (info.getApiVersion().equals(oldAPI.getId().getVersion()) && !addedApplications.contains(info.getApplicationId())) {
                                    String subscriptionStatus;
                                    if (APIConstants.SubscriptionStatus.BLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.BLOCKED;
                                    } else if (APIConstants.SubscriptionStatus.UNBLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.UNBLOCKED;
                                    } else if (APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.PROD_ONLY_BLOCKED;
                                    } else if (APIConstants.SubscriptionStatus.REJECTED.equalsIgnoreCase(info.getSubscriptionStatus())) {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.REJECTED;
                                    } else {
                                        subscriptionStatus = APIConstants.SubscriptionStatus.ON_HOLD;
                                    }
                                    apiTypeWrapper.setTier(info.getTierId());
                                    Application application = getLightweightApplicationById(connection, info.getApplicationId());
                                    int subscriptionId = addSubscription(connection, apiTypeWrapper, application, subscriptionStatus, apiIdentifier.getProviderName());
                                    if (subscriptionId == -1) {
                                        String msg = "Unable to add a new subscription for the API: " + apiIdentifier.getName() + ":v" + apiIdentifier.getVersion();
                                        log.error(msg);
                                        throw new APIManagementException(msg);
                                    }
                                    addedApplications.add(info.getApplicationId());
                                }
                            // catching the exception because when copy the api without the option "require
                            // re-subscription"
                            // need to go forward rather throwing the exception
                            } catch (SubscriptionAlreadyExistingException e) {
                                log.error("Error while adding subscription " + e.getMessage(), e);
                            } catch (SubscriptionBlockedException e) {
                                log.info("Subscription is blocked: " + e.getMessage());
                            }
                        }
                    }
                }
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    } catch (SQLException e) {
        handleException("Error when executing the SQL queries", e);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) SubscriptionBlockedException(org.wso2.carbon.apimgt.api.SubscriptionBlockedException) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) ResultSet(java.sql.ResultSet) SubscriptionAlreadyExistingException(org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) SubscribedAPI(org.wso2.carbon.apimgt.api.model.SubscribedAPI) API(org.wso2.carbon.apimgt.api.model.API) Application(org.wso2.carbon.apimgt.api.model.Application)

Example 4 with ApiTypeWrapper

use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.

the class ApiMgtDAO method getComments.

/**
 **************************************
 * Returns all the Comments on an API
 *
 * @param apiTypeWrapper API type Wrapper
 * @param parentCommentID Parent Comment ID
 * @return Comment Array
 * @throws APIManagementException
 */
public CommentList getComments(ApiTypeWrapper apiTypeWrapper, String parentCommentID, Integer limit, Integer offset) throws APIManagementException {
    CommentList commentList = null;
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        int id = -1;
        String uuid;
        Identifier identifier;
        String currentApiUuid;
        if (apiTypeWrapper.isAPIProduct()) {
            identifier = apiTypeWrapper.getApiProduct().getId();
            uuid = apiTypeWrapper.getApiProduct().getUuid();
            APIRevision apiRevision = checkAPIUUIDIsARevisionUUID(uuid);
            if (apiRevision != null && apiRevision.getApiUUID() != null) {
                currentApiUuid = apiRevision.getApiUUID();
            } else {
                currentApiUuid = uuid;
            }
        } else {
            identifier = apiTypeWrapper.getApi().getId();
            uuid = apiTypeWrapper.getApi().getUuid();
            APIRevision apiRevision = checkAPIUUIDIsARevisionUUID(uuid);
            if (apiRevision != null && apiRevision.getApiUUID() != null) {
                currentApiUuid = apiRevision.getApiUUID();
            } else {
                currentApiUuid = uuid;
            }
        }
        id = getAPIID(currentApiUuid, connection);
        if (id == -1) {
            String msg = "Could not load API record for: " + identifier.getName();
            throw new APIManagementException(msg);
        }
        commentList = getComments(currentApiUuid, parentCommentID, limit, offset, connection);
    } catch (SQLException e) {
        handleException("Failed to retrieve comments for  " + apiTypeWrapper.getName(), e);
    }
    return commentList;
}
Also used : DeployedAPIRevision(org.wso2.carbon.apimgt.api.model.DeployedAPIRevision) APIRevision(org.wso2.carbon.apimgt.api.model.APIRevision) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) CommentList(org.wso2.carbon.apimgt.api.model.CommentList)

Example 5 with ApiTypeWrapper

use of org.wso2.carbon.apimgt.api.model.ApiTypeWrapper in project carbon-apimgt by wso2.

the class ApiMgtDAO method getComment.

/**
 ************************
 * Returns a specific comment of an API
 *
 * @param commentId  Comment ID
 * @param apiTypeWrapper Api Type Wrapper
 * @return Comment Array
 * @throws APIManagementException
 */
public Comment getComment(ApiTypeWrapper apiTypeWrapper, String commentId, Integer replyLimit, Integer replyOffset) throws APIManagementException {
    String uuid;
    Identifier identifier;
    if (apiTypeWrapper.isAPIProduct()) {
        identifier = apiTypeWrapper.getApiProduct().getId();
        uuid = apiTypeWrapper.getApiProduct().getUuid();
    } else {
        identifier = apiTypeWrapper.getApi().getId();
        uuid = apiTypeWrapper.getApi().getUuid();
    }
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        Comment comment = new Comment();
        int id = -1;
        String getCommentQuery = SQLConstants.GET_COMMENT_SQL;
        id = getAPIID(uuid, connection);
        if (id == -1) {
            String msg = "Could not load API record for: " + identifier.getName();
            throw new APIManagementException(msg);
        }
        try (PreparedStatement prepStmt = connection.prepareStatement(getCommentQuery)) {
            prepStmt.setString(1, uuid);
            prepStmt.setString(2, commentId);
            try (ResultSet resultSet = prepStmt.executeQuery()) {
                if (resultSet.next()) {
                    comment.setId(resultSet.getString("COMMENT_ID"));
                    comment.setText(resultSet.getString("COMMENT_TEXT"));
                    comment.setUser(resultSet.getString("CREATED_BY"));
                    comment.setCreatedTime(resultSet.getTimestamp("CREATED_TIME"));
                    comment.setUpdatedTime(resultSet.getTimestamp("UPDATED_TIME"));
                    comment.setApiId(resultSet.getString("API_ID"));
                    comment.setParentCommentID(resultSet.getString("PARENT_COMMENT_ID"));
                    comment.setEntryPoint(resultSet.getString("ENTRY_POINT"));
                    comment.setCategory(resultSet.getString("CATEGORY"));
                    comment.setReplies(getComments(uuid, commentId, replyLimit, replyOffset, connection));
                    return comment;
                }
            }
        }
    } catch (SQLException e) {
        handleException("Failed to retrieve comment for API " + identifier.getName() + "with comment ID " + commentId, e);
    }
    return null;
}
Also used : Comment(org.wso2.carbon.apimgt.api.model.Comment) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) APIProductIdentifier(org.wso2.carbon.apimgt.api.model.APIProductIdentifier) Identifier(org.wso2.carbon.apimgt.api.model.Identifier) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

ApiTypeWrapper (org.wso2.carbon.apimgt.api.model.ApiTypeWrapper)41 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)38 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)25 API (org.wso2.carbon.apimgt.api.model.API)24 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)24 APIConsumer (org.wso2.carbon.apimgt.api.APIConsumer)16 URI (java.net.URI)14 URISyntaxException (java.net.URISyntaxException)14 APIProduct (org.wso2.carbon.apimgt.api.model.APIProduct)14 Application (org.wso2.carbon.apimgt.api.model.Application)14 ArrayList (java.util.ArrayList)13 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)13 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)11 Tier (org.wso2.carbon.apimgt.api.model.Tier)10 Comment (org.wso2.carbon.apimgt.api.model.Comment)9 DevPortalAPI (org.wso2.carbon.apimgt.persistence.dto.DevPortalAPI)9 Test (org.junit.Test)8 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)8 SubscriptionAlreadyExistingException (org.wso2.carbon.apimgt.api.SubscriptionAlreadyExistingException)7 Identifier (org.wso2.carbon.apimgt.api.model.Identifier)7