2 * Copyright (c) 2010-2020 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 org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.openhab.core.io.net.exec.ExecUtil;
18 import org.openhab.core.transform.TransformationException;
19 import org.openhab.core.transform.TransformationService;
20 import org.osgi.service.component.annotations.Activate;
21 import org.osgi.service.component.annotations.Component;
22 import org.osgi.service.component.annotations.Reference;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
27 * The implementation of {@link TransformationService} which transforms the
28 * input by command line.
30 * @author Pauli Anttila - Initial contribution
31 * @author Jan N. Klug - added command whitelist service
34 @Component(property = { "smarthome.transform=EXEC" })
35 public class ExecTransformationService implements TransformationService {
36 private final Logger logger = LoggerFactory.getLogger(ExecTransformationService.class);
37 private final ExecTransformationWhitelistWatchService execTransformationWhitelistWatchService;
40 public ExecTransformationService(
41 @Reference ExecTransformationWhitelistWatchService execTransformationWhitelistWatchService) {
42 this.execTransformationWhitelistWatchService = execTransformationWhitelistWatchService;
46 * Transforms the input <code>source</code> by the command line.
48 * @param commandLine the command to execute. Command line should contain %s string, which will be replaced by the
50 * @param source the input to transform
53 public @Nullable String transform(String commandLine, String source) throws TransformationException {
54 if (commandLine == null || source == null) {
55 throw new TransformationException("the given parameters 'commandLine' and 'source' must not be null");
58 if (!execTransformationWhitelistWatchService.isWhitelisted(commandLine)) {
59 logger.warn("Tried to execute '{}', but it is not contained in whitelist.", commandLine);
62 logger.debug("about to transform '{}' by the commandline '{}'", source, commandLine);
64 long startTime = System.currentTimeMillis();
66 String formattedCommandLine = String.format(commandLine, source);
67 String result = ExecUtil.executeCommandLineAndWaitResponse(formattedCommandLine, 5000);
68 logger.trace("command line execution elapsed {} ms", System.currentTimeMillis() - startTime);