com.mattc.argus2.io.ListFile.java Source code

Java tutorial

Introduction

Here is the source code for com.mattc.argus2.io.ListFile.java

Source

/*
 * Argus Installer v2 -- A Better School Zip Alternative Copyright (C) 2014 Matthew
 * Crocco
 * 
 * This program is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this
 * program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.mattc.argus2.io;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import com.google.common.base.Function;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.mattc.argus2.Ref;
import com.mattc.argus2.Settings;
import com.mattc.argus2.util.Console;
import com.mattc.argus2.util.IOUtils;

public final class ListFile implements IConfigurableFile<String> {

    private static final File DIR = Ref.getConfigDir();

    private final List<String> defaults = Lists.newArrayList();
    private final List<String> items = Lists.newArrayList();
    private final File linkFile;

    protected ListFile(File file) {
        this.linkFile = file;
        try {
            if (!file.exists()) {
                file.createNewFile();
            } else {
                load();
            }
        } catch (final IOException e) {
            Console.exception(e);
        }
    }

    public ListFile(String file) {
        this(new File(DIR, file.endsWith(".list") ? file : file + ".list"));
    }

    @Override
    public void reload() {
        load(this.linkFile);
    }

    public void load() {
        load(this.linkFile);
    }

    @Override
    public void load(File file) {
        StringWriter writer = null;
        FileReader reader = null;

        try {
            final Splitter splitter = Splitter.onPattern("\r?\n").omitEmptyStrings().trimResults();
            String result = null;
            final char[] buf = new char[1024];
            writer = new StringWriter();
            reader = new FileReader(file);

            for (int c = reader.read(buf); c != -1; c = reader.read(buf)) {
                writer.write(buf, 0, c);
            }

            // Assemble defaults
            result = writer.toString();
            this.defaults.clear();

            // Ensure that Comments are not included.
            for (final String s : splitter.split(result)) {
                if (!s.startsWith("#")) {
                    this.defaults.add(s);
                }
            }
            // --

        } catch (final IOException e) {
            Console.exception(e);
        } finally {
            IOUtils.closeSilently(writer);
            IOUtils.closeSilently(reader);
        }

        this.items.addAll(this.defaults);
        Configs.ensureFilesExist(this);
    }

    public void save(String comment) {
        save(this.linkFile, comment);
    }

    @Override
    public void save(File file, String comment) {
        Configs.ensureFilesExist(this);
        final List<String> newItems = Settings.State.MUTABLE ? this.items : this.defaults;
        FileWriter writer = null;

        try {
            writer = new FileWriter(file, false);

            if (comment != null) {
                Console.info("Writing Comments to " + file.getPath() + "...");
                IOUtils.write(new StringReader(Configs.formatComments(comment, true)), true, writer, false);
            }

            for (final String s : newItems) {
                Console.debug("Writing " + s + "...");
                IOUtils.write(new StringReader(s + System.getProperty("line.separator")), true, writer, false);
            }

        } catch (final IOException e) {
        } finally {
            IOUtils.closeSilently(writer);
        }
    }

    @Override
    public void addItem(String item) {
        this.items.add(item);
    }

    @Override
    public String getItem(String name) {
        if (this.items.indexOf(name) >= 0)
            return this.items.get(this.items.indexOf(name));
        else
            return null;
    }

    @Override
    public boolean removeItem(String item) {
        return this.items.remove(item);
    }

    public String[] getItems() {
        return Arrays.copyOf(this.items.toArray(new String[this.items.size()]), this.items.size());
    }

    public String[] getDefaultItems() {
        return Arrays.copyOf(this.defaults.toArray(new String[this.defaults.size()]), this.defaults.size());
    }

    @Override
    public Iterator<String> getAsIterator() {
        final Set<String> cpy = Sets.newHashSet(this.items);
        return cpy.iterator();
    }

    @Override
    public Enumeration<String> getAsEnumeration() {
        final Set<String> cpy = Sets.newHashSet(this.items);
        return Iterators.asEnumeration(cpy.iterator());
    }

    /**
     * Applies a Function based on the List's items. <br />
     * <br />
     * This does NOT change the list. It simply uses the values as input.
     * 
     * @param func
     */
    public void applyFunction(Function<String, ?> func) {
        final Iterator<String> iter = getAsIterator();

        while (iter.hasNext()) {
            func.apply(iter.next());
        }
    }

    /**
     * Uses a String Function to modify list values. <br />
     * If the function returns null, that item is removed. <br />
     * If the function returns non-null, the modified item replaces the original one.
     * 
     * @param func
     *            String, String Mutator Function
     */
    public void applyMutator(Function<String, String> func) {
        final Iterator<String> iter = getAsIterator();
        this.items.clear();

        while (iter.hasNext()) {
            final String val = func.apply(iter.next());
            if (val != null) {
                this.items.add(val);
            }
        }
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = (prime * result) + ((this.linkFile == null) ? 0 : this.linkFile.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        final ListFile other = (ListFile) obj;
        if (this.linkFile == null) {
            if (other.linkFile != null)
                return false;
        } else if (!this.linkFile.equals(other.linkFile))
            return false;
        return true;
    }

}