Search in sources :

Example 76 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class FunctionTrigger method captureEvent.

/**
 * Used to observe all the {@link org.wso2.carbon.apimgt.core.models.Event} occurrences
 * in an {@link org.wso2.carbon.apimgt.core.api.APIMObservable} object and trigger corresponding function that is
 * mapped to the particular {@link org.wso2.carbon.apimgt.core.models.Event} occurred.
 * <p>
 * This is a specific implementation for
 * {@link org.wso2.carbon.apimgt.core.api.EventObserver#captureEvent(Event, String, ZonedDateTime, Map)} method,
 * provided by {@link org.wso2.carbon.apimgt.core.impl.FunctionTrigger} which implements
 * {@link org.wso2.carbon.apimgt.core.api.EventObserver} interface.
 * <p>
 * {@inheritDoc}
 *
 * @see org.wso2.carbon.apimgt.core.impl.EventLogger#captureEvent(Event, String, ZonedDateTime, Map)
 */
@Override
public void captureEvent(Event event, String username, ZonedDateTime eventTime, Map<String, String> metadata) {
    List<Function> functions = null;
    String jsonPayload = null;
    if (event == null) {
        throw new IllegalArgumentException("Event must not be null");
    }
    if (username == null) {
        throw new IllegalArgumentException("Username must not be null");
    }
    if (eventTime == null) {
        throw new IllegalArgumentException("Event_time must not be null");
    }
    if (metadata == null) {
        throw new IllegalArgumentException("Payload must not be null");
    }
    // Add general attributes to payload
    metadata.put(APIMgtConstants.FunctionsConstants.EVENT, event.getEventAsString());
    metadata.put(APIMgtConstants.FunctionsConstants.COMPONENT, event.getComponent().getComponentAsString());
    metadata.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
    metadata.put(APIMgtConstants.FunctionsConstants.EVENT_TIME, eventTime.toString());
    try {
        functions = functionDAO.getUserFunctionsForEvent(username, event);
        jsonPayload = new Gson().toJson(metadata);
    } catch (APIMgtDAOException e) {
        String message = "Error loading functions for event from DB: -event: " + event + " -Username: " + username;
        log.error(message, new APIManagementException("Problem invoking 'getUserFunctionsForEvent' method in " + "'FunctionDAO' ", e, ExceptionCodes.APIMGT_DAO_EXCEPTION));
    }
    if (functions != null && !functions.isEmpty()) {
        for (Function function : functions) {
            HttpResponse response = null;
            try {
                response = restCallUtil.postRequest(function.getEndpointURI(), null, null, Entity.json(jsonPayload), MediaType.APPLICATION_JSON_TYPE, Collections.EMPTY_MAP);
            } catch (APIManagementException e) {
                log.error("Failed to make http request: -function: " + function.getName() + " -endpoint URI: " + function.getEndpointURI() + " -event: " + event + " -Username: " + username, e);
            }
            if (response != null) {
                int responseStatusCode = response.getResponseCode();
                // Benefit of integer division used to ensure all possible success response codes covered
                if (responseStatusCode / 100 == 2) {
                    log.info("Function successfully invoked: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
                } else {
                    log.error("Problem invoking function: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
                }
            }
        }
    }
}
Also used : Function(org.wso2.carbon.apimgt.core.models.Function) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) Gson(com.google.gson.Gson) HttpResponse(org.wso2.carbon.apimgt.core.models.HttpResponse)

Example 77 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIPublisherImpl method addEndpoint.

/**
 * Add an endpoint
 *
 * @param endpoint Endpoint object.
 * @return UUID of the added endpoint.
 * @throws APIManagementException If failed to add endpoint.
 */
@Override
public String addEndpoint(Endpoint endpoint) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    Endpoint.Builder builder = new Endpoint.Builder(endpoint);
    builder.id(UUID.randomUUID().toString());
    builder.applicableLevel(APIMgtConstants.GLOBAL_ENDPOINT);
    Endpoint endpoint1 = builder.build();
    String key = endpoint.getName();
    if (key == null || StringUtils.isEmpty(key)) {
        log.error("Endpoint name not provided");
        throw new APIManagementException("Endpoint name is not provided", ExceptionCodes.ENDPOINT_ADD_FAILED);
    }
    Endpoint endpoint2 = getApiDAO().getEndpointByName(endpoint.getName());
    if (endpoint2 != null) {
        log.error(String.format("Endpoint already exist with name %s", key));
        throw new APIManagementException("Endpoint already exist with name " + key, ExceptionCodes.ENDPOINT_ALREADY_EXISTS);
    }
    gateway.addEndpoint(endpoint1);
    String config = getGatewaySourceGenerator().getEndpointConfigStringFromTemplate(endpoint1);
    endpoint1 = new Endpoint.Builder(endpoint1).config(config).build();
    try {
        getApiDAO().addEndpoint(endpoint1);
    } catch (APIMgtDAOException e) {
        String msg = "Failed to add Endpoint : " + endpoint.getName();
        log.error(msg, e);
        throw new APIManagementException(msg, e, e.getErrorHandler());
    }
    // update endpoint config in gateway
    return endpoint1.getId();
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway)

