Search in sources :

Example 51 with Parameter

use of org.wso2.siddhi.annotation.Parameter in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method generateMergedResourceDefinition.

@Override
public String generateMergedResourceDefinition(String resourceConfigJson, API api) {
    SwaggerParser swaggerParser = new SwaggerParser();
    Swagger swagger = swaggerParser.parse(resourceConfigJson);
    addSecuritySchemeToSwaggerDefinition(swagger, api);
    String securityName = getOauthSecurityName(swagger);
    if (!StringUtils.isEmpty(securityName)) {
        List<SecurityRequirement> securityRequirements = swagger.getSecurity();
        if (securityRequirements != null) {
            for (SecurityRequirement securityRequirement : securityRequirements) {
                Map<String, List<String>> requirementMap = securityRequirement.getRequirements();
                if (requirementMap.containsKey(securityName)) {
                    requirementMap.replace(securityName, api.getScopes());
                } else {
                    if (!api.getScopes().isEmpty()) {
                        requirementMap.put(securityName, api.getScopes());
                    }
                }
            }
        } else {
            if (!api.getScopes().isEmpty()) {
                SecurityRequirement securityRequirement = new SecurityRequirement();
                securityRequirement.setRequirements(securityName, api.getScopes());
                swagger.addSecurity(securityRequirement);
            }
        }
        Map<String, UriTemplate> uriTemplateMap = new HashMap<>(api.getUriTemplates());
        swagger.getPaths().entrySet().removeIf(entry -> isPathNotExist(uriTemplateMap, securityName, entry));
        uriTemplateMap.forEach((k, v) -> {
            Path path = swagger.getPath(v.getUriTemplate());
            if (path == null) {
                path = new Path();
                swagger.path(v.getUriTemplate(), path);
            }
            Map<HttpMethod, Operation> operationMap = path.getOperationMap();
            Operation operation = operationMap.get(getHttpMethodForVerb(v.getHttpVerb().toUpperCase()));
            if (operation != null) {
                assignScopesToOperation(operation, securityName, v.getScopes());
            } else {
                Operation operationTocCreate = new Operation();
                operationTocCreate.addSecurity(securityName, v.getScopes());
                operationTocCreate.addResponse("200", getDefaultResponse());
                List<Parameter> parameterList = getParameters(v.getUriTemplate());
                if (!HttpMethod.GET.toString().equalsIgnoreCase(v.getHttpVerb()) && !HttpMethod.DELETE.toString().equalsIgnoreCase(v.getHttpVerb()) && !HttpMethod.OPTIONS.toString().equalsIgnoreCase(v.getHttpVerb()) && !HttpMethod.HEAD.toString().equalsIgnoreCase(v.getHttpVerb())) {
                    parameterList.add(getDefaultBodyParameter());
                }
                operationTocCreate.setParameters(parameterList);
                path.set(v.getHttpVerb().toLowerCase(), operationTocCreate);
            }
        });
    }
    return Json.pretty(swagger);
}
Also used : Path(io.swagger.models.Path) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Operation(io.swagger.models.Operation) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) SwaggerParser(io.swagger.parser.SwaggerParser) Swagger(io.swagger.models.Swagger) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) List(java.util.List) ArrayList(java.util.ArrayList) HttpMethod(io.swagger.models.HttpMethod) SecurityRequirement(io.swagger.models.SecurityRequirement)

Example 52 with Parameter

use of org.wso2.siddhi.annotation.Parameter in project carbon-apimgt by wso2.

the class APIDefinitionFromSwagger20 method generateSwaggerFromResources.

/**
 * generate the swagger from uri templates.
 *
 * @param api API Object
 * @return Generated swagger resources as string.
 */
