use of com.evolveum.midpoint.schema.expression.VariablesMap in project midpoint by Evolveum.
the class TestModelExpressions method testGetUserByOid.
@Test
public void testGetUserByOid() throws Exception {
// GIVEN
PrismObject<UserType> chef = repositoryService.getObject(UserType.class, CHEF_OID, null, getTestOperationResult());
VariablesMap variables = createVariables(ExpressionConstants.VAR_USER, chef, chef.getDefinition());
// WHEN, THEN
assertExecuteScriptExpressionString(variables, chef.asObjectable().getName().getOrig());
}
use of com.evolveum.midpoint.schema.expression.VariablesMap in project midpoint by Evolveum.
the class LegacySimpleSmsTransport method send.
@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
result.addParam("message subject", message.getSubject());
SystemConfigurationType systemConfiguration = TransportUtil.getSystemConfiguration(repositoryService, result);
if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null) {
String msg = "No notifications are configured. SMS notification to " + message.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
String smsConfigName = StringUtils.substringAfter(transportName, NAME + ":");
SmsConfigurationType found = null;
for (SmsConfigurationType smsConfigurationType : systemConfiguration.getNotificationConfiguration().getSms()) {
if (StringUtils.isEmpty(smsConfigName) && smsConfigurationType.getName() == null || StringUtils.isNotEmpty(smsConfigName) && smsConfigName.equals(smsConfigurationType.getName())) {
found = smsConfigurationType;
break;
}
}
if (found == null) {
String msg = "SMS configuration '" + smsConfigName + "' not found. SMS notification to " + message.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
SmsConfigurationType smsConfigurationType = found;
String logToFile = smsConfigurationType.getLogToFile();
if (logToFile != null) {
TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
}
String file = smsConfigurationType.getRedirectToFile();
int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(smsConfigurationType);
List<String> allowedRecipientTo = new ArrayList<>();
List<String> forbiddenRecipientTo = new ArrayList<>();
if (optionsForFilteringRecipient != 0) {
TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, message.getTo(), smsConfigurationType, task, result, expressionFactory, MiscSchemaUtil.getExpressionProfile(), LOGGER);
if (file != null) {
if (!forbiddenRecipientTo.isEmpty()) {
message.setTo(forbiddenRecipientTo);
writeToFile(message, file, null, emptyList(), null, result);
}
message.setTo(allowedRecipientTo);
}
} else if (file != null) {
writeToFile(message, file, null, emptyList(), null, result);
return;
}
if (smsConfigurationType.getGateway().isEmpty()) {
String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
String from;
if (message.getFrom() != null) {
from = message.getFrom();
} else if (smsConfigurationType.getDefaultFrom() != null) {
from = smsConfigurationType.getDefaultFrom();
} else {
from = "";
}
if (message.getTo().isEmpty()) {
if (optionsForFilteringRecipient != 0) {
String msg = "After recipient validation there is no recipient to send the notification to.";
LOGGER.debug(msg);
result.recordSuccess();
} else {
String msg = "There is no recipient to send the notification to.";
LOGGER.warn(msg);
result.recordWarning(msg);
}
return;
}
List<String> to = message.getTo();
assert to.size() > 0;
for (SmsGatewayConfigurationType smsGatewayConfigurationType : smsConfigurationType.getGateway()) {
OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
try {
VariablesMap variables = getDefaultVariables(from, to, message);
HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), null);
String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result);
String proxyHost = smsGatewayConfigurationType.getProxyHost();
String proxyPort = smsGatewayConfigurationType.getProxyPort();
LOGGER.debug("Sending SMS to URL {} via proxy host {} and port {} (method {})", url, proxyHost, proxyPort, method);
if (url == null) {
throw new IllegalArgumentException("No URL specified");
}
List<String> headersList = evaluateExpressionsChecked(smsGatewayConfigurationType.getHeadersExpression(), variables, "sms gateway request headers", task, result);
LOGGER.debug("Using request headers:\n{}", headersList);
String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(), StandardCharsets.ISO_8859_1.name());
String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables, "sms gateway request body", task, result);
LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);
if (smsGatewayConfigurationType.getLogToFile() != null) {
TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(), formatToFile(message, url, headersList, body), LOGGER);
}
if (smsGatewayConfigurationType.getRedirectToFile() != null) {
writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body, resultForGateway);
result.computeStatus();
return;
} else {
HttpClientBuilder builder = HttpClientBuilder.create();
String username = smsGatewayConfigurationType.getUsername();
ProtectedStringType password = smsGatewayConfigurationType.getPassword();
CredentialsProvider provider = new BasicCredentialsProvider();
if (username != null) {
String plainPassword = password != null ? protector.decryptString(password) : null;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword);
provider.setCredentials(AuthScope.ANY, credentials);
builder = builder.setDefaultCredentialsProvider(provider);
}
String proxyUsername = smsGatewayConfigurationType.getProxyUsername();
ProtectedStringType proxyPassword = smsGatewayConfigurationType.getProxyPassword();
if (StringUtils.isNotBlank(proxyHost)) {
HttpHost proxy;
if (StringUtils.isNotBlank(proxyPort) && isInteger(proxyPort)) {
int port = Integer.parseInt(proxyPort);
proxy = new HttpHost(proxyHost, port);
} else {
proxy = new HttpHost(proxyHost);
}
if (StringUtils.isNotBlank(proxyUsername)) {
String plainProxyPassword = proxyPassword != null ? protector.decryptString(proxyPassword) : null;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, plainProxyPassword);
provider.setCredentials(new AuthScope(proxy), credentials);
}
builder = builder.setDefaultCredentialsProvider(provider);
builder = builder.setProxy(proxy);
}
HttpClient client = builder.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpUtil.toHttpMethod(method));
setHeaders(request, headersList);
if (body != null) {
request.getBody().write(body.getBytes(encoding));
}
ClientHttpResponse response = request.execute();
LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText());
}
LOGGER.debug("Message sent successfully to {} via gateway {}.", message.getTo(), smsGatewayConfigurationType.getName());
resultForGateway.recordSuccess();
result.recordSuccess();
return;
}
} catch (Throwable t) {
String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
LoggingUtils.logException(LOGGER, msg, t);
resultForGateway.recordFatalError(msg, t);
}
}
LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}
use of com.evolveum.midpoint.schema.expression.VariablesMap in project midpoint by Evolveum.
the class LegacySimpleSmsTransport method evaluateExpression.
// A little hack: for single-value cases we always return single-item list (even if the returned value is null)
@NotNull
private List<String> evaluateExpression(ExpressionType expressionType, VariablesMap VariablesMap, boolean multipleValues, String shortDesc, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException {
if (expressionType == null) {
return multipleValues ? emptyList() : singletonList(null);
}
QName resultName = new QName(SchemaConstants.NS_C, "result");
MutablePrismPropertyDefinition<String> resultDef = prismContext.definitionFactory().createPropertyDefinition(resultName, DOMUtil.XSD_STRING);
if (multipleValues) {
resultDef.setMaxOccurs(-1);
}
Expression<PrismPropertyValue<String>, PrismPropertyDefinition<String>> expression = expressionFactory.makeExpression(expressionType, resultDef, MiscSchemaUtil.getExpressionProfile(), shortDesc, task, result);
ExpressionEvaluationContext params = new ExpressionEvaluationContext(null, VariablesMap, shortDesc, task);
PrismValueDeltaSetTriple<PrismPropertyValue<String>> exprResult = ModelExpressionThreadLocalHolder.evaluateExpressionInContext(expression, params, task, result);
if (!multipleValues) {
if (exprResult.getZeroSet().size() > 1) {
throw new SystemException("Invalid number of return values (" + exprResult.getZeroSet().size() + "), expected at most 1.");
} else if (exprResult.getZeroSet().isEmpty()) {
return singletonList(null);
} else {
// single-valued response is treated below
}
}
return exprResult.getZeroSet().stream().map(ppv -> ppv.getValue()).collect(Collectors.toList());
}
use of com.evolveum.midpoint.schema.expression.VariablesMap in project midpoint by Evolveum.
the class ImportController method parseColumnsAsVariablesFromFile.
public List<VariablesMap> parseColumnsAsVariablesFromFile(ReportDataType reportData) throws IOException {
List<String> headers = new ArrayList<>();
Reader reader = Files.newBufferedReader(Paths.get(reportData.getFilePath()));
CSVFormat csvFormat = support.createCsvFormat();
if (compiledCollection != null) {
Class<ObjectType> type = compiledCollection.getTargetClass(reportService.getPrismContext());
if (type == null) {
throw new IllegalArgumentException("Couldn't define type of imported objects");
}
PrismObjectDefinition<?> def = reportService.getPrismContext().getSchemaRegistry().findItemDefinitionByCompileTimeClass(type, PrismObjectDefinition.class);
for (GuiObjectColumnType column : columns) {
Validate.notNull(column.getName(), "Name of column is null");
String label = GenericSupport.getLabel(column, def, localizationService);
headers.add(label);
}
} else {
csvFormat = csvFormat.withFirstRecordAsHeader();
}
if (support.isHeader()) {
if (!headers.isEmpty()) {
String[] arrayHeader = new String[headers.size()];
arrayHeader = headers.toArray(arrayHeader);
csvFormat = csvFormat.withHeader(arrayHeader);
}
csvFormat = csvFormat.withSkipHeaderRecord(true);
} else {
if (headers.isEmpty()) {
throw new IllegalArgumentException("Couldn't find headers please " + "define them via view element or write them to csv file and set " + "header element in file format configuration to true.");
}
csvFormat = csvFormat.withSkipHeaderRecord(false);
}
CSVParser csvParser = new CSVParser(reader, csvFormat);
if (headers.isEmpty()) {
headers = csvParser.getHeaderNames();
}
List<VariablesMap> variablesMaps = new ArrayList<>();
for (CSVRecord csvRecord : csvParser) {
VariablesMap variables = new VariablesMap();
for (String name : headers) {
String value;
if (support.isHeader()) {
value = csvRecord.get(name);
} else {
value = csvRecord.get(headers.indexOf(name));
}
if (value != null && value.isEmpty()) {
value = null;
}
if (value != null && value.contains(support.getMultivalueDelimiter())) {
String[] realValues = value.split(support.getMultivalueDelimiter());
variables.put(name, Arrays.asList(realValues), String.class);
} else {
variables.put(name, value, String.class);
}
}
variablesMaps.add(variables);
}
return variablesMaps;
}
use of com.evolveum.midpoint.schema.expression.VariablesMap in project midpoint by Evolveum.
the class ColumnDataConverter method evaluateExportExpressionOverRealValues.
private Collection<? extends PrismValue> evaluateExportExpressionOverRealValues(ExpressionType expression, Object input) {
VariablesMap variables = new VariablesMap();
variables.putAll(parameters);
if (input == null) {
variables.put(ExpressionConstants.VAR_INPUT, null, Object.class);
} else {
variables.put(ExpressionConstants.VAR_INPUT, input, input.getClass());
}
try {
return reportService.evaluateScript(report.asPrismObject(), expression, variables, "value for column (export)", task, result);
} catch (Exception e) {
LOGGER.error("Couldn't execute expression " + expression, e);
return List.of();
}
}
Aggregations