2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.transform.exec.internal;
15 import java.time.Duration;
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.openhab.core.io.net.exec.ExecUtil;
20 import org.openhab.core.transform.TransformationException;
21 import org.openhab.core.transform.TransformationService;
22 import org.osgi.service.component.annotations.Activate;
23 import org.osgi.service.component.annotations.Component;
24 import org.osgi.service.component.annotations.Reference;
25 import org.slf4j.Logger;
26 import org.slf4j.LoggerFactory;
29 * The implementation of {@link TransformationService} which transforms the
30 * input by command line.
32 * @author Pauli Anttila - Initial contribution
33 * @author Jan N. Klug - added command whitelist service
36 @Component(property = { "openhab.transform=EXEC" })
37 public class ExecTransformationService implements TransformationService {
38 private final Logger logger = LoggerFactory.getLogger(ExecTransformationService.class);
39 private final ExecTransformationWhitelistWatchService execTransformationWhitelistWatchService;
42 public ExecTransformationService(
43 @Reference ExecTransformationWhitelistWatchService execTransformationWhitelistWatchService) {
44 this.execTransformationWhitelistWatchService = execTransformationWhitelistWatchService;
48 * Transforms the input <code>source</code> by the command line.
50 * @param commandLine the command to execute. Command line should contain %s string, which will be replaced by the
52 * @param source the input to transform
55 public @Nullable String transform(String commandLine, String source) throws TransformationException {
56 if (commandLine == null || source == null) {
57 throw new TransformationException("the given parameters 'commandLine' and 'source' must not be null");
60 if (!execTransformationWhitelistWatchService.isWhitelisted(commandLine)) {
61 logger.warn("Tried to execute '{}', but it is not contained in whitelist.", commandLine);
64 logger.debug("about to transform '{}' by the commandline '{}'", source, commandLine);
66 long startTime = System.currentTimeMillis();
68 String formattedCommandLine = String.format(commandLine, source);
69 String result = ExecUtil.executeCommandLineAndWaitResponse(Duration.ofSeconds(5),
70 formattedCommandLine.split(" "));
71 logger.trace("command line execution elapsed {} ms", System.currentTimeMillis() - startTime);