Search in sources :

Example 26 with APIIdentifier

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

the class ApiMgtDAO method deleteAPI.

public void deleteAPI(String uuid) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    int id;
    String deleteLCEventQuery = SQLConstants.REMOVE_FROM_API_LIFECYCLE_SQL;
    String deleteAuditAPIMapping = SQLConstants.REMOVE_SECURITY_AUDIT_MAP_SQL;
    String deleteCommentQuery = SQLConstants.REMOVE_FROM_API_COMMENT_SQL;
    String deleteRatingsQuery = SQLConstants.REMOVE_FROM_API_RATING_SQL;
    String deleteSubscriptionQuery = SQLConstants.REMOVE_FROM_API_SUBSCRIPTION_SQL;
    String deleteExternalAPIStoresQuery = SQLConstants.REMOVE_FROM_EXTERNAL_STORES_SQL;
    String deleteAPIQuery = SQLConstants.REMOVE_FROM_API_SQL_BY_UUID;
    String deleteResourceScopeMappingsQuery = SQLConstants.REMOVE_RESOURCE_SCOPE_URL_MAPPING_SQL;
    String deleteURLTemplateQuery = SQLConstants.REMOVE_FROM_API_URL_MAPPINGS_SQL;
    String deleteGraphqlComplexityQuery = SQLConstants.REMOVE_FROM_GRAPHQL_COMPLEXITY_SQL;
    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        APIIdentifier identifier = ApiMgtDAO.getInstance().getAPIIdentifierFromUUID(uuid);
        id = getAPIID(uuid, connection);
        prepStmt = connection.prepareStatement(deleteAuditAPIMapping);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        prepStmt = connection.prepareStatement(deleteGraphqlComplexityQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        prepStmt = connection.prepareStatement(deleteSubscriptionQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        // Delete all comments associated with given API
        deleteAPIComments(id, uuid, connection);
        prepStmt = connection.prepareStatement(deleteRatingsQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        prepStmt = connection.prepareStatement(deleteLCEventQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        // Delete all external APIStore details associated with a given API
        prepStmt = connection.prepareStatement(deleteExternalAPIStoresQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        // Delete resource scope mappings of the API
        prepStmt = connection.prepareStatement(deleteResourceScopeMappingsQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        // Delete URL Templates (delete the resource scope mappings on delete cascade)
        prepStmt = connection.prepareStatement(deleteURLTemplateQuery);
        prepStmt.setInt(1, id);
        prepStmt.execute();
        deleteAllAPISpecificOperationPoliciesByAPIUUID(connection, uuid, null);
        prepStmt = connection.prepareStatement(deleteAPIQuery);
        prepStmt.setString(1, uuid);
        prepStmt.execute();
        // If exception occurs at execute, this statement will close in finally else here
        prepStmt.close();
        String curDefaultVersion = getDefaultVersion(identifier);
        String pubDefaultVersion = getPublishedDefaultVersion(identifier);
        if (identifier.getVersion().equals(curDefaultVersion)) {
            ArrayList<APIIdentifier> apiIdList = new ArrayList<APIIdentifier>() {

                {
                    add(identifier);
                }
            };
            removeAPIFromDefaultVersion(apiIdList, connection);
        } else if (identifier.getVersion().equals(pubDefaultVersion)) {
            setPublishedDefVersion(identifier, connection, null);
        }
        connection.commit();
    } catch (SQLException e) {
        handleException("Error while removing the API with UUID: " + uuid + " from the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 27 with APIIdentifier

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

the class ApiMgtDAO method setDefaultVersion.

public void setDefaultVersion(API api) throws APIManagementException {
    APIIdentifier apiId = api.getId();
    try (Connection connection = APIMgtDBUtil.getConnection()) {
        try (PreparedStatement preparedStatement = connection.prepareStatement(SQLConstants.RETRIEVE_DEFAULT_VERSION)) {
            preparedStatement.setString(1, apiId.getApiName());
            preparedStatement.setString(2, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
                if (resultSet.next()) {
                    api.setDefaultVersion(apiId.getVersion().equals(resultSet.getString("DEFAULT_API_VERSION")));
                    api.setAsPublishedDefaultVersion(apiId.getVersion().equals(resultSet.getString("PUBLISHED_DEFAULT_API_VERSION")));
                }
            }
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while retrieving apimgt connection", e, ExceptionCodes.INTERNAL_ERROR);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) PreparedStatement(java.sql.PreparedStatement)

Example 28 with APIIdentifier

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

the class ApiMgtDAO method removeAPIFromDefaultVersion.

/**
 * Sets/removes default api entry such that api will not represent as default api further.
 * If the api's version is the same as the published version, then the whole entry will be removed.
 * Otherwise only the default version attribute is set to null.
 *
 * @param apiIdList
 * @param connection
 * @return
 * @throws APIManagementException
 */
private void removeAPIFromDefaultVersion(List<APIIdentifier> apiIdList, Connection connection) throws APIManagementException {
    // TODO: check list empty
    try (PreparedStatement prepStmtDefVersionDelete = connection.prepareStatement(SQLConstants.REMOVE_API_DEFAULT_VERSION_SQL)) {
        for (APIIdentifier apiId : apiIdList) {
            prepStmtDefVersionDelete.setString(1, apiId.getApiName());
            prepStmtDefVersionDelete.setString(2, APIUtil.replaceEmailDomainBack(apiId.getProviderName()));
            prepStmtDefVersionDelete.addBatch();
        }
        prepStmtDefVersionDelete.executeBatch();
    } catch (SQLException e) {
        try {
            connection.rollback();
        } catch (SQLException e1) {
            log.error("Error while rolling back the failed operation", e1);
        }
        handleException("Error while deleting the API default version entry: " + apiIdList.stream().map(APIIdentifier::getApiName).collect(Collectors.joining(",")) + " from the " + "database", e);
    }
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier)

Example 29 with APIIdentifier

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

the class ApiMgtDAO method getAllAPIUsageByProvider.

/**
 * @param providerName Name of the provider
 * @return UserApplicationAPIUsage of given provider
 * @throws org.wso2.carbon.apimgt.api.APIManagementException if failed to get
 *                                                           UserApplicationAPIUsage for given provider
 */
public UserApplicationAPIUsage[] getAllAPIUsageByProvider(String providerName) throws APIManagementException {
    Connection connection = null;
    PreparedStatement ps = null;
    ResultSet result = null;
    try {
        String sqlQuery = SQLConstants.GET_APP_API_USAGE_BY_PROVIDER_SQL;
        connection = APIMgtDBUtil.getConnection();
        ps = connection.prepareStatement(sqlQuery);
        ps.setString(1, APIUtil.replaceEmailDomainBack(providerName));
        result = ps.executeQuery();
        Map<String, UserApplicationAPIUsage> userApplicationUsages = new TreeMap<String, UserApplicationAPIUsage>();
        while (result.next()) {
            int subId = result.getInt("SUBSCRIPTION_ID");
            String userId = result.getString("USER_ID");
            String application = result.getString("APPNAME");
            int appId = result.getInt("APPLICATION_ID");
            String subStatus = result.getString("SUB_STATUS");
            String subsCreateState = result.getString("SUBS_CREATE_STATE");
            String key = userId + "::" + application;
            UserApplicationAPIUsage usage = userApplicationUsages.get(key);
            if (usage == null) {
                usage = new UserApplicationAPIUsage();
                usage.setUserId(userId);
                usage.setApplicationName(application);
                usage.setAppId(appId);
                userApplicationUsages.put(key, usage);
            }
            APIIdentifier apiId = new APIIdentifier(result.getString("API_PROVIDER"), result.getString("API_NAME"), result.getString("API_VERSION"));
            SubscribedAPI apiSubscription = new SubscribedAPI(new Subscriber(userId), apiId);
            apiSubscription.setSubStatus(subStatus);
            apiSubscription.setSubCreatedStatus(subsCreateState);
            apiSubscription.setUUID(result.getString("SUB_UUID"));
            apiSubscription.setTier(new Tier(result.getString("SUB_TIER_ID")));
            Application applicationObj = new Application(result.getString("APP_UUID"));
            apiSubscription.setApplication(applicationObj);
            usage.addApiSubscriptions(apiSubscription);
        }
        return userApplicationUsages.values().toArray(new UserApplicationAPIUsage[userApplicationUsages.size()]);
    } catch (SQLException e) {
        handleException("Failed to find API Usage for :" + providerName, e);
        return null;
    } finally {
        APIMgtDBUtil.closeAllConnections(ps, connection, result);
    }
}
Also used : UserApplicationAPIUsage(org.wso2.carbon.apimgt.api.dto.UserApplicationAPIUsage) Tier(org.wso2.carbon.apimgt.api.model.Tier) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) TreeMap(java.util.TreeMap) Subscriber(org.wso2.carbon.apimgt.api.model.Subscriber) 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 30 with APIIdentifier

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

the class ApiMgtDAO method updateAPI.

public void updateAPI(API api, String username) throws APIManagementException {
    Connection connection = null;
    PreparedStatement prepStmt = null;
    String previousDefaultVersion = getDefaultVersion(api.getId());
    String query = SQLConstants.UPDATE_API_SQL;
    try {
        connection = APIMgtDBUtil.getConnection();
        connection.setAutoCommit(false);
        // Header change check not required here as we update API level throttling tier
        // from same call.
        // TODO review and run tier update as separate query if need.
        prepStmt = connection.prepareStatement(query);
        prepStmt.setString(1, api.getContext());
        String contextTemplate = api.getContextTemplate();
        // context.
        if (contextTemplate.endsWith("/" + APIConstants.VERSION_PLACEHOLDER)) {
            // Remove the {version} part from the context template.
            contextTemplate = contextTemplate.split(Pattern.quote("/" + APIConstants.VERSION_PLACEHOLDER))[0];
        }
        prepStmt.setString(2, api.getId().getApiName());
        prepStmt.setString(3, contextTemplate);
        prepStmt.setString(4, username);
        prepStmt.setTimestamp(5, new Timestamp(System.currentTimeMillis()));
        prepStmt.setString(6, api.getApiLevelPolicy());
        prepStmt.setString(7, api.getType());
        prepStmt.setString(8, api.getGatewayVendor());
        prepStmt.setString(9, api.getUuid());
        prepStmt.execute();
        if (api.isDefaultVersion() ^ api.getId().getVersion().equals(previousDefaultVersion)) {
            // If the api is selected as default version, it is added/replaced into AM_API_DEFAULT_VERSION table
            if (api.isDefaultVersion()) {
                addUpdateAPIAsDefaultVersion(api, connection);
            } else {
                // tick is removed
                ArrayList<APIIdentifier> apiIdList = new ArrayList<APIIdentifier>() {

                    {
                        add(api.getId());
                    }
                };
                removeAPIFromDefaultVersion(apiIdList, connection);
            }
        }
        String serviceKey = api.getServiceInfo("key");
        if (StringUtils.isNotEmpty(serviceKey)) {
            int apiId = getAPIID(api.getUuid());
            int tenantID = APIUtil.getTenantId(username);
            updateAPIServiceMapping(apiId, serviceKey, api.getServiceInfo("md5"), tenantID, connection);
        }
        connection.commit();
    } catch (SQLException e) {
        try {
            if (connection != null) {
                connection.rollback();
            }
        } catch (SQLException ex) {
            // Rollback failed. Exception will be thrown later for upper exception
            log.error("Failed to rollback the update API: " + api.getId(), ex);
        }
        handleException("Error while updating the API: " + api.getId() + " in the database", e);
    } finally {
        APIMgtDBUtil.closeAllConnections(prepStmt, connection, null);
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) APIIdentifier(org.wso2.carbon.apimgt.api.model.APIIdentifier) Timestamp(java.sql.Timestamp)

Aggregations

APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)305 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)171 API (org.wso2.carbon.apimgt.api.model.API)160 Test (org.junit.Test)155 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)119 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)105 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)85 Resource (org.wso2.carbon.registry.core.Resource)79 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)69 ArrayList (java.util.ArrayList)68 ImportExportAPI (org.wso2.carbon.apimgt.impl.importexport.ImportExportAPI)56 GenericArtifact (org.wso2.carbon.governance.api.generic.dataobjects.GenericArtifact)48 ServiceReferenceHolder (org.wso2.carbon.apimgt.impl.internal.ServiceReferenceHolder)46 RegistryService (org.wso2.carbon.registry.core.service.RegistryService)46 PublisherAPI (org.wso2.carbon.apimgt.persistence.dto.PublisherAPI)44 HashSet (java.util.HashSet)41 HashMap (java.util.HashMap)40 IOException (java.io.IOException)37 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)37 JSONObject (org.json.simple.JSONObject)36