use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.
the class DataProcessAndPublishingAgent method run.
public void run() {
JSONObject jsonObMap = new JSONObject();
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext).getAxis2MessageContext();
if (ipAddress != null && ipAddress.length() > 0) {
if (ipAddress.contains(":") && ipAddress.split(":").length == 2) {
log.warn("Client port will be ignored and only the IP address (IPV4) will concern from " + ipAddress);
ipAddress = ipAddress.split(":")[0];
}
try {
InetAddress address = APIUtil.getAddress(ipAddress);
if (address instanceof Inet4Address) {
jsonObMap.put(APIThrottleConstants.IP, APIUtil.ipToLong(ipAddress));
jsonObMap.put(APIThrottleConstants.IPv6, 0);
} else if (address instanceof Inet6Address) {
jsonObMap.put(APIThrottleConstants.IPv6, APIUtil.ipToBigInteger(ipAddress));
jsonObMap.put(APIThrottleConstants.IP, 0);
}
} catch (UnknownHostException e) {
// send empty value as ip
log.error("Error while parsing host IP " + ipAddress, e);
jsonObMap.put(APIThrottleConstants.IPv6, 0);
jsonObMap.put(APIThrottleConstants.IP, 0);
}
}
// HeaderMap will only be set if the Header Publishing has been enabled.
if (getThrottleProperties().isEnableHeaderConditions()) {
if (this.headersMap != null) {
jsonObMap.putAll(this.headersMap);
}
}
// adding any custom property if available to stream's property map
if (this.customPropertyMap != null) {
jsonObMap.putAll(this.customPropertyMap);
}
// Setting query parameters
if (getThrottleProperties().isEnableQueryParamConditions()) {
Map<String, String> queryParams = GatewayUtils.getQueryParams(axis2MessageContext);
if (queryParams != null) {
jsonObMap.putAll(queryParams);
}
}
// Publish jwt claims
if (getThrottleProperties().isEnableJwtConditions()) {
if (authenticationContext.getCallerToken() != null) {
Map<String, String> assertions = JWTUtil.getJWTClaims(authenticationContext.getCallerToken());
if (assertions != null) {
jsonObMap.putAll(assertions);
}
}
}
// this parameter will be used to capture message size and pass it to calculation logic
ArrayList<VerbInfoDTO> list = (ArrayList<VerbInfoDTO>) messageContext.getProperty(APIConstants.VERB_INFO_DTO);
boolean isVerbInfoContentAware = false;
if (list != null && !list.isEmpty()) {
VerbInfoDTO verbInfoDTO = list.get(0);
isVerbInfoContentAware = verbInfoDTO.isContentAware();
}
if (authenticationContext.isContentAwareTierPresent() || isVerbInfoContentAware) {
if (log.isDebugEnabled()) {
log.debug("Message size: " + messageSizeInBytes + "B");
}
jsonObMap.put(APIThrottleConstants.MESSAGE_SIZE, messageSizeInBytes);
if (!StringUtils.isEmpty(authenticationContext.getApplicationName())) {
jsonObMap.put(APIThrottleConstants.APPLICATION_NAME, authenticationContext.getApplicationName());
}
if (!StringUtils.isEmpty(authenticationContext.getProductName()) && !StringUtils.isEmpty(authenticationContext.getProductProvider())) {
jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_PRODUCT_SUBSCRIPTION_TYPE);
} else {
jsonObMap.put(APIThrottleConstants.SUBSCRIPTION_TYPE, APIConstants.API_SUBSCRIPTION_TYPE);
}
}
Object[] objects = new Object[] { messageContext.getMessageID(), this.applicationLevelThrottleKey, this.applicationLevelTier, this.apiLevelThrottleKey, this.apiLevelTier, this.subscriptionLevelThrottleKey, this.subscriptionLevelTier, this.resourceLevelThrottleKey, this.resourceLevelTier, this.authorizedUser, this.apiContext, this.apiVersion, this.appTenant, this.apiTenant, this.appId, this.apiName, jsonObMap.toString() };
org.wso2.carbon.databridge.commons.Event event = new org.wso2.carbon.databridge.commons.Event(streamID, System.currentTimeMillis(), null, null, objects);
dataPublisher.tryPublish(event);
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.
the class AlertSubscriptionsApiServiceImpl method subscribeForBotDetectionAlerts.
/**
* Subscribe for bot detection alerts
*
* @param body email to be registered for the subscription
* @param messageContext CXF Message Context
* @return alert subscription DTO containing the uuid of the subscription and the registered email
* @throws APIManagementException if an error occurs when subscribing for bot detection alerts
*/
@Override
public Response subscribeForBotDetectionAlerts(BotDetectionAlertSubscriptionDTO body, MessageContext messageContext) throws APIManagementException {
String email = body.getEmail();
if (StringUtils.isBlank(email)) {
String propertyName = AlertMgtConstants.BOT_DETECTION_EMAIL_FIELD;
throw new APIManagementException(propertyName + " property value of payload cannot be blank", ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
APIAdmin apiAdmin = new APIAdminImpl();
BotDetectionData alertSubscription = apiAdmin.getBotDetectionAlertSubscription(AlertMgtConstants.BOT_DETECTION_EMAIL_FIELD, email);
if (alertSubscription != null) {
RestApiUtil.handleResourceAlreadyExistsError("Email: " + email + " has already been subscribed for bot detection alerts", log);
}
apiAdmin.addBotDetectionAlertSubscription(email);
BotDetectionData newAlertSubscription = apiAdmin.getBotDetectionAlertSubscription(AlertMgtConstants.BOT_DETECTION_EMAIL_FIELD, email);
BotDetectionAlertSubscriptionDTO alertSubscriptionDTO = BotDetectionMappingUtil.fromAlertSubscriptionToDTO(newAlertSubscription);
return Response.ok(alertSubscriptionDTO).build();
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.
the class SequenceGenerator method generateSequencesFromSwagger.
/**
* Generates in/out sequences from the swagger given
*
* @param swaggerStr swagger string
* @throws APIManagementException
*/
public static List<SOAPToRestSequence> generateSequencesFromSwagger(String swaggerStr) throws APIManagementException {
List<SOAPToRestSequence> sequences = new ArrayList<SOAPToRestSequence>();
Swagger swagger = new SwaggerParser().parse(swaggerStr);
Map<String, Model> definitions = swagger.getDefinitions();
// Configure serializers
SimpleModule simpleModule = new SimpleModule().addSerializer(new JsonNodeExampleSerializer());
Json.mapper().registerModule(simpleModule);
Yaml.mapper().registerModule(simpleModule);
Map<String, Path> paths = swagger.getPaths();
for (String pathName : paths.keySet()) {
Path path = paths.get(pathName);
Map<HttpMethod, Operation> operationMap = path.getOperationMap();
for (HttpMethod httpMethod : operationMap.keySet()) {
boolean isResourceFromWSDL = false;
Map<String, String> parameterJsonPathMapping = new HashMap<>();
Map<String, String> queryParameters = new HashMap<>();
Operation operation = operationMap.get(httpMethod);
String operationId = operation.getOperationId();
// get vendor extensions
Map<String, Object> vendorExtensions = operation.getVendorExtensions();
Object vendorExtensionObj = vendorExtensions.get("x-wso2-soap");
String soapAction = SOAPToRESTConstants.EMPTY_STRING;
String namespace = SOAPToRESTConstants.EMPTY_STRING;
String soapVersion = SOAPToRESTConstants.EMPTY_STRING;
if (vendorExtensionObj != null) {
soapAction = (String) ((LinkedHashMap) vendorExtensionObj).get("soap-action");
namespace = (String) ((LinkedHashMap) vendorExtensionObj).get("namespace");
soapVersion = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_VERSION);
soapMessageType = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_MESSAGE_TYPE);
soapStyle = (String) ((LinkedHashMap) vendorExtensionObj).get(SOAPToRESTConstants.Swagger.SOAP_STYLE);
isResourceFromWSDL = true;
}
String soapNamespace = SOAPToRESTConstants.SOAP12_NAMSPACE;
if (StringUtils.isNotBlank(soapVersion) && SOAPToRESTConstants.SOAP_VERSION_11.equals(soapVersion)) {
soapNamespace = SOAPToRESTConstants.SOAP11_NAMESPACE;
}
List<Parameter> parameters = operation.getParameters();
for (Parameter parameter : parameters) {
String name = parameter.getName();
if (parameter instanceof BodyParameter) {
Model schema = ((BodyParameter) parameter).getSchema();
if (schema instanceof RefModel) {
String $ref = ((RefModel) schema).get$ref();
if (StringUtils.isNotBlank($ref)) {
String defName = $ref.substring("#/definitions/".length());
Model model = definitions.get(defName);
Example example = ExampleBuilder.fromModel(defName, model, definitions, new HashSet<String>());
replaceNullWithStringExample(example);
String jsonExample = Json.pretty(example);
try {
org.json.JSONObject json = new org.json.JSONObject(jsonExample);
SequenceUtils.listJson(json, parameterJsonPathMapping);
} catch (JSONException e) {
log.error("Error occurred while generating json mapping for the definition", e);
}
}
}
}
if (parameter instanceof QueryParameter) {
String type = ((QueryParameter) parameter).getType();
queryParameters.put(name, type);
}
}
// populates body parameter json paths and query parameters to generate api sequence parameters
populateParametersFromOperation(operation, definitions, parameterJsonPathMapping, queryParameters);
Map<String, String> payloadSequence = createPayloadFacXMLForOperation(parameterJsonPathMapping, queryParameters, namespace, SOAPToRESTConstants.EMPTY_STRING, operationId, definitions);
try {
String[] propAndArgElements = getPropertyAndArgElementsForSequence(parameterJsonPathMapping, queryParameters);
if (log.isDebugEnabled()) {
log.debug("properties string for the generated sequence: " + propAndArgElements[0]);
log.debug("arguments string for the generated sequence: " + propAndArgElements[1]);
}
org.json.simple.JSONArray arraySequenceElements = new org.json.simple.JSONArray();
// gets array elements for the sequence to be used
getArraySequenceElements(arraySequenceElements, parameterJsonPathMapping);
Map<String, String> sequenceMap = new HashMap<>();
sequenceMap.put("args", propAndArgElements[0]);
sequenceMap.put("properties", propAndArgElements[1]);
sequenceMap.put("sequence", payloadSequence.get(operationId));
RESTToSOAPMsgTemplate template = new RESTToSOAPMsgTemplate();
String inSequence = template.getMappingInSequence(sequenceMap, operationId, soapAction, namespace, soapNamespace, arraySequenceElements);
String outSequence = template.getMappingOutSequence();
if (isResourceFromWSDL) {
SOAPToRestSequence inSeq = new SOAPToRestSequence(httpMethod.toString().toLowerCase(), pathName, inSequence, Direction.IN);
sequences.add(inSeq);
SOAPToRestSequence outSeq = new SOAPToRestSequence(httpMethod.toString().toLowerCase(), pathName, outSequence, Direction.OUT);
sequences.add(outSeq);
}
} catch (APIManagementException e) {
handleException("Error when generating sequence property and arg elements for soap operation: " + operationId, e);
}
}
}
return sequences;
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property 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;
}
use of org.wso2.carbon.identity.application.common.model.idp.xsd.Property in project carbon-apimgt by wso2.
the class WSDL11SOAPOperationExtractor method getSoapOutputParameterModel.
/**
* Gets swagger output parameter model for a given soap operation
*
* @param bindingOperation soap operation
* @return list of swagger models for the parameters
* @throws APIMgtWSDLException
*/
private List<ModelImpl> getSoapOutputParameterModel(BindingOperation bindingOperation) throws APIMgtWSDLException {
List<ModelImpl> outputParameterModelList = new ArrayList<>();
Operation operation = bindingOperation.getOperation();
if (operation != null) {
Output output = operation.getOutput();
if (output != null) {
Message message = output.getMessage();
if (message != null) {
Map map = message.getParts();
for (Object obj : map.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
Part part = (Part) entry.getValue();
if (part != null) {
if (part.getElementName() != null) {
outputParameterModelList.add(parameterModelMap.get(part.getElementName().getLocalPart()));
} else {
if (part.getTypeName() != null && parameterModelMap.containsKey(part.getTypeName().getLocalPart())) {
outputParameterModelList.add(parameterModelMap.get(part.getTypeName().getLocalPart()));
} else {
ModelImpl model = new ModelImpl();
model.setType(ObjectProperty.TYPE);
model.setName(message.getQName().getLocalPart());
if (getPropertyFromDataType(part.getTypeName().getLocalPart()) instanceof RefProperty) {
RefProperty property = (RefProperty) getPropertyFromDataType(part.getTypeName().getLocalPart());
property.set$ref(SOAPToRESTConstants.Swagger.DEFINITIONS_ROOT + part.getTypeName().getLocalPart());
model.addProperty(part.getName(), property);
} else {
model.addProperty(part.getName(), getPropertyFromDataType(part.getTypeName().getLocalPart()));
}
parameterModelMap.put(model.getName(), model);
outputParameterModelList.add(model);
}
}
}
}
}
}
}
return outputParameterModelList;
}
Aggregations