ParameterToolMerger.java

package org.wikimedia.discovery.cirrus.updater.common.config;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.flink.api.java.utils.ParameterTool;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import lombok.experimental.UtilityClass;

@UtilityClass
@SuppressWarnings("HideUtilityClassConstructor")
@SuppressFBWarnings(
        value = "HideUtilityClassConstructor",
        justification = "lombok takes care of that")
public class ParameterToolMerger {

    public static ParameterTool fromDefaultsWithOverrides(String[] args) throws IOException {
        return fromDefaultsWithOverrides("/cirrus-streaming-updater-producer.properties", args);
    }

    public static ParameterTool fromDefaultsWithOverrides(String defaultsResourceName, String[] args)
            throws IOException {
        final List<ParameterTool> sources = new ArrayList<>(3);
        if (defaultsResourceName != null) {
            try (InputStream inputStream =
                    ParameterToolMerger.class.getResourceAsStream(defaultsResourceName)) {
                if (inputStream == null) {
                    throw new IllegalArgumentException("Cannot find " + defaultsResourceName);
                }
                sources.add(ParameterTool.fromPropertiesFile(inputStream));
            }
        }
        if (args.length > 0) {
            if (!args[0].startsWith("--")) {
                if (args[0].contains(":/")) {
                    sources.add(ParameterTool.fromPropertiesFile(URI.create(args[0]).toURL().openStream()));
                } else {
                    final File path = new File(args[0]);
                    if (!path.exists()) {
                        throw new IllegalArgumentException("Cannot find " + path);
                    }
                    sources.add(ParameterTool.fromPropertiesFile(path));
                }
                args = Arrays.copyOfRange(args, 1, args.length);
            }
            sources.add(ParameterTool.fromArgs(args));
        }
        return sources.stream()
                .reduce(ParameterTool.fromMap(Collections.emptyMap()), ParameterTool::mergeWith);
    }
}