Search in sources :

Example 16 with API

use of org.wso2.carbon.apimgt.core.models.API in project carbon-apimgt by wso2.

the class ApiDAOImpl method getAPISummary.

/**
 * {@inheritDoc}
 */
@Override
public API getAPISummary(String apiID) throws APIMgtDAOException {
    final String query = API_SUMMARY_SELECT + " WHERE UUID = ? AND API_TYPE_ID = " + "(SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)";
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setString(1, apiID);
        statement.setString(2, ApiType.STANDARD.toString());
        List<API> apiResults = constructAPISummaryList(connection, statement);
        if (apiResults.isEmpty()) {
            throw new APIMgtDAOException("API with ID " + apiID + " does not exist", ExceptionCodes.API_NOT_FOUND);
        }
        return apiResults.get(0);
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "getting API: " + apiID, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) CompositeAPI(org.wso2.carbon.apimgt.core.models.CompositeAPI) API(org.wso2.carbon.apimgt.core.models.API)

Example 17 with API

use of org.wso2.carbon.apimgt.core.models.API in project carbon-apimgt by wso2.

the class ApiDAOImpl method constructAPIFromResultSet.

private API constructAPIFromResultSet(Connection connection, PreparedStatement statement) throws SQLException, IOException, APIMgtDAOException {
    try (ResultSet rs = statement.executeQuery()) {
        while (rs.next()) {
            BusinessInformation businessInformation = new BusinessInformation();
            businessInformation.setTechnicalOwner(rs.getString("TECHNICAL_OWNER"));
            businessInformation.setTechnicalOwnerEmail(rs.getString("TECHNICAL_EMAIL"));
            businessInformation.setBusinessOwner(rs.getString("BUSINESS_OWNER"));
            businessInformation.setBusinessOwnerEmail(rs.getString("BUSINESS_EMAIL"));
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.setEnabled(rs.getBoolean("CORS_ENABLED"));
            String allowOrigins = rs.getString("CORS_ALLOW_ORIGINS");
            corsConfiguration.setAllowOrigins(DAOUtil.commaSeperatedStringToList(allowOrigins));
            corsConfiguration.setAllowCredentials(rs.getBoolean("CORS_ALLOW_CREDENTIALS"));
            String allowHeaders = rs.getString("CORS_ALLOW_HEADERS");
            corsConfiguration.setAllowHeaders(DAOUtil.commaSeperatedStringToList(allowHeaders));
            String allowMethods = rs.getString("CORS_ALLOW_METHODS");
            corsConfiguration.setAllowMethods(DAOUtil.commaSeperatedStringToList(allowMethods));
            String apiPrimaryKey = rs.getString("UUID");
            return new API.APIBuilder(rs.getString("PROVIDER"), rs.getString("NAME"), rs.getString("VERSION")).id(apiPrimaryKey).context(rs.getString("CONTEXT")).isDefaultVersion(rs.getBoolean("IS_DEFAULT_VERSION")).description(rs.getString("DESCRIPTION")).visibility(API.Visibility.valueOf(rs.getString("VISIBILITY"))).visibleRoles(getVisibleRoles(connection, apiPrimaryKey)).isResponseCachingEnabled(rs.getBoolean("IS_RESPONSE_CACHED")).cacheTimeout(rs.getInt("CACHE_TIMEOUT")).hasOwnGateway(rs.getBoolean("HAS_OWN_GATEWAY")).tags(getTags(connection, apiPrimaryKey)).labels(getLabelIdsForAPI(connection, apiPrimaryKey)).wsdlUri(ApiResourceDAO.getTextValueForCategory(connection, apiPrimaryKey, ResourceCategory.WSDL_TEXT)).transport(getTransports(connection, apiPrimaryKey)).endpoint(getEndPointsForApi(connection, apiPrimaryKey)).apiPermission(getPermissionsStringForApi(connection, apiPrimaryKey)).permissionMap(getPermissionMapForApi(connection, apiPrimaryKey)).businessInformation(businessInformation).lifecycleInstanceId(rs.getString("LIFECYCLE_INSTANCE_ID")).lifeCycleStatus(rs.getString("CURRENT_LC_STATUS")).corsConfiguration(corsConfiguration).createdBy(rs.getString("CREATED_BY")).updatedBy(rs.getString("UPDATED_BY")).createdTime(rs.getTimestamp("CREATED_TIME").toLocalDateTime()).lastUpdatedTime(rs.getTimestamp("LAST_UPDATED_TIME").toLocalDateTime()).uriTemplates(getUriTemplates(connection, apiPrimaryKey)).policies(getSubscripitonPolciesByAPIId(connection, apiPrimaryKey)).copiedFromApiId(rs.getString("COPIED_FROM_API")).workflowStatus(rs.getString("LC_WORKFLOW_STATUS")).securityScheme(rs.getInt("SECURITY_SCHEME")).apiPolicy(getApiPolicyByAPIId(connection, apiPrimaryKey)).threatProtectionPolicies(getThreatProtectionPolicies(connection, apiPrimaryKey)).build();
        }
    }
    return null;
}
Also used : BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) CorsConfiguration(org.wso2.carbon.apimgt.core.models.CorsConfiguration) ResultSet(java.sql.ResultSet)

