Search in sources :

Example 31 with Types

use of org.wso2.ballerinalang.compiler.semantics.analyzer.Types in project carbon-apimgt by wso2.

the class AlertMgtUtils method alertTypesToMap.

/**
 * Converts a list of AlertTypeDTOs to HashMap.
 *
 * @param alertTypes : The AlertTypeDTO list
 * @return A HashMap of the alert types
 */
static Map<String, String> alertTypesToMap(List<AlertTypeDTO> alertTypes) {
    List<Integer> alertTypeIds = new ArrayList<>();
    List<String> alertTypeNames = new ArrayList<>();
    Map<String, String> alertTypesMap = new HashMap<>();
    for (AlertTypeDTO alertTypeDTO : alertTypes) {
        alertTypeIds.add(alertTypeDTO.getId());
        alertTypeNames.add(alertTypeDTO.getName());
    }
    alertTypesMap.put("ids", StringUtils.join(alertTypeIds, ","));
    alertTypesMap.put("names", StringUtils.join(alertTypeNames, ","));
    return alertTypesMap;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) AlertTypeDTO(org.wso2.carbon.apimgt.impl.dto.AlertTypeDTO)

Example 32 with Types

use of org.wso2.ballerinalang.compiler.semantics.analyzer.Types in project carbon-apimgt by wso2.

the class WSDL11SOAPOperationExtractor method initModels.

/**
 * Initiallize SOAP to REST Operations
 *
 * @return true if extracting operations was successful
 */