Example 78 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIPublisherImpl method deleteAPI.

/**
 * Delete an API
 *
 * @param identifier UUID of the API.
 * @throws APIManagementException if failed to remove the API
 */
@Override
public void deleteAPI(String identifier) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    try {
        if (getAPISubscriptionCountByAPI(identifier) == 0) {
            API api = getAPIbyUUID(identifier);
            // Checks whether the user has required permissions to delete the API
            verifyUserPermissionsToDeleteAPI(getUsername(), api);
            String apiWfStatus = api.getWorkflowStatus();
            API.APIBuilder apiBuilder = new API.APIBuilder(api);
            // Delete API in gateway
            gateway.deleteAPI(api);
            if (log.isDebugEnabled()) {
                log.debug("API : " + api.getName() + " has been successfully removed from the gateway");
            }
            if (!getApiDAO().isAPIVersionsExist(api.getName())) {
                Map<String, String> scopeMap = apiDefinitionFromSwagger20.getScopesFromSecurityDefinition(getApiSwaggerDefinition(identifier));
                for (String scope : scopeMap.keySet()) {
                    try {
                        getKeyManager().deleteScope(scope);
                    } catch (KeyManagementException e) {
                        // We ignore the error due to if scope get deleted from other end that will affect to delete
                        // api.
                        log.warn("Scope couldn't delete from Key Manager", e);
                    }
                }
            }
            getApiDAO().deleteAPI(identifier);
            // Deleting API specific endpoints
            if (api.getEndpoint() != null) {
                for (Map.Entry<String, Endpoint> entry : api.getEndpoint().entrySet()) {
                    Endpoint endpoint = entry.getValue();
                    if (APIMgtConstants.API_SPECIFIC_ENDPOINT.equals(endpoint.getApplicableLevel())) {
                        deleteEndpoint(endpoint.getId());
                    }
                }
            }
            getApiLifecycleManager().removeLifecycle(apiBuilder.getLifecycleInstanceId());
            APIUtils.logDebug("API with id " + identifier + " was deleted successfully.", log);
            if (APILCWorkflowStatus.PENDING.toString().equals(apiWfStatus)) {
                cleanupPendingTaskForAPIStateChange(identifier);
            }
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, api.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, api.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, api.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PROVIDER, api.getProvider());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, api.getDescription());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_DELETION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            throw new ApiDeleteFailureException("API with " + identifier + " already have subscriptions");
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while deleting the API with id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException e) {
        String errorMsg = "Error occurred while Disassociating the API with Lifecycle id " + identifier;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while deleting API with id - " + identifier + " from gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) ApiDeleteFailureException(org.wso2.carbon.apimgt.core.exception.ApiDeleteFailureException) HashMap(java.util.HashMap) KeyManagementException(org.wso2.carbon.apimgt.core.exception.KeyManagementException) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) API(org.wso2.carbon.apimgt.core.models.API) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) Map(java.util.Map) HashMap(java.util.HashMap)

Example 79 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class APIPublisherImpl method replaceGroupIdWithName.

/**
 * This method replaces the groupId field's value of the api permissions string to the role name before sending to
 * frontend
 *
 * @param permissionString - permissions string containing role ids in the groupId field
 * @return the permission string replacing the groupId field's value to role name
 * @throws ParseException         - if there is an error parsing the permission json
 * @throws APIManagementException - if there is an error getting the IdentityProvider instance
 */
