use of org.wso2.carbon.apimgt.core.models.Function in project carbon-apimgt by wso2.
the class FunctionTrigger method captureEvent.
/**
* Used to observe all the {@link org.wso2.carbon.apimgt.core.models.Event} occurrences
* in an {@link org.wso2.carbon.apimgt.core.api.APIMObservable} object and trigger corresponding function that is
* mapped to the particular {@link org.wso2.carbon.apimgt.core.models.Event} occurred.
* <p>
* This is a specific implementation for
* {@link org.wso2.carbon.apimgt.core.api.EventObserver#captureEvent(Event, String, ZonedDateTime, Map)} method,
* provided by {@link org.wso2.carbon.apimgt.core.impl.FunctionTrigger} which implements
* {@link org.wso2.carbon.apimgt.core.api.EventObserver} interface.
* <p>
* {@inheritDoc}
*
* @see org.wso2.carbon.apimgt.core.impl.EventLogger#captureEvent(Event, String, ZonedDateTime, Map)
*/
@Override
public void captureEvent(Event event, String username, ZonedDateTime eventTime, Map<String, String> metadata) {
List<Function> functions = null;
String jsonPayload = null;
if (event == null) {
throw new IllegalArgumentException("Event must not be null");
}
if (username == null) {
throw new IllegalArgumentException("Username must not be null");
}
if (eventTime == null) {
throw new IllegalArgumentException("Event_time must not be null");
}
if (metadata == null) {
throw new IllegalArgumentException("Payload must not be null");
}
// Add general attributes to payload
metadata.put(APIMgtConstants.FunctionsConstants.EVENT, event.getEventAsString());
metadata.put(APIMgtConstants.FunctionsConstants.COMPONENT, event.getComponent().getComponentAsString());
metadata.put(APIMgtConstants.FunctionsConstants.USERNAME, username);
metadata.put(APIMgtConstants.FunctionsConstants.EVENT_TIME, eventTime.toString());
try {
functions = functionDAO.getUserFunctionsForEvent(username, event);
jsonPayload = new Gson().toJson(metadata);
} catch (APIMgtDAOException e) {
String message = "Error loading functions for event from DB: -event: " + event + " -Username: " + username;
log.error(message, new APIManagementException("Problem invoking 'getUserFunctionsForEvent' method in " + "'FunctionDAO' ", e, ExceptionCodes.APIMGT_DAO_EXCEPTION));
}
if (functions != null && !functions.isEmpty()) {
for (Function function : functions) {
HttpResponse response = null;
try {
response = restCallUtil.postRequest(function.getEndpointURI(), null, null, Entity.json(jsonPayload), MediaType.APPLICATION_JSON_TYPE, Collections.EMPTY_MAP);
} catch (APIManagementException e) {
log.error("Failed to make http request: -function: " + function.getName() + " -endpoint URI: " + function.getEndpointURI() + " -event: " + event + " -Username: " + username, e);
}
if (response != null) {
int responseStatusCode = response.getResponseCode();
// Benefit of integer division used to ensure all possible success response codes covered
if (responseStatusCode / 100 == 2) {
log.info("Function successfully invoked: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
} else {
log.error("Problem invoking function: " + function.getName() + " -event: " + event + " -Username: " + username + " -Response code: " + responseStatusCode);
}
}
}
}
}
use of org.wso2.carbon.apimgt.core.models.Function in project carbon-apimgt by wso2.
the class FunctionDAOImplIT method testUpdateGetUserDeployedFunctions.
@Test
public void testUpdateGetUserDeployedFunctions() throws Exception {
FunctionDAO functionDAO = DAOFactory.getFunctionDAO();
// validate getUserDeployedFunctions() args
try {
functionDAO.getUserDeployedFunctions(null);
Assert.fail("Expected IllegalArgumentException when username is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Username must not be null"));
}
Function function1 = SampleTestObjectCreator.createDefaultFunction();
Function function2 = SampleTestObjectCreator.createAlternativeFunction();
Function function3 = SampleTestObjectCreator.createAlternativeFunction2();
// Validate updateUserDeployedFunctions() args
try {
functionDAO.updateUserDeployedFunctions(null, Arrays.asList(function1, function2));
Assert.fail("Expected IllegalArgumentException when username is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Username must not be null"));
}
try {
functionDAO.updateUserDeployedFunctions(ADMIN, null);
Assert.fail("Expected IllegalArgumentException when function list is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Functions(List) must not be null"));
}
functionDAO.updateUserDeployedFunctions(ADMIN, Arrays.asList(function1, function2));
List<Function> functionListFromDB = functionDAO.getUserDeployedFunctions(ADMIN);
Assert.assertEquals(functionListFromDB.size(), 2);
Assert.assertTrue(functionListFromDB.contains(function1));
Assert.assertTrue(functionListFromDB.contains(function2));
functionDAO.updateUserDeployedFunctions(ADMIN, Arrays.asList(function1, function3));
List<Function> functionListFromDBUpdated = functionDAO.getUserDeployedFunctions(ADMIN);
Assert.assertEquals(functionListFromDBUpdated.size(), 2);
Assert.assertTrue(functionListFromDBUpdated.contains(function1));
Assert.assertTrue(functionListFromDBUpdated.contains(function3));
Assert.assertFalse(functionListFromDBUpdated.contains(function2));
}
use of org.wso2.carbon.apimgt.core.models.Function in project carbon-apimgt by wso2.
the class FunctionDAOImplIT method testAddGetDeleteEventFunctionMapping.
@Test
public void testAddGetDeleteEventFunctionMapping() throws Exception {
FunctionDAO functionDAO = DAOFactory.getFunctionDAO();
Function function1 = SampleTestObjectCreator.createDefaultFunction();
Function function2 = SampleTestObjectCreator.createAlternativeFunction();
Function function3 = SampleTestObjectCreator.createAlternativeFunction2();
functionDAO.updateUserDeployedFunctions(ADMIN, Arrays.asList(function1, function2, function3));
try {
functionDAO.addEventFunctionMapping(null, Event.API_CREATION, function1.getName());
Assert.fail("Expected IllegalArgumentException when username is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Username must not be null"));
}
try {
functionDAO.addEventFunctionMapping(ADMIN, null, function1.getName());
Assert.fail("Expected IllegalArgumentException when Event is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Event must not be null"));
}
try {
functionDAO.addEventFunctionMapping(ADMIN, Event.API_CREATION, null);
Assert.fail("Expected IllegalArgumentException when function name is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Function name must not be null"));
}
functionDAO.addEventFunctionMapping(ADMIN, Event.API_CREATION, function1.getName());
functionDAO.addEventFunctionMapping(ADMIN, Event.API_UPDATE, function1.getName());
functionDAO.addEventFunctionMapping(ADMIN, Event.APP_CREATION, function2.getName());
functionDAO.addEventFunctionMapping(ADMIN, Event.APP_MODIFICATION, function2.getName());
functionDAO.addEventFunctionMapping(ADMIN, Event.API_CREATION, function3.getName());
functionDAO.addEventFunctionMapping(ADMIN, Event.APP_CREATION, function3.getName());
// Validate getTriggersForUserFunction() args
try {
functionDAO.getTriggersForUserFunction(null, function3.getName());
Assert.fail("Expected IllegalArgumentException when username is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Username must not be null"));
}
try {
functionDAO.getTriggersForUserFunction(ADMIN, null);
Assert.fail("Expected IllegalArgumentException when function name is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Function name must not be null"));
}
// Check events for functions
List<Event> eventsFromDB = functionDAO.getTriggersForUserFunction(ADMIN, function3.getName());
Assert.assertEquals(eventsFromDB.size(), 2);
Assert.assertTrue(eventsFromDB.get(0).equals(Event.API_CREATION) || eventsFromDB.get(0).equals(Event.APP_CREATION));
Assert.assertTrue(eventsFromDB.get(1).equals(Event.API_CREATION) || eventsFromDB.get(1).equals(Event.APP_CREATION));
// Validate getUserFunctionsForEvent() args
try {
functionDAO.getUserFunctionsForEvent(null, Event.API_UPDATE);
Assert.fail("Expected IllegalArgumentException when username is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Username must not be null"));
}
try {
functionDAO.getUserFunctionsForEvent(ADMIN, null);
Assert.fail("Expected IllegalArgumentException when Event is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Event must not be null"));
}
// Check functions for events
List<Function> functionsForAPIUpdateFromDB = functionDAO.getUserFunctionsForEvent(ADMIN, Event.API_UPDATE);
Assert.assertEquals(functionsForAPIUpdateFromDB.size(), 1);
Assert.assertTrue(functionsForAPIUpdateFromDB.get(0).equals(function1));
List<Function> functionsForAPICreateFromDB = functionDAO.getUserFunctionsForEvent(ADMIN, Event.API_CREATION);
Assert.assertEquals(functionsForAPICreateFromDB.size(), 2);
Assert.assertTrue(functionsForAPICreateFromDB.get(0).equals(function1) || functionsForAPICreateFromDB.get(0).equals(function3));
Assert.assertTrue(functionsForAPICreateFromDB.get(1).equals(function1) || functionsForAPICreateFromDB.get(1).equals(function3));
// Validate deleteEventFunctionMapping() args
try {
functionDAO.deleteEventFunctionMapping(null, Event.API_CREATION, function1.getName());
Assert.fail("Expected IllegalArgumentException when username is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Username must not be null"));
}
try {
functionDAO.deleteEventFunctionMapping(ADMIN, null, function1.getName());
Assert.fail("Expected IllegalArgumentException when Event is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Event must not be null"));
}
try {
functionDAO.deleteEventFunctionMapping(ADMIN, Event.API_CREATION, null);
Assert.fail("Expected IllegalArgumentException when function name is null.");
} catch (IllegalArgumentException e) {
Assert.assertTrue(e.getMessage().contains("Function name must not be null"));
}
// Check deletion
functionDAO.deleteEventFunctionMapping(ADMIN, Event.API_CREATION, function3.getName());
List<Function> functionsForAPICreateFromDBAfterDeletion = functionDAO.getUserFunctionsForEvent(ADMIN, Event.API_CREATION);
Assert.assertEquals(functionsForAPICreateFromDBAfterDeletion.size(), 1);
Assert.assertEquals(functionsForAPICreateFromDBAfterDeletion.get(0), function1);
}
use of org.wso2.carbon.apimgt.core.models.Function in project ballerina by ballerina-lang.
the class SignatureHelpUtil method getSignatureInformation.
/**
* Get the signature information for the given Ballerina function.
*
* @param bInvokableSymbol BLang Invokable symbol
* @param signatureContext Signature operation context
* @return {@link SignatureInformation} Signature information for the function
*/
private static SignatureInformation getSignatureInformation(BInvokableSymbol bInvokableSymbol, TextDocumentServiceContext signatureContext) {
List<ParameterInformation> parameterInformationList = new ArrayList<>();
SignatureInformation signatureInformation = new SignatureInformation();
SignatureInfoModel signatureInfoModel = getSignatureInfoModel(bInvokableSymbol, signatureContext);
String functionName = bInvokableSymbol.getName().getValue();
// Join the function parameters to generate the function's signature
String paramsJoined = signatureInfoModel.getParameterInfoModels().stream().map(parameterInfoModel -> {
// For each of the parameters, create a parameter info instance
ParameterInformation parameterInformation = new ParameterInformation(parameterInfoModel.paramValue, parameterInfoModel.description);
parameterInformationList.add(parameterInformation);
return parameterInfoModel.toString();
}).collect(Collectors.joining(", "));
signatureInformation.setLabel(functionName + "(" + paramsJoined + ")");
signatureInformation.setParameters(parameterInformationList);
signatureInformation.setDocumentation(signatureInfoModel.signatureDescription);
return signatureInformation;
}
use of org.wso2.carbon.apimgt.core.models.Function in project ballerina by ballerina-lang.
the class TestAnnotationProcessor method process.
@Override
public void process(FunctionNode functionNode, List<AnnotationAttachmentNode> annotations) {
// to avoid processing those, we have to have below check.
if (!suite.getSuiteName().equals(functionNode.getPosition().getSource().getPackageName())) {
return;
}
// traverse through the annotations of this function
for (AnnotationAttachmentNode attachmentNode : annotations) {
String annotationName = attachmentNode.getAnnotationName().getValue();
String functionName = functionNode.getName().getValue();
if (BEFORE_SUITE_ANNOTATION_NAME.equals(annotationName)) {
suite.addBeforeSuiteFunction(functionName);
} else if (AFTER_SUITE_ANNOTATION_NAME.equals(annotationName)) {
suite.addAfterSuiteFunction(functionName);
} else if (BEFORE_EACH_ANNOTATION_NAME.equals(annotationName)) {
suite.addBeforeEachFunction(functionName);
} else if (AFTER_EACH_ANNOTATION_NAME.equals(annotationName)) {
suite.addAfterEachFunction(functionName);
} else if (MOCK_ANNOTATION_NAME.equals(annotationName)) {
String[] vals = new String[2];
// If package property not present the package is .
// TODO: when default values are supported in annotation struct we can remove this
vals[0] = ".";
if (attachmentNode.getExpression() instanceof BLangRecordLiteral) {
List<BLangRecordLiteral.BLangRecordKeyValue> attributes = ((BLangRecordLiteral) attachmentNode.getExpression()).getKeyValuePairs();
attributes.forEach(attributeNode -> {
String name = attributeNode.getKey().toString();
String value = attributeNode.getValue().toString();
if (PACKAGE.equals(name)) {
vals[0] = value;
} else if (FUNCTION.equals(name)) {
vals[1] = value;
}
});
suite.addMockFunction(vals[0] + MOCK_ANNOTATION_DELIMITER + vals[1], functionName);
}
} else if (TEST_ANNOTATION_NAME.equals(annotationName)) {
Test test = new Test();
test.setTestName(functionName);
AtomicBoolean shouldSkip = new AtomicBoolean();
AtomicBoolean groupsFound = new AtomicBoolean();
List<String> groups = registry.getGroups();
boolean shouldIncludeGroups = registry.shouldIncludeGroups();
if (attachmentNode.getExpression() instanceof BLangRecordLiteral) {
List<BLangRecordLiteral.BLangRecordKeyValue> attributes = ((BLangRecordLiteral) attachmentNode.getExpression()).getKeyValuePairs();
attributes.forEach(attributeNode -> {
String name = attributeNode.getKey().toString();
// Check if enable property is present in the annotation
if (TEST_ENABLE_ANNOTATION_NAME.equals(name) && "false".equals(attributeNode.getValue().toString())) {
// If enable is false, disable the test, no further processing is needed
shouldSkip.set(true);
return;
}
// Check whether user has provided a group list
if (groups != null && !groups.isEmpty()) {
// check if groups attribute is present in the annotation
if (GROUP_ANNOTATION_NAME.equals(name)) {
if (attributeNode.getValue() instanceof BLangArrayLiteral) {
BLangArrayLiteral values = (BLangArrayLiteral) attributeNode.getValue();
boolean isGroupPresent = isGroupAvailable(groups, values.exprs.stream().map(node -> node.toString()).collect(Collectors.toList()));
if (shouldIncludeGroups) {
// include only if the test belong to one of these groups
if (!isGroupPresent) {
// skip the test if this group is not defined in this test
shouldSkip.set(true);
return;
}
} else {
// exclude only if the test belong to one of these groups
if (isGroupPresent) {
// skip if this test belongs to one of the excluded groups
shouldSkip.set(true);
return;
}
}
groupsFound.set(true);
}
}
}
if (VALUE_SET_ANNOTATION_NAME.equals(name)) {
test.setDataProvider(attributeNode.getValue().toString());
}
if (BEFORE_FUNCTION.equals(name)) {
test.setBeforeTestFunction(attributeNode.getValue().toString());
}
if (AFTER_FUNCTION.equals(name)) {
test.setAfterTestFunction(attributeNode.getValue().toString());
}
if (DEPENDS_ON_FUNCTIONS.equals(name)) {
if (attributeNode.getValue() instanceof BLangArrayLiteral) {
BLangArrayLiteral values = (BLangArrayLiteral) attributeNode.getValue();
values.exprs.stream().map(node -> node.toString()).forEach(test::addDependsOnTestFunction);
}
}
});
}
if (groups != null && !groups.isEmpty() && !groupsFound.get() && shouldIncludeGroups) {
// if the user has asked to run only a specific list of groups and this test doesn't have
// that group, we should skip the test
shouldSkip.set(true);
}
if (!shouldSkip.get()) {
suite.addTests(test);
}
} else {
// disregard this annotation
}
}
}
Aggregations