Example 18 with API

use of org.wso2.carbon.apimgt.core.models.API in project carbon-apimgt by wso2.

the class ApiDAOImpl method getAPIsByStatus.

/**
 * @see ApiDAO#getAPIsByStatus(Set, List, List)
 */
@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<API> getAPIsByStatus(Set<String> roles, List<String> statuses, List<String> labels) throws APIMgtDAOException {
    // check for null at the beginning before constructing the query to retrieve APIs from database
    if (roles == null || statuses == null) {
        String errorMessage = "Role list or API status list should not be null to retrieve APIs.";
        log.error(errorMessage);
        throw new APIMgtDAOException(errorMessage);
    }
    // the below query will be used to retrieve the union of,
    // published/prototyped APIs (statuses) with public visibility and
    // published/prototyped APIs with restricted visibility where APIs are restricted based on roles of the user
    String labelQuery = null;
    if (labels.isEmpty()) {
        labelQuery = "SELECT LABEL_ID FROM  AM_LABELS WHERE TYPE_NAME='STORE'";
    } else {
        labelQuery = "SELECT LABEL_ID FROM  AM_LABELS WHERE NAME IN ( " + DAOUtil.getParameterString(labels.size()) + ") AND TYPE_NAME='STORE'";
    }
    final String query = "Select UUID, PROVIDER, NAME, CONTEXT, VERSION, DESCRIPTION, CURRENT_LC_STATUS, " + "LIFECYCLE_INSTANCE_ID, LC_WORKFLOW_STATUS, SECURITY_SCHEME  FROM (" + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.PUBLIC + "' " + "AND " + "CURRENT_LC_STATUS  IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + "API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)" + "UNION " + API_SUMMARY_SELECT + " WHERE " + "VISIBILITY = '" + API.Visibility.RESTRICTED + "' " + "AND " + "UUID IN (SELECT API_ID FROM AM_API_VISIBLE_ROLES WHERE ROLE IN " + "(" + DAOUtil.getParameterString(roles.size()) + ")) " + " AND CURRENT_LC_STATUS  IN (" + DAOUtil.getParameterString(statuses.size()) + ") AND " + " API_TYPE_ID = (SELECT TYPE_ID FROM AM_API_TYPES WHERE TYPE_NAME = ?)) A" + " JOIN AM_API_LABEL_MAPPING LM ON A.UUID=LM.API_ID WHERE LM.LABEL_ID IN (" + labelQuery + ")";
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        int i = 0;
        // put desired API status into the query (to get APIs with public visibility)
        for (String status : statuses) {
            statement.setString(++i, status);
        }
        statement.setString(++i, ApiType.STANDARD.toString());
        // put desired roles into the query
        for (String role : roles) {
            statement.setString(++i, role);
        }
        // put desired API status into the query (to get APIs with restricted visibility)
        for (String status : statuses) {
            statement.setString(++i, status);
        }
        statement.setString(++i, ApiType.STANDARD.toString());
        // Set the label names in the query
        for (String label : labels) {
            statement.setString(++i, label);
        }
        return constructAPISummaryList(connection, statement);
    } catch (SQLException e) {
        String errorMessage = "Error while retrieving API list in store.";
        throw new APIMgtDAOException(errorMessage, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 19 with API

use of org.wso2.carbon.apimgt.core.models.API in project carbon-apimgt by wso2.

the class ApiDAOImpl method searchAPIsByAttributeInStore.

/**
 * @see ApiDAO#searchAPIsByAttributeInStore(List roles, List labels, Map attributeMap, int offset, int limit)
 */
@Override
@SuppressFBWarnings("SQL_PREPARED_STATEMENT_GENERATED_FROM_NONCONSTANT_STRING")
public List<API> searchAPIsByAttributeInStore(List<String> roles, List<String> labels, Map<String, String> attributeMap, int offset, int limit) throws APIMgtDAOException {
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = sqlStatements.prepareAttributeSearchStatementForStore(connection, roles, labels, attributeMap, offset, limit)) {
        DatabaseMetaData md = connection.getMetaData();
        Iterator<Map.Entry<String, String>> entries = attributeMap.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry<String, String> entry = entries.next();
            String tableName = null, columnName = null;
            if (APIMgtConstants.TAG_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
                // if the search is related to tags, need to check NAME column in AM_TAGS table
                tableName = connection.getMetaData().getDriverName().contains("PostgreSQL") ? AM_TAGS_TABLE_NAME.toLowerCase(Locale.ENGLISH) : AM_TAGS_TABLE_NAME;
                columnName = connection.getMetaData().getDriverName().contains("PostgreSQL") ? APIMgtConstants.TAG_NAME_COLUMN.toLowerCase(Locale.ENGLISH) : APIMgtConstants.TAG_NAME_COLUMN.toUpperCase(Locale.ENGLISH);
            } else if (APIMgtConstants.SUBCONTEXT_SEARCH_TYPE_PREFIX.equalsIgnoreCase(entry.getKey())) {
                // if the search is related to subcontext, need to check URL_PATTERN column in
                // AM_API_OPERATION_MAPPING table
                tableName = connection.getMetaData().getDriverName().contains("PostgreSQL") ? AM_API_OPERATION_MAPPING_TABLE_NAME.toLowerCase(Locale.ENGLISH) : AM_API_OPERATION_MAPPING_TABLE_NAME;
                columnName = connection.getMetaData().getDriverName().contains("PostgreSQL") ? APIMgtConstants.URL_PATTERN_COLUMN.toLowerCase(Locale.ENGLISH) : APIMgtConstants.URL_PATTERN_COLUMN.toUpperCase(Locale.ENGLISH);
            } else {
                // if the search is related to any other attribute, need to check that attribute
                // in AM_API table
                tableName = connection.getMetaData().getDriverName().contains("PostgreSQL") ? AM_API_TABLE_NAME.toLowerCase(Locale.ENGLISH) : AM_API_TABLE_NAME;
                columnName = connection.getMetaData().getDriverName().contains("PostgreSQL") ? entry.getKey().toLowerCase(Locale.ENGLISH) : entry.getKey().toUpperCase(Locale.ENGLISH);
            }
            if (!checkTableColumnExists(md, tableName, columnName)) {
                throw new APIMgtDAOException("Attribute does not exist with name: " + entry.getKey(), ExceptionCodes.API_ATTRIBUTE_NOT_FOUND);
            }
        }
        return constructAPISummaryList(connection, statement);
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "searching APIs by attribute", e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) DatabaseMetaData(java.sql.DatabaseMetaData) Map(java.util.Map) HashMap(java.util.HashMap) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 20 with API

use of org.wso2.carbon.apimgt.core.models.API in project carbon-apimgt by wso2.

the class ApiDAOImpl method updateRating.

@Override
public void updateRating(String apiId, String ratingId, Rating rating) throws APIMgtDAOException {
    final String updateRatingQuery = "UPDATE AM_API_RATINGS SET RATING = ? , UPDATED_BY = ? , LAST_UPDATED_TIME = ?" + " WHERE API_ID = ? AND UUID = ?";
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(updateRatingQuery)) {
        try {
            connection.setAutoCommit(false);
            statement.setInt(1, rating.getRating());
            statement.setString(2, rating.getUsername());
            statement.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
            statement.setString(4, apiId);
            statement.setString(5, ratingId);
            statement.execute();
            connection.commit();
        } catch (SQLException e) {
            connection.rollback();
            String errorMessage = "updating Rating for API: " + apiId + ", Rating: " + rating.getUuid();
            throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + errorMessage, e);
        } finally {
            connection.setAutoCommit(DAOUtil.isAutoCommit());
        }
    } catch (SQLException e) {
        String errorMessage = "updating Rating for API: " + apiId + ", Rating: " + rating.getUuid();
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + errorMessage, e);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement)

Aggregations

API (org.wso2.carbon.apimgt.core.models.API)359 Test (org.testng.annotations.Test)320 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)253 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)179 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)154 CompositeAPI (org.wso2.carbon.apimgt.core.models.CompositeAPI)132 HashMap (java.util.HashMap)129 ArrayList (java.util.ArrayList)112 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)106 Test (org.junit.Test)83 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)83 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)82 SQLException (java.sql.SQLException)75 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)75 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)70 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)65 APIBuilder (org.wso2.carbon.apimgt.core.models.API.APIBuilder)61 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)60 Connection (java.sql.Connection)58 Response (javax.ws.rs.core.Response)58