private boolean initModels() throws APIMgtWSDLException {
    wsdlDefinition = getWSDLDefinition();
    boolean canProcess = true;
    targetNamespace = wsdlDefinition.getTargetNamespace();
    Types types = wsdlDefinition.getTypes();
    if (types != null) {
        typeList = types.getExtensibilityElements();
    }
    if (typeList != null) {
        for (Object ext : typeList) {
            if (ext instanceof Schema) {
                Schema schema = (Schema) ext;
                Map importedSchemas = schema.getImports();
                Element schemaElement = schema.getElement();
                NodeList schemaNodes = schemaElement.getChildNodes();
                schemaNodeList.addAll(SOAPOperationBindingUtils.list(schemaNodes));
                // gets types from imported schemas from the parent wsdl. Nested schemas will not be imported.
                if (importedSchemas != null) {
                    for (Object importedSchemaObj : importedSchemas.keySet()) {
                        String schemaUrl = (String) importedSchemaObj;
                        if (importedSchemas.get(schemaUrl) != null) {
                            Vector vector = (Vector) importedSchemas.get(schemaUrl);
                            for (Object schemaVector : vector) {
                                if (schemaVector instanceof SchemaImport) {
                                    Schema referencedSchema = ((SchemaImport) schemaVector).getReferencedSchema();
                                    if (referencedSchema != null && referencedSchema.getElement() != null) {
                                        if (referencedSchema.getElement().hasChildNodes()) {
                                            schemaNodeList.addAll(SOAPOperationBindingUtils.list(referencedSchema.getElement().getChildNodes()));
                                        } else {
                                            log.warn("The referenced schema : " + schemaUrl + " doesn't have any defined types");
                                        }
                                    } else {
                                        boolean isInlineSchema = false;
                                        for (Object aSchema : typeList) {
                                            if (schemaUrl.equalsIgnoreCase(((Schema) aSchema).getElement().getAttribute(TARGET_NAMESPACE_ATTRIBUTE))) {
                                                isInlineSchema = true;
                                                break;
                                            }
                                        }
                                        if (isInlineSchema) {
                                            log.debug(schemaUrl + " is already defined inline. Hence continue.");
                                        } else {
                                            log.warn("Cannot access referenced schema for the schema defined at: " + schemaUrl);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    log.info("No any imported schemas found in the given wsdl.");
                }
                List schemaIncludes = schema.getIncludes();
                for (Iterator iter = schemaIncludes.iterator(); iter.hasNext(); ) {
                    SchemaReference schemaInclude = (SchemaReference) iter.next();
                    Schema schemaImp = schemaInclude.getReferencedSchema();
                    String schemaLoc = schemaInclude.getSchemaLocationURI();
                    if (schemaImp != null && schemaImp.getElement() != null) {
                        if (schemaImp.getElement().hasChildNodes()) {
                            schemaNodeList.addAll(SOAPOperationBindingUtils.list(schemaImp.getElement().getChildNodes()));
                        } else {
                            log.warn("The referenced schema : " + schemaLoc + " doesn't have any defined types");
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    Gson gson = new GsonBuilder().setExclusionStrategies(new SwaggerFieldsExcludeStrategy()).create();
                    log.debug("swagger definition model map from the wsdl: " + gson.toJson(parameterModelMap));
                }
                if (schemaNodeList == null) {
                    log.warn("No schemas found in the type element for target namespace:" + schema.getDocumentBaseURI());
                }
            }
        }
        if (schemaNodeList != null) {
            for (Node node : schemaNodeList) {
                WSDLParamDefinition wsdlParamDefinition = new WSDLParamDefinition();
                ModelImpl model = new ModelImpl();
                Property currentProperty = null;
                try {
                    traverseTypeElement(node, null, model, currentProperty);
                } catch (APIManagementException e) {
                    throw new APIMgtWSDLException(e);
                }
                if (StringUtils.isNotBlank(model.getName())) {
                    parameterModelMap.put(model.getName(), model);
                }
                if (wsdlParamDefinition.getDefinitionName() != null) {
                    wsdlParamDefinitions.add(wsdlParamDefinition);
                }
            }
        } else {
            log.info("No schema is defined in the wsdl document");
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Successfully initialized an instance of " + this.getClass().getSimpleName() + " with a single WSDL.");
    }
    return canProcess;
}
Also used : Types(javax.wsdl.Types) SwaggerFieldsExcludeStrategy(org.wso2.carbon.apimgt.impl.wsdl.util.SwaggerFieldsExcludeStrategy) WSDLParamDefinition(org.wso2.carbon.apimgt.impl.wsdl.model.WSDLParamDefinition) SchemaImport(javax.wsdl.extensions.schema.SchemaImport) GsonBuilder(com.google.gson.GsonBuilder) Schema(javax.wsdl.extensions.schema.Schema) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Gson(com.google.gson.Gson) SchemaReference(javax.wsdl.extensions.schema.SchemaReference) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) APIMgtWSDLException(org.wso2.carbon.apimgt.impl.wsdl.exceptions.APIMgtWSDLException) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) ModelImpl(io.swagger.models.ModelImpl) Map(java.util.Map) HashMap(java.util.HashMap) NamedNodeMap(org.w3c.dom.NamedNodeMap) Vector(java.util.Vector) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) LongProperty(io.swagger.models.properties.LongProperty) DecimalProperty(io.swagger.models.properties.DecimalProperty) Property(io.swagger.models.properties.Property) DoubleProperty(io.swagger.models.properties.DoubleProperty) DateTimeProperty(io.swagger.models.properties.DateTimeProperty) RefProperty(io.swagger.models.properties.RefProperty) FloatProperty(io.swagger.models.properties.FloatProperty) DateProperty(io.swagger.models.properties.DateProperty) ObjectProperty(io.swagger.models.properties.ObjectProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) BooleanProperty(io.swagger.models.properties.BooleanProperty)

Example 33 with Types

use of org.wso2.ballerinalang.compiler.semantics.analyzer.Types in project carbon-apimgt by wso2.

the class AlertTypesApiServiceImpl method getAdminAlertTypes.

@Override
public Response getAdminAlertTypes(MessageContext messageContext) throws APIManagementException {
    try {
        AdminAlertConfigurator adminAlertConfigurator = (AdminAlertConfigurator) AlertConfigManager.getInstance().getAlertConfigurator(AlertMgtConstants.ADMIN_DASHBOARD_AGENT);
        List<org.wso2.carbon.apimgt.impl.dto.AlertTypeDTO> alertTypes = adminAlertConfigurator.getSupportedAlertTypes();
        AlertTypesListDTO alertTypesListDTO = AlertsMappingUtil.fromAlertTypesListToAlertTypeListDTO(alertTypes);
        return Response.status(Response.Status.OK).entity(alertTypesListDTO).build();
    } catch (APIManagementException e) {
        RestApiUtil.handleInternalServerError("Internal Server Error Occurred while retrieving alert types", e, log);
    } catch (AlertManagementException e) {
        log.warn("API Manager Analytics is not enabled", e);
        return Response.status(Response.Status.NO_CONTENT).build();
    }
    return Response.status(Response.Status.NO_CONTENT).build();
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) AlertManagementException(org.wso2.carbon.apimgt.impl.alertmgt.exception.AlertManagementException) AdminAlertConfigurator(org.wso2.carbon.apimgt.impl.alertmgt.AdminAlertConfigurator) AlertTypesListDTO(org.wso2.carbon.apimgt.rest.api.admin.v1.dto.AlertTypesListDTO)

Example 34 with Types

use of org.wso2.ballerinalang.compiler.semantics.analyzer.Types in project carbon-apimgt by wso2.

the class APIControllerUtil method handleEndpointSecurityConfigs.

/**
 * This method will be used to add Endpoint security related environment parameters to imported Api object.
 *
 * @param envParams      Env params object with required parameters
 * @param endpointConfig Endpoint config object to be updated
 * @throws APIManagementException If an error occurs when setting security env parameters
 */
private static void handleEndpointSecurityConfigs(JsonObject envParams, JsonObject endpointConfig) throws APIManagementException {
    // If the user has set (either true or false) the enabled field under security in the params file,
    // the following code should be executed.
    JsonObject security = envParams.getAsJsonObject(ImportExportConstants.ENDPOINT_SECURITY_FIELD);
    if (security == null) {
        return;
    }
    String[] endpointTypes = { APIConstants.ENDPOINT_SECURITY_PRODUCTION, APIConstants.ENDPOINT_SECURITY_SANDBOX };
    for (String endpointType : endpointTypes) {
        if (security.has(endpointType)) {
            JsonObject endpointSecurityDetails = security.get(endpointType).getAsJsonObject();
            if (endpointSecurityDetails.has(APIConstants.ENDPOINT_SECURITY_ENABLED) && (endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_ENABLED) != null || !endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_ENABLED).isJsonNull())) {
                boolean securityEnabled = endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_ENABLED).getAsBoolean();
                // Set endpoint security details to API
                if (securityEnabled) {
                    String endpointSecurityType;
                    if (endpointSecurityDetails.has(APIConstants.ENDPOINT_SECURITY_TYPE) && (endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_TYPE) != null || !endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_TYPE).isJsonNull())) {
                        // Check whether the type is defined in the params file
                        JsonElement type = endpointSecurityDetails.get(APIConstants.ENDPOINT_SECURITY_TYPE);
                        endpointSecurityType = type.getAsString();
                    } else {
                        throw new APIManagementException("You have enabled endpoint security but the type is not found " + "in the params file. Please specify type field and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
                    }
                    // Setup security type (basic, digest or oauth)
                    endpointSecurityDetails.remove(APIConstants.ENDPOINT_SECURITY_TYPE);
                    if (StringUtils.equals(endpointSecurityType.toLowerCase(), APIConstants.ENDPOINT_SECURITY_TYPE_DIGEST)) {
                        endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_DIGEST.toUpperCase());
                        validateEndpointSecurityUsernamePassword(endpointSecurityDetails);
                    } else if (StringUtils.equals(endpointSecurityType.toLowerCase(), APIConstants.ENDPOINT_SECURITY_TYPE_BASIC)) {
                        endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_BASIC.toUpperCase());
                        validateEndpointSecurityUsernamePassword(endpointSecurityDetails);
                    } else if (StringUtils.equals(endpointSecurityType.toLowerCase(), APIConstants.ENDPOINT_SECURITY_TYPE_OAUTH)) {
                        endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, APIConstants.ENDPOINT_SECURITY_TYPE_OAUTH.toUpperCase());
                        validateEndpointSecurityOauth(endpointSecurityDetails);
                    } else {
                        // If the type is not either basic or digest, return an error
                        throw new APIManagementException("Invalid endpoint security type found in the params file. " + "Should be either basic, digest or oauth. " + "Please specify correct security types field and continue...", ExceptionCodes.ERROR_READING_PARAMS_FILE);
                    }
                } else {
                    endpointSecurityDetails.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, ImportExportConstants.ENDPOINT_NONE_SECURITY_TYPE);
                }
            }
        } else {
            // Even though the security field is defined, if either production/sandbox is not defined
            // under that,set endpoint security to none. Otherwise the security will be blank if you
            // check from the UI.
            JsonObject endpointSecurityForNotDefinedEndpointType = new JsonObject();
            endpointSecurityForNotDefinedEndpointType.addProperty(APIConstants.ENDPOINT_SECURITY_TYPE, ImportExportConstants.ENDPOINT_NONE_SECURITY_TYPE);
            endpointSecurityForNotDefinedEndpointType.addProperty(APIConstants.ENDPOINT_SECURITY_ENABLED, Boolean.FALSE);
            security.add(endpointType, endpointSecurityForNotDefinedEndpointType);
        }
    }
    endpointConfig.add(APIConstants.ENDPOINT_SECURITY, security);
}
Also used : APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JsonElement(com.google.gson.JsonElement) JsonObject(com.google.gson.JsonObject)

