aboutsummaryrefslogtreecommitdiff
path: root/src/org/traccar/command/StringCommandTemplate.java
blob: 12470d44105c9bab2d68570486c3b4675bf7b562 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package org.traccar.command;

import org.traccar.database.ActiveDevice;

import java.util.HashMap;
import java.util.Map;

public class StringCommandTemplate<T extends GpsCommand> implements CommandTemplate<T> {

    private String messageTemplate;
    private Map<Class<?>, CommandValueConversion> converters = new HashMap<Class<?>, CommandValueConversion>();

    public StringCommandTemplate(String template, Object... replacements) {
        this.messageTemplate = String.format(template, replacements);
    }

    @Override
    public Object applyTo(ActiveDevice activeDevice, T command) {
        String currentMessage = messageTemplate;
        currentMessage = this.replace(currentMessage, GpsCommand.UNIQUE_ID, activeDevice.getUniqueId());

        Map<String, Object> replacements = command.getReplacements();

        for (Map.Entry<String, Object> entry : replacements.entrySet()) {
            currentMessage = this.replace(currentMessage, entry.getKey(), entry.getValue());
        }

        return currentMessage;
    }

    public CommandTemplate addConverter(Class<?> type, CommandValueConversion converter) {
        converters.put(type, converter);
        return this;
    }

    protected CommandValueConversion getConverter(Class<?> type) {
        return converters.containsKey(type) ? converters.get(type) : idConverter();
    }

    private CommandValueConversion idConverter() {
        return new CommandValueConversion() {
            @Override
            public String convert(Object value) {
                return value.toString();
            }
        };
    }

    private String replace(String currentMessage, String key, Object value) {
        String replacementValue = getConverter(value.getClass()).convert(value);
        return currentMessage.replace("[" + key + "]", replacementValue);
    }

}