Search in sources :

Example 46 with VariablesMap

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());
}
Also used : VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) UserType(com.evolveum.midpoint.xml.ns._public.common.common_3.UserType) Test(org.testng.annotations.Test) AbstractInternalModelIntegrationTest(com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)

Example 47 with VariablesMap

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.");
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) ArrayList(java.util.ArrayList) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) URI(java.net.URI) HttpHost(org.apache.http.HttpHost) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpClient(org.apache.http.client.HttpClient) AuthScope(org.apache.http.auth.AuthScope) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse)

Example 48 with VariablesMap

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());
}
Also used : Date(java.util.Date) Autowired(org.springframework.beans.factory.annotation.Autowired) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) ModelExpressionThreadLocalHolder(com.evolveum.midpoint.model.common.expression.ModelExpressionThreadLocalHolder) com.evolveum.midpoint.util.exception(com.evolveum.midpoint.util.exception) StringUtils(org.apache.commons.lang3.StringUtils) ExpressionConstants(com.evolveum.midpoint.schema.constants.ExpressionConstants) Collections.singletonList(java.util.Collections.singletonList) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) DOMUtil(com.evolveum.midpoint.util.DOMUtil) Transport(com.evolveum.midpoint.notifications.api.transports.Transport) TransportUtil(com.evolveum.midpoint.transport.impl.TransportUtil) PrismValueDeltaSetTriple(com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple) MiscSchemaUtil(com.evolveum.midpoint.schema.util.MiscSchemaUtil) URI(java.net.URI) TransportSupport(com.evolveum.midpoint.notifications.api.transports.TransportSupport) Collections.emptyList(java.util.Collections.emptyList) Task(com.evolveum.midpoint.task.api.Task) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) MutablePrismPropertyDefinition(com.evolveum.midpoint.prism.MutablePrismPropertyDefinition) List(java.util.List) ExpressionFactory(com.evolveum.midpoint.repo.common.expression.ExpressionFactory) QName(javax.xml.namespace.QName) CredentialsProvider(org.apache.http.client.CredentialsProvider) NotNull(org.jetbrains.annotations.NotNull) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) com.evolveum.midpoint.xml.ns._public.common.common_3(com.evolveum.midpoint.xml.ns._public.common.common_3) SchemaConstants(com.evolveum.midpoint.schema.constants.SchemaConstants) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Trace(com.evolveum.midpoint.util.logging.Trace) ObjectUtils.defaultIfNull(org.apache.commons.lang3.ObjectUtils.defaultIfNull) ArrayList(java.util.ArrayList) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) HttpClient(org.apache.http.client.HttpClient) PrismContext(com.evolveum.midpoint.prism.PrismContext) Qualifier(org.springframework.beans.factory.annotation.Qualifier) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) HttpUtil(com.evolveum.midpoint.notifications.impl.util.HttpUtil) RepositoryService(com.evolveum.midpoint.repo.api.RepositoryService) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) Event(com.evolveum.midpoint.notifications.api.events.Event) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) Expression(com.evolveum.midpoint.repo.common.expression.Expression) IOException(java.io.IOException) ExpressionEvaluationContext(com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) HttpStatus(org.springframework.http.HttpStatus) Message(com.evolveum.midpoint.notifications.api.transports.Message) URLEncoder(java.net.URLEncoder) Component(org.springframework.stereotype.Component) Protector(com.evolveum.midpoint.prism.crypto.Protector) AuthScope(org.apache.http.auth.AuthScope) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) HttpHost(org.apache.http.HttpHost) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) MutablePrismPropertyDefinition(com.evolveum.midpoint.prism.MutablePrismPropertyDefinition) PrismPropertyDefinition(com.evolveum.midpoint.prism.PrismPropertyDefinition) ExpressionEvaluationContext(com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext) QName(javax.xml.namespace.QName) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue) NotNull(org.jetbrains.annotations.NotNull)

Example 49 with VariablesMap

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;
}
Also used : Reader(java.io.Reader) CSVParser(org.apache.commons.csv.CSVParser) CSVFormat(org.apache.commons.csv.CSVFormat) VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) CSVRecord(org.apache.commons.csv.CSVRecord)

Example 50 with VariablesMap

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();
    }
}
Also used : VariablesMap(com.evolveum.midpoint.schema.expression.VariablesMap) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) ObjectNotFoundException(com.evolveum.midpoint.util.exception.ObjectNotFoundException) CommonException(com.evolveum.midpoint.util.exception.CommonException)

Aggregations

VariablesMap (com.evolveum.midpoint.schema.expression.VariablesMap)166 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)48 ExpressionEvaluationContext (com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext)30 Test (org.testng.annotations.Test)28 Task (com.evolveum.midpoint.task.api.Task)23 NotNull (org.jetbrains.annotations.NotNull)23 QName (javax.xml.namespace.QName)15 AbstractInternalModelIntegrationTest (com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)12 Source (com.evolveum.midpoint.repo.common.expression.Source)12 AbstractModelCommonTest (com.evolveum.midpoint.model.common.AbstractModelCommonTest)11 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)11 ExpressionFactory (com.evolveum.midpoint.repo.common.expression.ExpressionFactory)10 Trace (com.evolveum.midpoint.util.logging.Trace)10 TraceManager (com.evolveum.midpoint.util.logging.TraceManager)10 ObjectFilter (com.evolveum.midpoint.prism.query.ObjectFilter)9 ObjectQuery (com.evolveum.midpoint.prism.query.ObjectQuery)9 com.evolveum.midpoint.xml.ns._public.common.common_3 (com.evolveum.midpoint.xml.ns._public.common.common_3)9 PrismPropertyValue (com.evolveum.midpoint.prism.PrismPropertyValue)8 ExpressionType (com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType)8 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)7