Search in sources :

Example 76 with Subscription

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

the class WebsocketHandlerTestCase method testGraphQLWriteResponse.

@Test
public void testGraphQLWriteResponse() throws Exception {
    InboundMessageContext inboundMessageContext = new InboundMessageContext();
    inboundMessageContext.setElectedAPI(graphQLAPI);
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    msg = new TextWebSocketFrame("{\"id\":\"1\",\"type\":\"start\",\"payload\":{\"variables\":{}," + "\"extensions\":{},\"operationName\":null," + "\"query\":\"subscription {\\n  liftStatusChange {\\n    id\\n    name\\n    }\\n}\\n\"}}");
    VerbInfoDTO verbInfoDTO = new VerbInfoDTO();
    verbInfoDTO.setHttpVerb(GraphQLConstants.SubscriptionConstants.HTTP_METHOD_NAME);
    verbInfoDTO.setAuthType("OAUTH");
    GraphQLOperationDTO graphQLOperationDTO = new GraphQLOperationDTO(verbInfoDTO, "liftStatusChange");
    inboundMessageContext.addVerbInfoForGraphQLMsgId("1", graphQLOperationDTO);
    InboundProcessorResponseDTO responseDTO = new InboundProcessorResponseDTO();
    PowerMockito.when(InboundWebsocketProcessorUtil.validateScopes(Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.doThrottleForGraphQL(Mockito.anyInt(), Mockito.anyObject(), Mockito.anyObject(), Mockito.anyObject())).thenReturn(responseDTO);
    PowerMockito.when(InboundWebsocketProcessorUtil.authenticateToken(inboundMessageContext)).thenReturn(responseDTO);
    // happy path
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// No error has occurred context exists in data-holder map.
    channelIdString)));
    // close connection error
    responseDTO.setError(true);
    responseDTO.setCloseConnection(true);
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertFalse(InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(// Closing connection error has occurred
    channelIdString));
    // Websocket frame error has occurred
    InboundMessageContextDataHolder.getInstance().addInboundMessageContextForConnection(channelIdString, inboundMessageContext);
    responseDTO.setError(true);
    responseDTO.setCloseConnection(false);
    websocketHandler.write(channelHandlerContext, msg, channelPromise);
    Assert.assertTrue((InboundMessageContextDataHolder.getInstance().getInboundMessageContextMap().containsKey(channelIdString)));
}
Also used : GraphQLOperationDTO(org.wso2.carbon.apimgt.gateway.dto.GraphQLOperationDTO) VerbInfoDTO(org.wso2.carbon.apimgt.impl.dto.VerbInfoDTO) InboundProcessorResponseDTO(org.wso2.carbon.apimgt.gateway.inbound.websocket.InboundProcessorResponseDTO) TextWebSocketFrame(io.netty.handler.codec.http.websocketx.TextWebSocketFrame) InboundMessageContext(org.wso2.carbon.apimgt.gateway.inbound.InboundMessageContext) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Example 77 with Subscription

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

the class SubscriptionValidationDAO method getSubscriptionPolicyByNameForTenant.

/*
     * @param policyName : name of the subscription level throttling policy
     * @return {@link SubscriptionPolicy}
     * */
