]> git.basschouten.com Git - openhab-addons.git/blob
3a690203b89c3b4171bd17c4eaeee697560e4461
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.http.internal.transform;
14
15 import java.util.Arrays;
16 import java.util.List;
17 import java.util.Optional;
18 import java.util.function.Function;
19 import java.util.stream.Collectors;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.openhab.core.transform.TransformationService;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * The {@link CascadedValueTransformationImpl} implements {@link ValueTransformation} for a cascaded set of
29  * transformations
30  *
31  * @author Jan N. Klug - Initial contribution
32  */
33 @NonNullByDefault
34 public class CascadedValueTransformationImpl implements ValueTransformation {
35     private final Logger logger = LoggerFactory.getLogger(CascadedValueTransformationImpl.class);
36     private final List<ValueTransformation> transformations;
37
38     public CascadedValueTransformationImpl(String transformationString,
39             Function<String, @Nullable TransformationService> transformationServiceSupplier) {
40         List<ValueTransformation> transformations;
41         try {
42             transformations = Arrays.stream(transformationString.split("∩")).filter(s -> !s.isEmpty())
43                     .map(transformation -> new SingleValueTransformation(transformation, transformationServiceSupplier))
44                     .collect(Collectors.toList());
45         } catch (IllegalArgumentException e) {
46             transformations = List.of(NoOpValueTransformation.getInstance());
47             logger.warn("Transformation ignore, failed to parse {}: {}", transformationString, e.getMessage());
48         }
49         this.transformations = transformations;
50     }
51
52     @Override
53     public Optional<String> apply(String value) {
54         Optional<String> valueOptional = Optional.of(value);
55
56         // process all transformations
57         for (ValueTransformation transformation : transformations) {
58             valueOptional = valueOptional.flatMap(transformation::apply);
59         }
60
61         return valueOptional;
62     }
63 }