Search in sources :

Example 71 with Endpoint

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

the class APIPublisherImpl method updateAPI.

/**
 * Updates design and implementation of an existing API. This method must not be used to change API status.
 * Implementations should throw an exceptions when such attempts are made. All life cycle state changes
 * should be carried out using the changeAPIStatus method of this interface.
 *
 * @param apiBuilder {@code org.wso2.carbon.apimgt.core.models.API.APIBuilder} model object
 * @throws APIManagementException if failed to update API
 */
@Override
public void updateAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    apiBuilder.updatedBy(getUsername());
    try {
        API originalAPI = getAPIbyUUID(apiBuilder.getId());
        if (originalAPI != null) {
            // Checks whether the logged in user has the "UPDATE" permission for the API
            verifyUserPermissionsToUpdateAPI(getUsername(), originalAPI);
            apiBuilder.createdTime(originalAPI.getCreatedTime());
            // workflow status is an internal property and shouldn't be allowed to update externally
            apiBuilder.workflowStatus(originalAPI.getWorkflowStatus());
            if ((originalAPI.getName().equals(apiBuilder.getName())) && (originalAPI.getVersion().equals(apiBuilder.getVersion())) && (originalAPI.getProvider().equals(apiBuilder.getProvider())) && originalAPI.getLifeCycleStatus().equalsIgnoreCase(apiBuilder.getLifeCycleStatus())) {
                if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                    apiBuilder.apiPermission(replaceGroupNamesWithId(apiBuilder.getApiPermission()));
                    Map<String, Integer> roleNamePermissionList;
                    roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                    apiBuilder.permissionMap(roleNamePermissionList);
                }
                Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
                validateEndpoints(apiEndpointMap, true);
                validateLabels(apiBuilder.getLabels(), originalAPI.hasOwnGateway());
                createUriTemplateList(apiBuilder, true);
                validateApiPolicy(apiBuilder.getApiPolicy());
                validateSubscriptionPolicies(apiBuilder);
                String updatedSwagger = apiDefinitionFromSwagger20.generateMergedResourceDefinition(getApiDAO().getApiSwaggerDefinition(apiBuilder.getId()), apiBuilder.build());
                String gatewayConfig = getApiGatewayConfig(apiBuilder.getId());
                GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
                APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
                gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
                String updatedGatewayConfig = gatewaySourceGenerator.getGatewayConfigFromSwagger(gatewayConfig, updatedSwagger);
                API api = apiBuilder.build();
                // Add API to gateway
                gateway.updateAPI(api);
                if (log.isDebugEnabled()) {
                    log.debug("API : " + apiBuilder.getName() + " has been successfully updated in gateway");
                }
                if (originalAPI.getContext() != null && !originalAPI.getContext().equals(apiBuilder.getContext())) {
                    if (!checkIfAPIContextExists(api.getContext())) {
                        // if the API has public visibility, update the API without any role checking
                        if (API.Visibility.PUBLIC == api.getVisibility()) {
                            getApiDAO().updateAPI(api.getId(), api);
                        } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                            // get all the roles in the system
                            Set<String> availableRoles = APIUtils.getAllAvailableRoles();
                            // get the roles needed to be associated with the API
                            Set<String> apiRoleList = api.getVisibleRoles();
                            // if the API has role based visibility, update the API with role checking
                            if (APIUtils.checkAllowedRoles(availableRoles, apiRoleList)) {
                                getApiDAO().updateAPI(api.getId(), api);
                            }
                        }
                        getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                        getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                    } else {
                        throw new APIManagementException("Context already Exist", ExceptionCodes.API_ALREADY_EXISTS);
                    }
                } else {
                    // if the API has public visibility, update the API without any role checking
                    if (API.Visibility.PUBLIC == api.getVisibility()) {
                        getApiDAO().updateAPI(api.getId(), api);
                    } else if (API.Visibility.RESTRICTED == api.getVisibility()) {
                        // get all the roles in the system
                        Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                        // get the roles needed to be associated with the API
                        Set<String> apiRoleList = api.getVisibleRoles();
                        // if the API has role based visibility, update the API with role checking
                        if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                            getApiDAO().updateAPI(api.getId(), api);
                        }
                    }
                    getApiDAO().updateApiDefinition(api.getId(), updatedSwagger, api.getUpdatedBy());
                    getApiDAO().updateGatewayConfig(api.getId(), updatedGatewayConfig, api.getUpdatedBy());
                }
                if (log.isDebugEnabled()) {
                    log.debug("API " + api.getName() + "-" + api.getVersion() + " was updated successfully.");
                    // '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_DESCRIPTION, api.getDescription());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, api.getContext());
                    eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, api.getLifeCycleStatus());
                    // This will notify all the EventObservers(Asynchronous)
                    ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_UPDATE, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
                    ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
                }
            } else {
                APIUtils.verifyValidityOfApiUpdate(apiBuilder, originalAPI);
            }
        } else {
            log.error("Couldn't found API with ID " + apiBuilder.getId());
            throw new APIManagementException("Couldn't found API with ID " + apiBuilder.getId(), ExceptionCodes.API_NOT_FOUND);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while updating the API - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (ParseException e) {
        String errorMsg = "Error occurred while parsing the permission json from swagger - " + apiBuilder.getName();
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.SWAGGER_PARSE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while updating API - " + apiBuilder.getName() + " in gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) 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) ParseException(org.json.simple.parser.ParseException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Example 72 with Endpoint

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

the class DefaultIdentityProviderImpl method getEmailOfUser.

@Override
public String getEmailOfUser(String userId) throws IdentityProviderException {
    Response userResponse = scimServiceStub.getUser(userId);
    String userEmail;
    if (userResponse == null) {
        String errorMessage = "Error occurred while retrieving Id of user " + userId + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    if (userResponse.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        String responseBody = userResponse.body().toString();
        JsonParser parser = new JsonParser();
        JsonObject parsedResponseBody = (JsonObject) parser.parse(responseBody);
        userEmail = parsedResponseBody.get("emails").toString().replaceAll("[\\[\\]\"]", "");
        log.debug("Email {} of user {} is successfully retrieved from SCIM endpoint.", userEmail, parsedResponseBody.get(USERNAME).getAsString());
    } else {
        String errorMessage = "Error occurred while retrieving Id of user " + userId + ". Error : " + getErrorMessage(userResponse);
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return userEmail;
}
Also used : Response(feign.Response) JsonObject(com.google.gson.JsonObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) JsonParser(com.google.gson.JsonParser)

Example 73 with Endpoint

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

the class DefaultIdentityProviderImpl method getRoleNamesOfUser.

@Override
public List<String> getRoleNamesOfUser(String userId) throws IdentityProviderException {
    List<String> roleNames = new ArrayList<>();
    Response response = scimServiceStub.getUser(userId);
    if (response == null) {
        String errorMessage = "Error occurred while retrieving user with Id " + userId + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    try {
        if (response.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
            SCIMUser scimUser = (SCIMUser) new GsonDecoder().decode(response, SCIMUser.class);
            if (scimUser != null) {
                List<SCIMUser.SCIMUserGroups> roles = scimUser.getGroups();
                if (roles != null) {
                    roles.forEach(role -> roleNames.add(role.getDisplay()));
                    String message = "Role names of user " + scimUser.getName() + " are successfully retrieved as " + StringUtils.join(roleNames, ", ") + ".";
                    if (log.isDebugEnabled()) {
                        log.debug(message);
                    }
                }
            } else {
                String errorMessage = "Error occurred while retrieving user with user Id " + userId + " from SCIM endpoint. " + "Response body is null or empty.";
                log.error(errorMessage);
                throw new IdentityProviderException("Error occurred while retrieving user with user Id " + userId + " from SCIM endpoint. " + "Response body is null or empty.", ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
            }
        } else {
            String errorMessage = "Error occurred while retrieving role names of user with Id " + userId + ". Error : " + getErrorMessage(response);
            log.error(errorMessage);
            throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
        }
    } catch (IOException e) {
        String errorMessage = "Error occurred while parsing response from SCIM endpoint.";
        log.error(errorMessage);
        throw new IdentityProviderException("Error occurred while parsing response from SCIM endpoint for ", e, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return roleNames;
}
Also used : Response(feign.Response) SCIMUser(org.wso2.carbon.apimgt.core.auth.dto.SCIMUser) ArrayList(java.util.ArrayList) GsonDecoder(feign.gson.GsonDecoder) IOException(java.io.IOException) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException)

Example 74 with Endpoint

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

the class DefaultIdentityProviderImpl method getIdOfUser.

@Override
public String getIdOfUser(String userName) throws IdentityProviderException {
    // should not user id outside this domain and should not log that id.
    try {
        userName = userNameMapper.getLoggedInUserIDFromPseudoName(userName);
    } catch (APIManagementException e) {
        throw new IdentityProviderException(e.getMessage(), ExceptionCodes.USER_MAPPING_RETRIEVAL_FAILED);
    }
    Response userResponse = scimServiceStub.searchUsers(FILTER_PREFIX_USER + userName);
    String userId;
    if (userResponse == null) {
        String errorMessage = "Error occurred while retrieving Id of user " + userName + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    if (userResponse.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        String responseBody = userResponse.body().toString();
        JsonParser parser = new JsonParser();
        JsonObject parsedResponseBody = (JsonObject) parser.parse(responseBody);
        JsonArray user = (JsonArray) parsedResponseBody.get(RESOURCES);
        JsonObject scimUser = (JsonObject) user.get(0);
        userId = scimUser.get(ID).getAsString();
        String message = "Id " + userId + " of user " + scimUser.get(USERNAME).getAsString() + " is successfully retrieved from SCIM endpoint.";
        if (log.isDebugEnabled()) {
            log.debug(message);
        }
    } else {
        String errorMessage = "Error occurred while retrieving Id of user " + userName + ". Error : " + getErrorMessage(userResponse);
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return userId;
}
Also used : Response(feign.Response) JsonArray(com.google.gson.JsonArray) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) JsonObject(com.google.gson.JsonObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) JsonParser(com.google.gson.JsonParser)

Example 75 with Endpoint

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

the class DefaultIdentityProviderImpl method getRoleId.

@Override
public String getRoleId(String roleName) throws IdentityProviderException {
    Response roleResponse = scimServiceStub.searchGroups(FILTER_PREFIX_ROLE + roleName);
    String roleId;
    if (roleResponse == null) {
        String errorMessage = "Error occurred while retrieving Id of role " + roleName + ". Error : Response is null.";
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    if (roleResponse.status() == APIMgtConstants.HTTPStatusCodes.SC_200_OK) {
        String responseBody = roleResponse.body().toString();
        JsonParser parser = new JsonParser();
        JsonObject parsedResponseBody = (JsonObject) parser.parse(responseBody);
        JsonArray role = (JsonArray) parsedResponseBody.get(RESOURCES);
        JsonObject scimGroup = (JsonObject) role.get(0);
        roleId = scimGroup.get(ID).getAsString();
        String message = "Id " + roleId + " of role " + scimGroup.get(GROUPNAME).getAsString() + " is successfully retrieved from SCIM endpoint.";
        if (log.isDebugEnabled()) {
            log.debug(message);
        }
    } else {
        String errorMessage = "Error occurred while retrieving Id of role " + roleName + ". Error : " + getErrorMessage(roleResponse);
        log.error(errorMessage);
        throw new IdentityProviderException(errorMessage, ExceptionCodes.RESOURCE_RETRIEVAL_FAILED);
    }
    return roleId;
}
Also used : Response(feign.Response) JsonArray(com.google.gson.JsonArray) JsonObject(com.google.gson.JsonObject) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) JsonParser(com.google.gson.JsonParser)

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