xmlconverter.controller.logic.SiteToDir.java Source code

Java tutorial

Introduction

Here is the source code for xmlconverter.controller.logic.SiteToDir.java

Source

/*
 *    Copyright (C) 2016  Artiom Blinvoas
 *
 *   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 xmlconverter.controller.logic;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;
import xmlconverter.items.site.Site;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.log4j.Logger;
import xmlconverter.data.MasterBean;
import xmlconverter.items.site.Panel;

/**
 * This class created directories that are based on data that has been extracted
 * from the given xml. writeDir() writes dirPath that should be created to
 * Set<>. After the end of this method createDir() method is called. createDir()
 * created actually directories based on formated <code>pathName</code>
 *
 */
public class SiteToDir {

    private String os = System.getProperty("os.name");
    private String slash = File.separator;
    //private ArrayList<File> all;
    private final Set<File> pathName = new LinkedHashSet<>();
    private String detection = null, build = null;
    private File home;
    private static Logger log = Logger.getLogger(SiteToDir.class.getName());
    private MasterBean bean;

    /**
     * Takes MasterBean to set some needed variables.
     *
     * @param bean
     */
    public SiteToDir(MasterBean bean) {
        this.bean = bean;
        this.home = bean.getEnvBean().getHome();
    }

    /**
     * This method consists of some nested loops and tries to build correct path
     * for file creation. Each crafted path will be saved to <code>Set<String>
     * pathName</code>. This will avoid duplication if any. The path is crafted
     * manually with given root path and added String values to it
     *
     * After the end of this method <code>createDir()</code> method is called.
     *
     * @param site
     * @throws java.io.IOException
     */
    //Flag 0 - Default 1 - Override 2 - Update
    public void writeDir(Site site) throws IOException {
        ArrayList<String> detectList = site.getSiteAsArrayList();
        ArrayList<File> tempArray = new ArrayList<>();
        ArrayList<String> allowOverrideList = new ArrayList<>();
        int flag = bean.getUserInputBean().getFlag();
        String siteDesc = bean.getEnvBean().getSiteDir().getName();
        allowOverrideList.add(siteDesc);

        for (Panel s : site.getPanelList()) {
            String panel = s.getDescription();
            tempArray.add(new File(format(home.getAbsolutePath() + slash + siteDesc.trim() + slash + panel)));
            int indexHardware = panel.indexOf("_");
            int stationIdHardware = Character.getNumericValue(panel.charAt(indexHardware - 1));
            for (String detectionList : detectList) {
                int index = detectionList.indexOf("_");
                int stationId = Character.getNumericValue(detectionList.charAt(index + 1));
                if (detectionList.contains("Detektions-Objekt") && stationId == stationIdHardware) {
                    detection = siteDesc.trim() + slash + panel + slash + detectionList.trim();
                    pathName.add(new File(home, format(detection).replace("!", "")));
                } else if (detectionList.contains("Abschnitt") && stationId == stationIdHardware) {
                    build = detection.trim() + slash + detectionList.trim();
                    pathName.add(new File(home, format(build.trim()).replace("!", "")));
                } else if (detectionList.contains("Automatische") && stationId == stationIdHardware) {
                    pathName.add(
                            new File(home, format(build.trim() + slash + detectionList.trim()).replace("!", "")));
                } else if (detectionList.contains("Manuelle") && stationId == stationIdHardware) {
                    pathName.add(new File(home, format(build.trim() + slash + detectionList).replace("!", "")));
                } else if (detectionList.contains("Stations-Objekt") && stationId == stationIdHardware) {
                    pathName.add(new File(home,
                            format(siteDesc.trim() + slash + panel.trim() + slash + detectionList.trim())
                                    .replace("!", "")));
                }
            }
        }
        File[] sortedFiles = pathName.toArray(new File[pathName.size()]);
        Arrays.sort(sortedFiles);

        //deletes everything and afterwards revrites as it suppost to.
        if (flag == 1) {
            File check = new File(home.getAbsolutePath() + slash + allowOverrideList.get(0));
            if (check.exists() && check.isDirectory()) {
                FileUtils.deleteDirectory(check);
            }
            /*  This method makes update posible.
             It findes files that already exist and subtracts them from 
             files that has been created. GG.
             All already existing file are added to <code>tempArray</code>.
             */
        } else if (flag == 2) {
            //Somewhat cleaned
            File beginnDir = new File(home.getAbsolutePath() + slash + allowOverrideList.get(0));
            for (File f : sortedFiles) {
                tempArray.add(f);
            }
            tempArray.add(beginnDir);
            Collection<File> collection = FileUtils.listFilesAndDirs(beginnDir,
                    new NotFileFilter(TrueFileFilter.INSTANCE), DirectoryFileFilter.DIRECTORY);

            collection.removeAll(tempArray);
            for (File f : collection) {
                FileUtils.deleteDirectory(f);
            }
        }
        createDir(sortedFiles);
    }

    /**
     * This method creates all directories that will be skeleton of the site.
     * Path are obtained from <code>pathName</code>!
     */
    private void createDir(File[] fileArray) throws SecurityException {
        for (File s : fileArray) {
            s.mkdirs();
        }
        log.info("Directories are created successfully!");
    }

    /**
     * Does some formating.
     *
     * @param toBeFormated
     * @return
     */
    private String format(String toBeFormated) {
        if (os.startsWith("Windows")) {
            return trimLastChar(toBeFormated.replace("", "ae").replace("", "ss").replace("", "ue")
                    .replace("", "oe").replace("!", "").replace("/", "_").trim());
        } else {
            return trimLastChar(toBeFormated.replace("", "ae").replace("", "ss").replace("", "ue")
                    .replace("", "oe").replace("!", "").trim());
        }
    }

    /**
     * trimmsLastChar.
     *
     * @param str
     * @return trimmedString
     */
    private String trimLastChar(String str) {
        if (str.endsWith(".")) {
            return str.substring(0, str.length() - 1);
        } else {
            return str;
        }
    }
}