@Override
public String generateSwaggerFromResources(API.APIBuilder api) {
    Swagger swagger = new Swagger();
    Info info = new Info();
    info.setTitle(api.getName());
    info.setDescription(api.getDescription());
    Contact contact = new Contact();
    if (api.getBusinessInformation() != null) {
        BusinessInformation businessInformation = api.getBusinessInformation();
        contact.setName(businessInformation.getBusinessOwner());
        contact.setEmail(businessInformation.getBusinessOwnerEmail());
    }
    info.setContact(contact);
    info.setVersion(api.getVersion());
    swagger.setInfo(info);
    addSecuritySchemeToSwaggerDefinition(swagger, api.build());
    Map<String, Path> stringPathMap = new HashMap();
    for (UriTemplate uriTemplate : api.getUriTemplates().values()) {
        String uriTemplateString = uriTemplate.getUriTemplate();
        List<Parameter> parameterList = getParameters(uriTemplateString);
        if (uriTemplate.getParameters() == null || uriTemplate.getParameters().isEmpty()) {
            if (!HttpMethod.GET.toString().equalsIgnoreCase(uriTemplate.getHttpVerb()) && !HttpMethod.DELETE.toString().equalsIgnoreCase(uriTemplate.getHttpVerb()) && !HttpMethod.OPTIONS.toString().equalsIgnoreCase(uriTemplate.getHttpVerb()) && !HttpMethod.HEAD.toString().equalsIgnoreCase(uriTemplate.getHttpVerb())) {
                parameterList.add(getDefaultBodyParameter());
            }
        } else {
            for (URITemplateParam uriTemplateParam : uriTemplate.getParameters()) {
                Parameter parameter = getParameterFromURITemplateParam(uriTemplateParam);
                parameterList.add(parameter);
            }
        }
        Operation operation = new Operation();
        operation.setParameters(parameterList);
        operation.setOperationId(uriTemplate.getTemplateId());
        // having content types like */* can break swagger definition
        if (!StringUtils.isEmpty(uriTemplate.getContentType()) && !uriTemplate.getContentType().contains("*")) {
            List<String> consumesList = new ArrayList<>();
            consumesList.add(uriTemplate.getContentType());
            operation.setConsumes(consumesList);
        }
        operation.addResponse("200", getDefaultResponse());
        if (!APIMgtConstants.AUTH_NO_AUTHENTICATION.equals(uriTemplate.getAuthType()) && ((api.getSecurityScheme() & 2) == 2)) {
            log.debug("API security scheme : API Key Scheme ---- Resource Auth Type : Not None");
            operation.addSecurity(APIMgtConstants.SWAGGER_APIKEY, null);
        }
        if (!APIMgtConstants.AUTH_NO_AUTHENTICATION.equals(uriTemplate.getAuthType()) && ((api.getSecurityScheme() & 1) == 1)) {
            log.debug("API security scheme : Oauth Scheme ---- Resource Auth Type : Not None");
            operation.addSecurity(APIMgtConstants.SWAGGER_OAUTH2, null);
        }
        if (stringPathMap.containsKey(uriTemplateString)) {
            Path path = stringPathMap.get(uriTemplateString);
            path.set(uriTemplate.getHttpVerb().toLowerCase(), operation);
        } else {
            Path path = new Path();
            path.set(uriTemplate.getHttpVerb().toLowerCase(), operation);
            stringPathMap.put(uriTemplateString, path);
        }
    }
    swagger.setPaths(stringPathMap);
    swagger.setPaths(stringPathMap);
    return Json.pretty(swagger);
}
Also used : Path(io.swagger.models.Path) BusinessInformation(org.wso2.carbon.apimgt.core.models.BusinessInformation) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Operation(io.swagger.models.Operation) Info(io.swagger.models.Info) ServiceMethodInfo(org.wso2.msf4j.ServiceMethodInfo) UriTemplate(org.wso2.carbon.apimgt.core.models.UriTemplate) Contact(io.swagger.models.Contact) Swagger(io.swagger.models.Swagger) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) BodyParameter(io.swagger.models.parameters.BodyParameter) URITemplateParam(org.wso2.carbon.apimgt.core.models.URITemplateParam)

Example 53 with Parameter

use of org.wso2.siddhi.annotation.Parameter in project carbon-apimgt by wso2.

the class UserMappingDAOImpl method getUserIDByPseudoName.

/**
 * @param pseudoName pseudo name parameter of the user
 * @return String user id
 * @throws APIMgtDAOException when error in data retrieving
 */
@Override
public String getUserIDByPseudoName(String pseudoName) throws APIMgtDAOException {
    final String query = "SELECT USER_DOMAIN_NAME, USER_IDENTIFIER FROM AM_USER_NAME_MAPPING WHERE " + "PSEUDO_NAME = ?";
    String realName = null;
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setString(1, pseudoName);
        try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
                realName = rs.getString("USER_IDENTIFIER");
            }
        }
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + "getting name mappings", e);
    }
    return realName;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 54 with Parameter

use of org.wso2.siddhi.annotation.Parameter in project carbon-apimgt by wso2.

the class UserMappingDAOImpl method getPseudoNameByUserID.

/**
 * @param userID user identifier
 * @return String pseudo name parameter of the user
 * @throws APIMgtDAOException when error in data retrieving
 */
@Override
public String getPseudoNameByUserID(String userID) throws APIMgtDAOException {
    final String query = "SELECT PSEUDO_NAME FROM AM_USER_NAME_MAPPING WHERE USER_IDENTIFIER = ?";
    String pseudoName = null;
    try (Connection connection = DAOUtil.getConnection();
        PreparedStatement statement = connection.prepareStatement(query)) {
        statement.setString(1, userID);
        try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
                pseudoName = rs.getString("PSEUDO_NAME");
            }
        }
        if (pseudoName == null) {
            pseudoName = addUserMapping(userID);
        }
    } catch (SQLException e) {
        throw new APIMgtDAOException(DAOUtil.DAO_ERROR_PREFIX + " getting name mappings", e);
    }
    return pseudoName;
}
Also used : APIMgtDAOException(org.wso2.carbon.apimgt.core.exception.APIMgtDAOException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 55 with Parameter

use of org.wso2.siddhi.annotation.Parameter in project carbon-apimgt by wso2.

the class LabelsApiServiceImpl method labelsLabelIdDelete.

/**
 * Delete label by label id
 *
 * @param labelId           Id of the label
 * @param request           msf4j request object
 * @return 200 OK if the operation is successful
 * @throws NotFoundException If failed to find the particular resource
 */
@Override
public Response labelsLabelIdDelete(String labelId, Request request) throws NotFoundException {
    try {
        if (labelId != null) {
            APIMgtAdminService apiMgtAdminService = RestApiUtil.getAPIMgtAdminService();
            apiMgtAdminService.deleteLabel(labelId);
        } else {
            // mandatory parameters not provided
            String errorMessage = "Label Id parameter should be provided";
            ErrorHandler errorHandler = ExceptionCodes.PARAMETER_NOT_PROVIDED;
            ErrorDTO errorDTO = RestApiUtil.getErrorDTO(errorHandler);
            log.error(errorMessage);
            return Response.status(errorHandler.getHttpStatusCode()).entity(errorDTO).build();
        }
    } catch (APIManagementException e) {
        String errorMessage = "Error occurred while deleting the label [labelId] " + labelId;
        HashMap<String, String> paramList = new HashMap<String, String>();
        ErrorDTO errorDTO = RestApiUtil.getErrorDTO(e.getErrorHandler(), paramList);
        log.error(errorMessage, e);
        return Response.status(e.getErrorHandler().getHttpStatusCode()).entity(errorDTO).build();
    }
    return Response.status(Response.Status.NO_CONTENT).build();
}
Also used : APIMgtAdminService(org.wso2.carbon.apimgt.core.api.APIMgtAdminService) ErrorHandler(org.wso2.carbon.apimgt.core.exception.ErrorHandler) APIManagementException(org.wso2.carbon.apimgt.core.exception.APIManagementException) HashMap(java.util.HashMap) ErrorDTO(org.wso2.carbon.apimgt.rest.api.common.dto.ErrorDTO)

Aggregations

HashMap (java.util.HashMap)26 ArrayList (java.util.ArrayList)19 BLangEndpoint (org.wso2.ballerinalang.compiler.tree.BLangEndpoint)14 JSONDecoder (org.wso2.charon3.core.encoder.JSONDecoder)11 BadRequestException (org.wso2.charon3.core.exceptions.BadRequestException)11 CharonException (org.wso2.charon3.core.exceptions.CharonException)11 InternalErrorException (org.wso2.charon3.core.exceptions.InternalErrorException)11 NotFoundException (org.wso2.charon3.core.exceptions.NotFoundException)11 SCIMResponse (org.wso2.charon3.core.protocol.SCIMResponse)11 SCIMResourceTypeSchema (org.wso2.charon3.core.schema.SCIMResourceTypeSchema)11 Test (org.testng.annotations.Test)8 BInvokableSymbol (org.wso2.ballerinalang.compiler.semantics.model.symbols.BInvokableSymbol)8 BLangVariable (org.wso2.ballerinalang.compiler.tree.BLangVariable)8 JSONEncoder (org.wso2.charon3.core.encoder.JSONEncoder)8 List (java.util.List)7 BLangFunction (org.wso2.ballerinalang.compiler.tree.BLangFunction)7 ConstantExpressionExecutor (org.wso2.siddhi.core.executor.ConstantExpressionExecutor)7 SiddhiAppValidationException (org.wso2.siddhi.query.api.exception.SiddhiAppValidationException)7 Parameter (org.apache.axis2.description.Parameter)6 BInvokableType (org.wso2.ballerinalang.compiler.semantics.model.types.BInvokableType)6