private String replaceGroupIdWithName(String permissionString) throws ParseException, APIManagementException {
    JSONArray updatedPermissionArray = new JSONArray();
    JSONParser jsonParser = new JSONParser();
    JSONArray originalPermissionArray = (JSONArray) jsonParser.parse(permissionString);
    for (Object permissionObj : originalPermissionArray) {
        JSONObject jsonObject = (JSONObject) permissionObj;
        String groupId = (String) jsonObject.get(APIMgtConstants.Permission.GROUP_ID);
        try {
            String groupName = getIdentityProvider().getRoleName(groupId);
            JSONObject updatedPermissionJsonObj = new JSONObject();
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.GROUP_ID, groupName);
            updatedPermissionJsonObj.put(APIMgtConstants.Permission.PERMISSION, jsonObject.get(APIMgtConstants.Permission.PERMISSION));
            updatedPermissionArray.add(updatedPermissionJsonObj);
        } catch (IdentityProviderException e) {
            // lets the execution continue after logging the exception
            String errorMessage = "Error occurred while calling SCIM endpoint to retrieve role name of role " + "with Id " + groupId;
            log.warn(errorMessage, e);
        }
    }
    return updatedPermissionArray.toJSONString();
}
Also used : JSONObject(org.json.simple.JSONObject) JSONArray(org.json.simple.JSONArray) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Example 80 with Endpoint

use of org.wso2.carbon.governance.api.endpoints.dataobjects.Endpoint in project carbon-apimgt by wso2.

the class SubscriptionsApiServiceImplTestCase method testSubscriptionsPost.

@Test
public void testSubscriptionsPost() throws APIManagementException, NotFoundException {
    TestUtil.printTestMethodName();
    String applicationId = UUID.randomUUID().toString();
    String apiId = UUID.randomUUID().toString();
    String subsID1 = UUID.randomUUID().toString();
    String subsID2 = UUID.randomUUID().toString();
    SubscriptionsApiServiceImpl subscriptionsApiService = new SubscriptionsApiServiceImpl();
    APIStore apiStore = Mockito.mock(APIStoreImpl.class);
    PowerMockito.mockStatic(RestApiUtil.class);
    PowerMockito.when(RestApiUtil.getConsumer(USER)).thenReturn(apiStore);
    Request request = TestUtil.getRequest();
    PowerMockito.when(RestApiUtil.getLoggedInUsername(request)).thenReturn(USER);
    Application application = SampleTestObjectCreator.createDefaultApplication();
    Endpoint api1SandBoxEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("abcd").build();
    Endpoint api1ProdEndpointId = new Endpoint.Builder().id(UUID.randomUUID().toString()).applicableLevel(APIMgtConstants.API_SPECIFIC_ENDPOINT).name("cdef").build();
    API api = TestUtil.createApi("provider1", apiId, "testapi1", "1.0.0", "Test API 1 - version 1.0.0", TestUtil.createEndpointTypeToIdMap(api1SandBoxEndpointId, api1ProdEndpointId)).build();
    Mockito.when(apiStore.getApplicationByUuid(applicationId)).thenReturn(application);
    Mockito.when(apiStore.getAPIbyUUID(apiId)).thenReturn(api);
    SubscriptionDTO subscriptionDTO = SubscriptionMappingUtil.fromSubscriptionToDTO(SampleTestObjectCreator.createSubscription(subsID1));
    Response response = subscriptionsApiService.subscriptionsPost(subscriptionDTO, request);
    Assert.assertEquals(404, response.getStatus());
}
Also used : WorkflowResponse(org.wso2.carbon.apimgt.core.api.WorkflowResponse) GeneralWorkflowResponse(org.wso2.carbon.apimgt.core.workflow.GeneralWorkflowResponse) Response(javax.ws.rs.core.Response) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) Request(org.wso2.msf4j.Request) API(org.wso2.carbon.apimgt.core.models.API) Application(org.wso2.carbon.apimgt.core.models.Application) SubscriptionDTO(org.wso2.carbon.apimgt.rest.api.store.dto.SubscriptionDTO) APIStore(org.wso2.carbon.apimgt.core.api.APIStore) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Endpoint (org.wso2.carbon.apimgt.core.models.Endpoint)118 Test (org.testng.annotations.Test)114 HashMap (java.util.HashMap)90 IOException (java.io.IOException)84 ArrayList (java.util.ArrayList)77 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)70 Test (org.junit.Test)62 API (org.wso2.carbon.apimgt.core.models.API)58 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)50 APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)50 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)46 Map (java.util.Map)44 HashSet (java.util.HashSet)36 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)33 URL (java.net.URL)31 CharonException (org.wso2.charon3.core.exceptions.CharonException)31 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)30 OMElement (org.apache.axiom.om.OMElement)28 Response (javax.ws.rs.core.Response)27 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)27