Example 35 with Types

use of org.wso2.ballerinalang.compiler.semantics.analyzer.Types in project carbon-apimgt by wso2.

the class APIDefinitionFromOpenAPISpec method validateScopesFromSwagger.

/**
 * Called using the jaggery api. Checks if the swagger contains valid api scopes.
 *
 * @param swagger Swagger definition
 * @return true if the scope definition is valid
 * @throws APIManagementException
 */
public Boolean validateScopesFromSwagger(String swagger) throws APIManagementException {
    try {
        Set<Scope> scopes = getScopes(swagger);
        JSONParser parser = new JSONParser();
        JSONObject swaggerJson;
        swaggerJson = (JSONObject) parser.parse(swagger);
        if (swaggerJson.get("paths") != null) {
            JSONObject paths = (JSONObject) swaggerJson.get("paths");
            for (Object uriTempKey : paths.keySet()) {
                String uriTemp = (String) uriTempKey;
                // if url template is a custom attribute "^x-" ignore.
                if (uriTemp.startsWith("x-") || uriTemp.startsWith("X-")) {
                    continue;
                }
                JSONObject path = (JSONObject) paths.get(uriTemp);
                // See field types supported by "Path Item Object" in swagger spec.
                if (path.containsKey("$ref")) {
                    continue;
                }
                for (Object httpVerbKey : path.keySet()) {
                    String httpVerb = (String) httpVerbKey;
                    JSONObject operation = (JSONObject) path.get(httpVerb);
                    String operationScope = (String) operation.get(APIConstants.SWAGGER_X_SCOPE);
                    Scope scope = APIUtil.findScopeByKey(scopes, operationScope);
                    if (scope == null && operationScope != null) {
                        return false;
                    }
                }
            }
        }
        return true;
    } catch (APIManagementException e) {
        handleException("Error when validating scopes", e);
        return false;
    } catch (ParseException e) {
        handleException("Error when validating scopes", e);
        return false;
    }
}
Also used : Scope(org.wso2.carbon.apimgt.api.model.Scope) JSONObject(org.json.simple.JSONObject) APIManagementException(org.wso2.carbon.apimgt.api.APIManagementException) JSONParser(org.json.simple.parser.JSONParser) JSONObject(org.json.simple.JSONObject) ParseException(org.json.simple.parser.ParseException)

Aggregations

ArrayList (java.util.ArrayList)20 Test (org.testng.annotations.Test)15 BType (org.wso2.ballerinalang.compiler.semantics.model.types.BType)13 SiddhiManager (org.wso2.siddhi.core.SiddhiManager)12 HashMap (java.util.HashMap)11 Map (java.util.Map)11 APIManagementException (org.wso2.carbon.apimgt.api.APIManagementException)10 List (java.util.List)8 JsonObject (com.google.gson.JsonObject)5 Test (org.junit.Test)5 SiddhiAppRuntime (org.wso2.siddhi.core.SiddhiAppRuntime)5 Arrays (java.util.Arrays)4 Collectors (java.util.stream.Collectors)4 JSONObject (org.json.simple.JSONObject)4 BSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BSymbol)4 BLangPackage (org.wso2.ballerinalang.compiler.tree.BLangPackage)4 JsonElement (com.google.gson.JsonElement)3 Paths (java.nio.file.Paths)3 TokenStream (org.antlr.v4.runtime.TokenStream)3 StringUtils (org.apache.commons.lang3.StringUtils)3