public SubscriptionPolicy getSubscriptionPolicyByNameForTenant(String policyName, String tenantDomain) {
    if (StringUtils.isNotEmpty(policyName) && StringUtils.isNotEmpty(tenantDomain)) {
        try (Connection conn = APIMgtDBUtil.getConnection();
            PreparedStatement ps = conn.prepareStatement(SubscriptionValidationSQLConstants.GET_SUBSCRIPTION_POLICY_SQL)) {
            int tenantId = 0;
            try {
                tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager().getTenantId(tenantDomain);
            } catch (UserStoreException e) {
                log.error("Error in loading ApplicationPolicy for tenantDomain : " + tenantDomain, e);
            }
            ps.setString(1, policyName);
            ps.setInt(2, tenantId);
            try (ResultSet resultSet = ps.executeQuery()) {
                if (resultSet.next()) {
                    SubscriptionPolicy subscriptionPolicy = new SubscriptionPolicy();
                    subscriptionPolicy.setId(resultSet.getInt(ThrottlePolicyConstants.COLUMN_POLICY_ID));
                    subscriptionPolicy.setName(resultSet.getString(ThrottlePolicyConstants.COLUMN_POLICY_NAME));
                    subscriptionPolicy.setQuotaType(resultSet.getString(ThrottlePolicyConstants.COLUMN_QUOTA_POLICY_TYPE));
                    subscriptionPolicy.setTenantId(resultSet.getInt(ThrottlePolicyConstants.COLUMN_TENANT_ID));
                    subscriptionPolicy.setTenantDomain(APIUtil.getTenantDomainFromTenantId(tenantId));
                    subscriptionPolicy.setRateLimitCount(resultSet.getInt(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_COUNT));
                    subscriptionPolicy.setRateLimitTimeUnit(resultSet.getString(ThrottlePolicyConstants.COLUMN_RATE_LIMIT_TIME_UNIT));
                    subscriptionPolicy.setStopOnQuotaReach(resultSet.getBoolean(ThrottlePolicyConstants.COLUMN_STOP_ON_QUOTA_REACH));
                    subscriptionPolicy.setGraphQLMaxDepth(resultSet.getInt(ThrottlePolicyConstants.COLUMN_MAX_DEPTH));
                    subscriptionPolicy.setGraphQLMaxComplexity(resultSet.getInt(ThrottlePolicyConstants.COLUMN_MAX_COMPLEXITY));
                    setCommonProperties(subscriptionPolicy, resultSet);
                    return subscriptionPolicy;
                }
            }
        } catch (SQLException e) {
            log.error("Error in retrieving Subscription policy by id : " + policyName + " for " + tenantDomain, e);
        }
    }
    return null;
}
Also used : SubscriptionPolicy(org.wso2.carbon.apimgt.api.model.subscription.SubscriptionPolicy) SQLException(java.sql.SQLException) Connection(java.sql.Connection) UserStoreException(org.wso2.carbon.user.api.UserStoreException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 78 with Subscription

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

the class WebhooksDAO method updateDeliveryStatus.

/*
     * This method can be used to update webhooks callback url delivery data to the database
     *
     * @param properties Subscription request properties
     * */
public void updateDeliveryStatus(String apiUUID, String appID, String tenantDomain, String callback, String topic, int state) throws APIManagementException {
    try (Connection conn = APIMgtDBUtil.getConnection()) {
        conn.setAutoCommit(false);
        try (PreparedStatement prepareStmt = conn.prepareStatement(SQLConstants.WebhooksSqlConstants.UPDATE_DELIVERY_STATE)) {
            Date currentTime = new Date();
            Timestamp updatedTimestamp = new Timestamp(currentTime.getTime());
            prepareStmt.setTimestamp(1, updatedTimestamp);
            prepareStmt.setInt(2, state);
            prepareStmt.setString(3, apiUUID);
            prepareStmt.setString(4, appID);
            prepareStmt.setString(5, tenantDomain);
            prepareStmt.setString(6, callback);
            prepareStmt.setString(7, topic);
            prepareStmt.executeUpdate();
            conn.commit();
        } catch (SQLException e) {
            handleConnectionRollBack(conn);
            throw new APIManagementException("Error while storing webhooks delivery status data for callback" + callback + " for the API " + apiUUID, e);
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while storing webhooks delivery status data for callback " + callback + " for the API " + apiUUID, e);
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) Date(java.util.Date)

Example 79 with Subscription

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

the class WebhooksDAO method getSubscriptionsList.

/*
     * This method can be used to add webhooks unsubscription request to the database
     *
     * @param properties
     * */
public List<Subscription> getSubscriptionsList(String tenantDomain) throws APIManagementException {
    List<Subscription> subscriptionsList = new ArrayList<>();
    String sqlQuery = SQLConstants.WebhooksSqlConstants.GET_ALL_VALID_SUBSCRIPTIONS;
    String postgreSQLQuery = SQLConstants.WebhooksSqlConstants.GET_ALL_VALID_SUBSCRIPTIONS_POSTGRE_SQL;
    try (Connection conn = APIMgtDBUtil.getConnection()) {
        if (conn.getMetaData().getDriverName().contains("PostgreSQL")) {
            sqlQuery = postgreSQLQuery;
        }
        try (PreparedStatement preparedStatement = conn.prepareStatement(sqlQuery)) {
            long currentTime = Instant.now().toEpochMilli();
            preparedStatement.setLong(1, currentTime);
            preparedStatement.setString(2, tenantDomain);
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    Subscription subscription = new Subscription();
                    subscription.setApiUuid(rs.getString(APIConstants.Webhooks.API_UUID_COLUMN));
                    subscription.setAppID(rs.getString(APIConstants.Webhooks.APPLICATION_ID_COLUMN));
                    subscription.setCallback(rs.getString(APIConstants.Webhooks.CALLBACK_COLUMN));
                    subscription.setTopic(rs.getString(APIConstants.Webhooks.TOPIC_COLUMN));
                    String secret = rs.getString(APIConstants.Webhooks.SECRET_COLUMN);
                    String decryptedSecret = null;
                    if (!StringUtils.isEmpty(secret)) {
                        decryptedSecret = decryptSecret(rs.getString(APIConstants.Webhooks.SECRET_COLUMN));
                    }
                    subscription.setSecret(decryptedSecret);
                    subscription.setExpiryTime(rs.getLong(APIConstants.Webhooks.EXPIRY_AT_COLUMN));
                    subscription.setApiContext(rs.getString(APIConstants.Webhooks.API_CONTEXT_COLUMN));
                    subscription.setApiVersion(rs.getString(APIConstants.Webhooks.API_VERSION_COLUMN));
                    subscription.setTenantId(rs.getInt(APIConstants.Webhooks.TENANT_ID_COLUMN));
                    subscription.setTier(rs.getString(APIConstants.Webhooks.SUB_TIER_COLUMN));
                    subscription.setApiTier(rs.getString(APIConstants.Webhooks.API_TIER_COLUMN));
                    subscription.setApplicationTier(rs.getString(APIConstants.Webhooks.APPLICATION_TIER_COLUMN));
                    subscription.setSubscriberName(rs.getString(APIConstants.Webhooks.SUBSCRIBER_COLUMN));
                    subscription.setTenantDomain(tenantDomain);
                    subscriptionsList.add(subscription);
                }
            }
        } catch (SQLException | CryptoException e) {
            throw new APIManagementException("Error while retrieving webhooks subscription request", e);
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while retrieving webhooks subscription request", e);
    }
    return subscriptionsList;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Subscription(org.wso2.carbon.apimgt.api.model.webhooks.Subscription) CryptoException(org.wso2.carbon.core.util.CryptoException)

Example 80 with Subscription

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

the class WebhooksDAO method addSubscription.

/*
     * This method can be used to insert webhooks subscriptions to the database
     *
     * @param properties Subscription request properties
     * */
public boolean addSubscription(Properties properties) throws APIManagementException {
    try (Connection conn = APIMgtDBUtil.getConnection()) {
        try {
            conn.setAutoCommit(false);
            int id = findSubscription(conn, properties);
            if (id == 0) {
                int throttleLimit = getAllowedConnectionsCount(conn, properties);
                int currentLimit = getCurrentConnectionsCount(conn, properties);
                if (currentLimit >= throttleLimit) {
                    return false;
                }
                addSubscription(conn, properties);
            } else {
                updateSubscription(conn, properties, id);
            }
            conn.commit();
        } catch (SQLException e) {
            handleConnectionRollBack(conn);
            throw new APIManagementException("Error while storing webhooks unsubscription request for callback" + properties.getProperty(APIConstants.Webhooks.CALLBACK) + " for the API " + properties.getProperty(APIConstants.Webhooks.API_UUID), e);
        }
    } catch (SQLException e) {
        throw new APIManagementException("Error while storing subscription with callback " + properties.getProperty(APIConstants.Webhooks.CALLBACK) + " for the API " + properties.getProperty(APIConstants.Webhooks.API_UUID), e);
    }
    return true;
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) SQLException(java.sql.SQLException) Connection(java.sql.Connection)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)79 ArrayList (java.util.ArrayList)69 Test (org.testng.annotations.Test)58 Subscription (org.wso2.carbon.apimgt.core.models.Subscription)58 Test (org.junit.Test)56 SQLException (java.sql.SQLException)55 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)51 Connection (java.sql.Connection)49 PreparedStatement (java.sql.PreparedStatement)48 ResultSet (java.sql.ResultSet)39 SubscriptionPolicy (org.wso2.carbon.apimgt.core.models.policy.SubscriptionPolicy)37 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)35 APISubscriptionDAO (org.wso2.carbon.apimgt.core.dao.APISubscriptionDAO)34 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)34 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)31 Application (org.wso2.carbon.apimgt.core.models.Application)30 API (org.wso2.carbon.apimgt.core.models.API)28 Response (javax.ws.rs.core.Response)24 Application (org.wso2.carbon.apimgt.api.model.Application)22 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)22