Search in sources :

Example 1 with APIManagementException

use of org.wso2.carbon.apimgt.core.exception.APIManagementException in project carbon-apimgt by wso2.

the class APIPublisherImpl method removePendingLifecycleWorkflowTaskForAPI.

/**
 * {@inheritDoc}
 */
@Override
public void removePendingLifecycleWorkflowTaskForAPI(String apiId) throws APIManagementException {
    try {
        API api = getApiDAO().getAPI(apiId);
        if (APILCWorkflowStatus.PENDING.toString().equals(api.getWorkflowStatus())) {
            // change the state back
            getApiDAO().updateAPIWorkflowStatus(apiId, APILCWorkflowStatus.APPROVED);
            // call executor's cleanup task
            cleanupPendingTaskForAPIStateChange(apiId);
        } else {
            String msg = "API does not have a pending lifecycle state change.";
            log.error(msg);
            throw new APIManagementException(msg, ExceptionCodes.WORKFLOW_NO_PENDING_TASK);
        }
    } catch (APIMgtDAOException e) {
        String msg = "Error occurred while changing api lifecycle workflow status";
        log.error(msg, e);
        throw new APIManagementException(msg, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API)

Example 2 with APIManagementException

use of org.wso2.carbon.apimgt.core.exception.APIManagementException in project carbon-apimgt by wso2.

the class APIPublisherImpl method updateEndpoint.

/**
 * Update and endpoint
 *
 * @param endpoint Endpoint object.
 * @throws APIManagementException If failed to update endpoint.
 */
@Override
public void updateEndpoint(Endpoint endpoint) throws APIManagementException {
    APIGateway gateway = getApiGateway();
    gateway.updateEndpoint(endpoint);
    String config = getGatewaySourceGenerator().getEndpointConfigStringFromTemplate(endpoint);
    Endpoint updatedEndpoint = new Endpoint.Builder(endpoint).config(config).build();
    try {
        getApiDAO().updateEndpoint(updatedEndpoint);
    } catch (APIMgtDAOException e) {
        String msg = "Failed to update Endpoint : " + endpoint.getName();
        log.error(msg, e);
        throw new APIManagementException(msg, e, e.getErrorHandler());
    }
// update endpoint config in gateway
}
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 3 with APIManagementException

use of org.wso2.carbon.apimgt.core.exception.APIManagementException in project carbon-apimgt by wso2.

the class APIPublisherImpl method searchAPIs.

/**
 * @param limit  Limit
 * @param offset Offset
 * @param query  Search query
 * @return List of APIS.
 * @throws APIManagementException If failed to formatApiSearch APIs.
 */
@Override
public List<API> searchAPIs(Integer limit, Integer offset, String query) throws APIManagementException {
    List<API> apiResults;
    String user = getUsername();
    Set<String> roles = new HashSet<>();
    try {
        // TODO: Need to validate users roles against results returned
        if (!"admin".equals(user)) {
            // Whenever call identity provider should convert pseudo name to actual name
            String userId = getIdentityProvider().getIdOfUser(user);
            roles = new HashSet<>(getIdentityProvider().getRoleIdsOfUser(userId));
        }
        if (query != null && !query.isEmpty()) {
            String[] attributes = query.split(ATTRIBUTE_DELIMITER);
            Map<String, String> attributeMap = new HashMap<>();
            boolean isFullTextSearch = false;
            String searchAttribute, searchValue;
            if (!query.contains(KEY_VALUE_DELIMITER)) {
                isFullTextSearch = true;
            } else {
                log.debug("Search query: " + query);
                for (String attribute : attributes) {
                    searchAttribute = attribute.split(KEY_VALUE_DELIMITER)[0];
                    searchValue = attribute.split(KEY_VALUE_DELIMITER)[1];
                    log.debug(searchAttribute + KEY_VALUE_DELIMITER + searchValue);
                    attributeMap.put(searchAttribute, searchValue);
                }
            }
            if (isFullTextSearch) {
                apiResults = getApiDAO().searchAPIs(roles, user, query, offset, limit);
            } else {
                log.debug("Attributes:", attributeMap.toString());
                apiResults = getApiDAO().attributeSearchAPIs(roles, user, attributeMap, offset, limit);
            }
        } else {
            apiResults = getApiDAO().getAPIs(roles, user);
        }
        return apiResults;
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while Searching the API with query " + query;
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (IdentityProviderException e) {
        String errorMsg = "Error occurred while calling SCIM endpoint to retrieve user " + user + "'s information";
        log.error(errorMsg, e);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    }
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) HashMap(java.util.HashMap) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API) IdentityProviderException(org.wso2.carbon.apimgt.core.exception.IdentityProviderException) HashSet(java.util.HashSet)

Example 4 with APIManagementException

use of org.wso2.carbon.apimgt.core.exception.APIManagementException in project carbon-apimgt by wso2.

the class APIPublisherImpl method deleteThreatProtectionPolicy.

@Override
public void deleteThreatProtectionPolicy(String apiId, String policyId) throws APIManagementException {
    API api = getAPIbyUUID(apiId);
    if (api == null) {
        String message = "Delete threat protection policy from API: No API found for APIID: " + apiId;
        log.error(message);
        throw new APIManagementException(message);
    }
    API.APIBuilder builder = new API.APIBuilder(api);
    Set<String> policies = builder.getThreatProtectionPolicies();
    if (policies != null) {
        policies.remove(policyId);
    }
    updateAPI(builder);
    if (log.isDebugEnabled()) {
        log.debug("Threat protection policy (ID: " + policyId + ") deleted from the API (ID: " + builder.getId() + ")");
    }
}
Also used : APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) API(org.wso2.carbon.apimgt.core.models.API)

Example 5 with APIManagementException

use of org.wso2.carbon.apimgt.core.exception.APIManagementException in project carbon-apimgt by wso2.

the class APIPublisherImpl method addAPI.

/**
 * Adds a new API to the system
 *
 * @param apiBuilder API model object
 * @return UUID of the added API.
 * @throws APIManagementException if failed to add API
 */
@Override
public String addAPI(API.APIBuilder apiBuilder) throws APIManagementException {
    API createdAPI;
    APIGateway gateway = getApiGateway();
    apiBuilder.provider(getUsername());
    if (StringUtils.isEmpty(apiBuilder.getId())) {
        apiBuilder.id(UUID.randomUUID().toString());
    }
    LocalDateTime localDateTime = LocalDateTime.now();
    apiBuilder.createdTime(localDateTime);
    apiBuilder.lastUpdatedTime(localDateTime);
    apiBuilder.createdBy(getUsername());
    apiBuilder.updatedBy(getUsername());
    if (apiBuilder.getLabels().isEmpty()) {
        List<String> labelSet = new ArrayList<>();
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_GATEWAY));
        labelSet.add(getLabelIdByNameAndType(APIMgtConstants.DEFAULT_LABEL_NAME, APIMgtConstants.LABEL_TYPE_STORE));
        apiBuilder.labels(labelSet);
    }
    Map<String, Endpoint> apiEndpointMap = apiBuilder.getEndpoint();
    validateEndpoints(apiEndpointMap, false);
    try {
        if (!isApiNameExist(apiBuilder.getName()) && !isContextExist(apiBuilder.getContext())) {
            LifecycleState lifecycleState = getApiLifecycleManager().addLifecycle(APIMgtConstants.API_LIFECYCLE, getUsername());
            apiBuilder.associateLifecycle(lifecycleState);
            createUriTemplateList(apiBuilder, false);
            List<UriTemplate> list = new ArrayList<>(apiBuilder.getUriTemplates().values());
            List<TemplateBuilderDTO> resourceList = new ArrayList<>();
            validateApiPolicy(apiBuilder.getApiPolicy());
            validateSubscriptionPolicies(apiBuilder);
            for (UriTemplate uriTemplate : list) {
                TemplateBuilderDTO dto = new TemplateBuilderDTO();
                dto.setTemplateId(uriTemplate.getTemplateId());
                dto.setUriTemplate(uriTemplate.getUriTemplate());
                dto.setHttpVerb(uriTemplate.getHttpVerb());
                Map<String, Endpoint> map = uriTemplate.getEndpoint();
                if (map.containsKey(APIMgtConstants.PRODUCTION_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.PRODUCTION_ENDPOINT);
                    dto.setProductionEndpoint(endpoint);
                }
                if (map.containsKey(APIMgtConstants.SANDBOX_ENDPOINT)) {
                    Endpoint endpoint = map.get(APIMgtConstants.SANDBOX_ENDPOINT);
                    dto.setSandboxEndpoint(endpoint);
                }
                resourceList.add(dto);
            }
            GatewaySourceGenerator gatewaySourceGenerator = getGatewaySourceGenerator();
            APIConfigContext apiConfigContext = new APIConfigContext(apiBuilder.build(), config.getGatewayPackageName());
            gatewaySourceGenerator.setApiConfigContext(apiConfigContext);
            String gatewayConfig = gatewaySourceGenerator.getConfigStringFromTemplate(resourceList);
            if (log.isDebugEnabled()) {
                log.debug("API " + apiBuilder.getName() + "gateway config: " + gatewayConfig);
            }
            apiBuilder.gatewayConfig(gatewayConfig);
            if (StringUtils.isEmpty(apiBuilder.getApiDefinition())) {
                apiBuilder.apiDefinition(apiDefinitionFromSwagger20.generateSwaggerFromResources(apiBuilder));
            }
            if (!StringUtils.isEmpty(apiBuilder.getApiPermission())) {
                Map<String, Integer> roleNamePermissionList;
                roleNamePermissionList = getAPIPermissionArray(apiBuilder.getApiPermission());
                apiBuilder.permissionMap(roleNamePermissionList);
            }
            createdAPI = apiBuilder.build();
            APIUtils.validate(createdAPI);
            // Add API to gateway
            gateway.addAPI(createdAPI);
            if (log.isDebugEnabled()) {
                log.debug("API : " + apiBuilder.getName() + " has been identifier published to gateway");
            }
            Set<String> apiRoleList;
            // if the API has role based visibility, add the API with role checking
            if (API.Visibility.PUBLIC == createdAPI.getVisibility()) {
                getApiDAO().addAPI(createdAPI);
            } else if (API.Visibility.RESTRICTED == createdAPI.getVisibility()) {
                // get all the roles in the system
                Set<String> allAvailableRoles = APIUtils.getAllAvailableRoles();
                // get the roles needed to be associated with the API
                apiRoleList = createdAPI.getVisibleRoles();
                if (APIUtils.checkAllowedRoles(allAvailableRoles, apiRoleList)) {
                    getApiDAO().addAPI(createdAPI);
                }
            }
            APIUtils.logDebug("API " + createdAPI.getName() + "-" + createdAPI.getVersion() + " was created " + "successfully.", log);
            // 'API_M Functions' related code
            // Create a payload with event specific details
            Map<String, String> eventPayload = new HashMap<>();
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_ID, createdAPI.getId());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_NAME, createdAPI.getName());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_VERSION, createdAPI.getVersion());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_DESCRIPTION, createdAPI.getDescription());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_CONTEXT, createdAPI.getContext());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_LC_STATUS, createdAPI.getLifeCycleStatus());
            eventPayload.put(APIMgtConstants.FunctionsConstants.API_PERMISSION, createdAPI.getApiPermission());
            // This will notify all the EventObservers(Asynchronous)
            ObserverNotifier observerNotifier = new ObserverNotifier(Event.API_CREATION, getUsername(), ZonedDateTime.now(ZoneOffset.UTC), eventPayload, this);
            ObserverNotifierThreadPool.getInstance().executeTask(observerNotifier);
        } else {
            String message = "Duplicate API already Exist with name/Context " + apiBuilder.getName();
            log.error(message);
            throw new APIManagementException(message, ExceptionCodes.API_ALREADY_EXISTS);
        }
    } catch (APIMgtDAOException e) {
        String errorMsg = "Error occurred while creating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, e.getErrorHandler());
    } catch (LifecycleException | ParseException e) {
        String errorMsg = "Error occurred while Associating the API - " + apiBuilder.getName();
        log.error(errorMsg);
        throw new APIManagementException(errorMsg, e, ExceptionCodes.APIMGT_LIFECYCLE_EXCEPTION);
    } catch (APITemplateException e) {
        String message = "Error generating API configuration for API " + apiBuilder.getName();
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.TEMPLATE_EXCEPTION);
    } catch (GatewayException e) {
        String message = "Error occurred while adding API - " + apiBuilder.getName() + " to gateway";
        log.error(message, e);
        throw new APIManagementException(message, ExceptionCodes.GATEWAY_EXCEPTION);
    }
    return apiBuilder.getId();
}
Also used : LocalDateTime(java.time.LocalDateTime) APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LifecycleState(org.wso2.carbon.lcm.core.impl.LifecycleState) GatewaySourceGenerator(org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator) Endpoint(org.wso2.carbon.apimgt.core.models.Endpoint) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) APIGateway(org.wso2.carbon.apimgt.core.api.APIGateway) LifecycleException(org.wso2.carbon.lcm.core.exception.LifecycleException) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) GatewayException(org.wso2.carbon.apimgt.core.exception.GatewayException) TemplateBuilderDTO(org.wso2.carbon.apimgt.core.template.dto.TemplateBuilderDTO) API(org.wso2.carbon.apimgt.core.models.API) ParseException(org.json.simple.parser.ParseException) APITemplateException(org.wso2.carbon.apimgt.core.template.APITemplateException) APIConfigContext(org.wso2.carbon.apimgt.core.template.APIConfigContext)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.core.exception.APIManagementException)432 Test (org.testng.annotations.Test)353 ApiDAO (org.wso2.carbon.apimgt.core.dao.ApiDAO)233 APIStore (org.wso2.carbon.apimgt.core.api.APIStore)202 API (org.wso2.carbon.apimgt.core.models.API)200 Test (org.junit.Test)164 Response (javax.ws.rs.core.Response)160 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)159 HashMap (java.util.HashMap)148 ErrorDTO (org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)146 APIGateway (org.wso2.carbon.apimgt.core.api.APIGateway)134 APIMgtDAOException (org.wso2.carbon.apimgt.core.exception.APIMgtDAOException)129 ArrayList (java.util.ArrayList)102 APIPublisher (org.wso2.carbon.apimgt.core.api.APIPublisher)100 BeforeTest (org.testng.annotations.BeforeTest)82 PolicyDAO (org.wso2.carbon.apimgt.core.dao.PolicyDAO)80 Request (org.wso2.msf4j.Request)80 WorkflowResponse (org.wso2.carbon.apimgt.core.api.WorkflowResponse)76 APILifecycleManager (org.wso2.carbon.apimgt.core.api.APILifecycleManager)75 GatewaySourceGenerator (org.wso2.carbon.apimgt.core.api.GatewaySourceGenerator)71