Search in sources :

Example 1 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier 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)

Example 2 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier 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 3 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-business-process by wso2.

the class TaskOperationsImpl method complete.

/**
 * Execution of the task finished successfully.
 * @param taskIdURI : task identifier
 * @param outputStr : task outcome (String)
 * @throws IllegalStateFault
 * @throws IllegalOperationFault
 * @throws IllegalArgumentFault
 * @throws IllegalAccessFault
 */
public void complete(final URI taskIdURI, final String outputStr) throws IllegalStateFault, IllegalOperationFault, IllegalArgumentFault, IllegalAccessFault {
    try {
        final Long taskId = validateTaskId(taskIdURI);
        HumanTaskServiceComponent.getHumanTaskServer().getTaskEngine().getScheduler().execTransaction(new Callable<Object>() {

            public Object call() throws Exception {
                Element output = DOMUtils.stringToDOM(outputStr);
                Complete completeCommand = new Complete(getCaller(), taskId, output);
                completeCommand.execute();
                return null;
            }
        });
    } catch (Exception ex) {
        handleException(ex);
    }
}
Also used : Complete(org.wso2.carbon.humantask.core.engine.commands.Complete) Element(org.w3c.dom.Element) HumanTaskIllegalArgumentException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalArgumentException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) HumanTaskIllegalStateException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalStateException) HumanTaskIllegalOperationException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalOperationException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) HumanTaskException(org.wso2.carbon.humantask.core.engine.HumanTaskException) HumanTaskIllegalAccessException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalAccessException) HumanTaskRuntimeException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)

Example 4 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-business-process by wso2.

the class TaskOperationsImpl method remove.

/**
 * Applies to notifications only.
 * Used by notification recipients to remove the notification permanently from their task list client.
 * @param taskId : Notification identifier
 * @throws IllegalOperationFault
 * @throws IllegalArgumentFault
 * @throws IllegalAccessFault
 */
public void remove(URI taskId) throws IllegalOperationFault, IllegalArgumentFault, IllegalAccessFault {
    try {
        final Long notificationId = validateTaskId(taskId);
        HumanTaskServiceComponent.getHumanTaskServer().getTaskEngine().getScheduler().execTransaction(new Callable<Object>() {

            public Object call() throws Exception {
                Remove removeCommand = new Remove(getCaller(), notificationId);
                removeCommand.execute();
                return null;
            }
        });
    } catch (HumanTaskIllegalOperationException ex) {
        log.error(ex);
        throw new IllegalOperationFault(ex);
    } catch (HumanTaskIllegalAccessException ex) {
        log.error(ex);
        throw new IllegalAccessFault(ex);
    } catch (Exception ex) {
        log.error(ex);
        throw new IllegalArgumentFault(ex);
    }
}
Also used : HumanTaskIllegalAccessException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalAccessException) HumanTaskIllegalOperationException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalOperationException) Remove(org.wso2.carbon.humantask.core.engine.commands.Remove) HumanTaskIllegalArgumentException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalArgumentException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) HumanTaskIllegalStateException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalStateException) HumanTaskIllegalOperationException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalOperationException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) HumanTaskException(org.wso2.carbon.humantask.core.engine.HumanTaskException) HumanTaskIllegalAccessException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalAccessException) HumanTaskRuntimeException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)

Example 5 with Identifier

use of org.wso2.carbon.apimgt.api.model.Identifier in project carbon-business-process by wso2.

the class TaskOperationsImpl method setOutput.

/**
 * Set the data for the part of the task's output message.
 *
 * @param taskIdURI : task identifier
 * @param ncName    : PartName
 * @param o
 * @throws IllegalStateFault
 * @throws IllegalOperationFault
 * @throws IllegalArgumentFault
 * @throws IllegalAccessFault
 */
public void setOutput(URI taskIdURI, NCName ncName, Object o) throws IllegalStateFault, IllegalOperationFault, IllegalArgumentFault, IllegalAccessFault {
    try {
        final Long taskId = validateTaskId(taskIdURI);
        if (ncName != null && o != null) {
            final String outputName = ncName.toString();
            final Element outputData = DOMUtils.stringToDOM((String) o);
            HumanTaskServiceComponent.getHumanTaskServer().getTaskEngine().getScheduler().execTransaction(new Callable<Object>() {

                public Object call() throws Exception {
                    SetOutput setOutputCommand = new SetOutput(getCaller(), taskId, outputName, outputData);
                    setOutputCommand.execute();
                    return null;
                }
            });
        } else {
            log.error("The output data for setOutput operation cannot be empty");
            throw new IllegalArgumentFault("The output data cannot be empty!");
        }
    } catch (Exception ex) {
        handleException(ex);
    }
}
Also used : Element(org.w3c.dom.Element) SetOutput(org.wso2.carbon.humantask.core.engine.commands.SetOutput) HumanTaskIllegalArgumentException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalArgumentException) RegistryException(org.wso2.carbon.registry.core.exceptions.RegistryException) HumanTaskIllegalStateException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalStateException) HumanTaskIllegalOperationException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalOperationException) UserStoreException(org.wso2.carbon.user.core.UserStoreException) HumanTaskException(org.wso2.carbon.humantask.core.engine.HumanTaskException) HumanTaskIllegalAccessException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskIllegalAccessException) HumanTaskRuntimeException(org.wso2.carbon.humantask.core.engine.runtime.api.HumanTaskRuntimeException)

Aggregations

APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)118 APIIdentifier (org.wso2.carbon.apimgt.api.model.APIIdentifier)83 RegistryException (org.wso2.carbon.registry.core.exceptions.RegistryException)66 API (org.wso2.carbon.apimgt.api.model.API)42 Resource (org.wso2.carbon.registry.core.Resource)40 APIProductIdentifier (org.wso2.carbon.apimgt.api.model.APIProductIdentifier)39 Test (org.junit.Test)36 PreparedStatement (java.sql.PreparedStatement)34 SQLException (java.sql.SQLException)34 SubscribedAPI (org.wso2.carbon.apimgt.api.model.SubscribedAPI)34 Connection (java.sql.Connection)33 UserStoreException (org.wso2.carbon.user.core.UserStoreException)31 ResultSet (java.sql.ResultSet)29 ArrayList (java.util.ArrayList)29 APIProvider (org.wso2.carbon.apimgt.api.APIProvider)29 UserRegistry (org.wso2.carbon.registry.core.session.UserRegistry)27 IOException (java.io.IOException)26 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)26 APIProductResource (org.wso2.carbon.apimgt.api.model.APIProductResource)25 HumanTaskException (org.wso2.carbon.humantask.core.engine.HumanTaskException)24