All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cdc.util.tools.FileEncoder Maven / Gradle / Ivy

package cdc.util.tools;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cdc.util.cli.AbstractMainSupport;
import cdc.util.cli.FeatureMask;
import cdc.util.cli.OptionEnum;

public final class FileEncoder {
    protected static final Logger LOGGER = LogManager.getLogger(FileEncoder.class);
    private final MainArgs margs;

    public static class MainArgs {
        public File input;
        public String inputCharset;
        public File output;
        public String outputCharset;
        protected final FeatureMask features = new FeatureMask<>();

        public boolean isEnabled(Feature feature) {
            return features.isEnabled(feature);
        }

        public void setEnabled(Feature feature,
                               boolean enabled) {
            features.setEnabled(feature, enabled);
        }

        public void validate() throws ParseException {
            if (input == null && output == null && !isEnabled(Feature.LIST_CHARSETS)) {
                throw new ParseException("input and output must be specified.");
            }
            if (input != null && output == null || input == null && output != null) {
                throw new ParseException("input and output must be specified.");
            }
        }

        /**
         * Enumeration of possible boolean options.
         */
        public enum Feature implements OptionEnum {
            VERBOSE("verbose", "Print messages."),
            LIST_CHARSETS("list-charsets", "List available charsets");

            private final String name;
            private final String description;

            private Feature(String name,
                            String description) {
                this.name = name;
                this.description = description;
            }

            @Override
            public final String getName() {
                return name;
            }

            @Override
            public final String getDescription() {
                return description;
            }
        }
    }

    private FileEncoder(MainArgs margs) {
        this.margs = margs;
    }

    private Reader getInputReader() throws IOException {
        if (margs.inputCharset == null) {
            return new BufferedReader(new InputStreamReader(new FileInputStream(margs.input)));
        } else {
            return new BufferedReader(new InputStreamReader(new FileInputStream(margs.input), margs.inputCharset));
        }
    }

    private Writer getOutputWriter() throws IOException {
        if (margs.outputCharset == null) {
            return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(margs.output)));
        } else {
            return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(margs.output), margs.outputCharset));
        }
    }

    private static String toCharsetName(String charset) {
        return charset == null ? Charset.defaultCharset().name() : charset;
    }

    private void execute() throws IOException {
        if (margs.isEnabled(MainArgs.Feature.LIST_CHARSETS)) {
            for (final String name : Charset.availableCharsets().keySet()) {
                System.out.println(name);
            }
        }

        if (margs.input != null && margs.output != null) {
            if (margs.isEnabled(MainArgs.Feature.VERBOSE)) {
                LOGGER.info("load: " + margs.input + " [" + toCharsetName(margs.inputCharset) + "]");
            }
            try (final Reader in = getInputReader();
                    final Writer out = getOutputWriter()) {
                int c;
                while ((c = in.read()) != -1) {
                    out.write(c);
                }
            }
            if (margs.isEnabled(MainArgs.Feature.VERBOSE)) {
                LOGGER.info("generated: " + margs.output + " [" + toCharsetName(margs.outputCharset) + "]");
            }
        }
    }

    public static void execute(MainArgs margs) throws IOException {
        final FileEncoder instance = new FileEncoder(margs);
        instance.execute();
    }

    public static void main(String[] args) {
        final MainSupport support = new MainSupport();
        support.main(args);
    }

    private static class MainSupport extends AbstractMainSupport {
        private static final String INPUT_CHARSET = "input-charset";
        private static final String OUTPUT_CHARSET = "output-charset";

        public MainSupport() {
            super(FileEncoder.class, LOGGER);
        }

        @Override
        protected String getVersion() {
            return cdc.util.Config.VERSION;
        }

        @Override
        protected void addSpecificOptions(Options options) {
            options.addOption(Option.builder()
                                    .longOpt(INPUT)
                                    .desc("Name of the input file.")
                                    .hasArg()
                                    .build());

            options.addOption(Option.builder()
                                    .longOpt(INPUT_CHARSET)
                                    .desc("Optional name of the input charset.")
                                    .hasArg()
                                    .build());

            options.addOption(Option.builder()
                                    .longOpt(OUTPUT)
                                    .desc("Name of the output file.")
                                    .hasArg()
                                    .build());

            options.addOption(Option.builder()
                                    .longOpt(OUTPUT_CHARSET)
                                    .desc("Optional name of the output charset.")
                                    .hasArg()
                                    .build());
            addNoArgOptions(options, MainArgs.Feature.class);
        }

        @Override
        protected MainArgs analyze(CommandLine cl) throws ParseException {
            final MainArgs margs = new MainArgs();
            margs.input = getValueAsNullOrExistingFile(cl, INPUT, null);
            if (cl.hasOption(INPUT_CHARSET)) {
                margs.inputCharset = cl.getOptionValue(INPUT_CHARSET);
            }
            margs.output = getValueAsFile(cl, OUTPUT, null);
            if (cl.hasOption(OUTPUT_CHARSET)) {
                margs.outputCharset = cl.getOptionValue(OUTPUT_CHARSET);
            }
            setMask(cl, MainArgs.Feature.class, margs.features::setEnabled);
            margs.validate();
            return margs;
        }

        @Override
        protected Void execute(MainArgs margs) throws IOException {
            FileEncoder.execute(margs);
            return null;
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy