com.git.ifly6.IRPController.java Source code

Java tutorial

Introduction

Here is the source code for com.git.ifly6.IRPController.java

Source

/* Copyright (c) 2015 ifly6
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */

package com.git.ifly6;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;

import org.apache.commons.lang3.text.WordUtils;

import com.git.ifly6.components.NSObjects.NSNation;
import com.git.ifly6.components.NSObjects.NSRegion;
import com.git.ifly6.components.exceptions.IRPIOException;
import com.git.ifly6.components.exceptions.IRPVersionMismatch;
import com.git.ifly6.components.fileIO.IRPConfigKeys;
import com.git.ifly6.components.fileIO.IRPConfigReader;
import com.git.ifly6.components.fileIO.IRPConfigWriter;
import com.git.ifly6.components.utils.IRPUtilities;
import com.git.ifly6.components.utils.ValueComparator;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.MenuBar;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextInputDialog;

public class IRPController {

    public static int version = IflyRegionProtection.version;
    static double waitTime = 1.716;
    private File configurationFile = new File(IflyRegionProtection.workingDir + "/" + "config.txt");

    @FXML
    private CheckMenuItem networkEnabled;
    @FXML
    private CheckMenuItem heuristicsEnabled;
    @FXML
    private CheckMenuItem endoCapEnabled;
    @FXML
    private TextArea outPane;
    @FXML
    private CheckMenuItem anticoupEnabled;
    @FXML
    private MenuBar menuBar;

    private IRPFormatter out;

    private String regionName = "";
    private String delegate = "";
    private String founder = "";
    private boolean verified = false;
    private int endorsementCap = 0;

    private TreeMap<String, Integer> sortedMap;
    private String[] regionWAMembers = {};

    @FXML
    private void initialize() {

        out = new IRPFormatter(outPane);

        out.comment("Welcome to ifly Region Protection");
        out.comment("Version " + version);

        try {

            IRPConfigReader reader = new IRPConfigReader(configurationFile);
            IRPConfigKeys keys = reader.getKeys();

            regionName = keys.getRegion();
            delegate = keys.getDelegate();
            founder = keys.getFounder();

            anticoupEnabled.setSelected(keys.isAnticoup());
            heuristicsEnabled.setSelected(keys.isHeuristics());
            networkEnabled.setSelected(keys.isNetwork());

            endorsementCap = keys.getCapAmount();

            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("IRP Alert");
            alert.setHeaderText("Scanning");
            alert.setContentText("ifly Region Protection is now scanning your region for endorsement counts.");
            alert.showAndWait();

        } catch (FileNotFoundException e) {
            out.log("Error. Configuration file not found. Please provide configuration file.");

            String newRegion = "";

            TextInputDialog dialog = new TextInputDialog("Region name");
            dialog.setTitle("IRP Settings");
            dialog.setHeaderText("Change Region");
            dialog.setContentText("Enter the region name here:");

            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                newRegion = result.get();
            }

            boolean exists = false;
            try {
                exists = new NSRegion(newRegion).exists();
            } catch (IOException e1) {
                out.log("ERROR. Cannot confirm region existence.");
            }

            if (!newRegion.equals("") && exists) {
                regionName = newRegion;

                try {
                    IRPConfigWriter configWriter = new IRPConfigWriter(regionName);
                    configWriter.setAnticoup(true);
                    configWriter.setCap(10000);
                    configWriter.setCap(false);
                    configWriter.setHeuristics(true);

                    configWriter.write();
                    // Create configuration file

                } catch (IRPIOException e1) {
                    out.log("Error. Unable to create default configuration file.");
                } catch (FileNotFoundException e1) {
                    out.log("Failed to find file.");
                }
            }

        } catch (IRPVersionMismatch e) {
            out.log("Error. Version of configuration file is incompatible.");
        }

        new Thread() {
            @Override
            public void run() {
                updateScan();
            }
        }.run();
    }

    @FXML
    void about(ActionEvent event) {
        // Show dialogue.
    }

    @FXML
    void changeEndoCap(ActionEvent event) {

        if (endoCapEnabled.isSelected()) {

            String input = "";

            TextInputDialog dialog = new TextInputDialog("Endorsement cap");
            dialog.setTitle("IRP Settings");
            dialog.setHeaderText("Change endorsement cap");
            dialog.setContentText("Enter an integer here:");

            Optional<String> result = dialog.showAndWait();
            if (result.isPresent()) {
                input = result.get();
            }

            try {
                int capSet = Integer.parseInt(input);
                endorsementCap = capSet;
                // Write this fact to file.
            } catch (NumberFormatException e) {
                out.log("ERROR. Please provide an integer to the endorsement cap.");
            }

        } else {
            Alert alert = new Alert(AlertType.INFORMATION);
            alert.setTitle("IRP Settings");
            alert.setHeaderText("Endorsement Cap");
            alert.setContentText(
                    "You cannot change the endorsement cap if the endorsement cap system is disabled.");
            alert.showAndWait();
        }

        // Show an alert to change the endorsement cap.
        // Save that change to file.
    }

    @FXML
    void changeRegion(ActionEvent event) {

        String newRegion = "";

        TextInputDialog dialog = new TextInputDialog("Region name");
        dialog.setTitle("IRP Settings");
        dialog.setHeaderText("Change Region");
        dialog.setContentText("Enter the region name here:");

        Optional<String> result = dialog.showAndWait();
        if (result.isPresent()) {
            newRegion = result.get();
        }

        boolean exists = false;
        try {
            exists = new NSRegion(newRegion).exists();
        } catch (Exception e1) {
            out.log("ERROR. Cannot confirm region existence.");
        }

        if (!newRegion.equals("") && exists) {

            configurationFile
                    .renameTo(new File(IflyRegionProtection.workingDir + File.separator + regionName + ".txt"));

            File[] fileList = new File(IflyRegionProtection.workingDir).listFiles();
            boolean preexisting = false;
            for (File element : fileList) {
                if (element.getName().equals(newRegion + ".txt")) {
                    preexisting = true;
                }
            }

            if (preexisting) {
                new File(newRegion + ".txt").renameTo(configurationFile);
            } else {
                // Create new configuration file and copy setting stored in memory.
            }

        } else {
            out.log("Error. Please provide a valid region name.");
        }

        regionName = newRegion;

    }

    @FXML
    void delegateEndorsements(ActionEvent event) {
        NSNation delegateNation = new NSNation(delegate);
        try {
            String[] endorsements = delegateNation.getEndorsements();
            ArrayList<String> disloyal = new ArrayList<String>();

            for (String nationName : regionWAMembers) {
                boolean onList = false;

                for (String endorsing : endorsements) {
                    if (nationName.equals(endorsing)) {
                        onList = true;
                    }
                    break;
                }

                if (!onList) {
                    disloyal.add(nationName);
                }
            }

            String header = String.format("%-40.40s %12s", "Disloyal Nations", "Endorsements");
            String line = "-----------------------------------------------------";

            out.append(header);
            out.append(line);

            for (String nationName : disloyal) {
                out.append(String.format("%-40.40s %12s %12s", nationName, sortedMap.get(nationName).intValue()));
            }
        } catch (IOException e) {
            out.log("Failed to fetch Delegate endorsements.");
        }

        // Show who is and isn't endorsing Delegate
    }

    @FXML
    void exit(ActionEvent event) {
        System.exit(0);
    }

    @FXML
    void scan(ActionEvent event) {

        new Runnable() {
            @Override
            public void run() {
                updateScan();
            }
        }.run();

        // Update all endorsement listings via the API
        // Save all endorsement listings to a certain date
        // Have the program do so at every update + 2 hours
    }

    @FXML
    void showEndos(ActionEvent event) {
        int current = 0;
        int previous = sortedMap.firstEntry().getValue();

        String header = String.format("%-40.40s %12s %12s", "Nations", "Endorsements", "Difference");
        String line = "------------------------------------------------------------------";

        out.append(header);
        out.append(line);

        for (Map.Entry<String, Integer> entry : sortedMap.entrySet()) {

            String nationName = WordUtils.capitalize(entry.getKey().replace('_', ' '));
            current = entry.getValue();

            if ((previous - current) != 0) {
                out.append(String.format("%-40.40s %12s %12s", nationName, entry.getValue(), (previous - current)));
            } else {
                out.append(String.format("%-40.40s %12s %12s", nationName, entry.getValue(), "-"));
            }

            previous = entry.getValue();
        }

        out.append(line);
        out.append(String.format("%-40.40s %12s %12s", "Delegate", "Endorsements", "Proportion"));
        out.append(String.format("%-40.40s %12s %12.3f",
                WordUtils.capitalize(sortedMap.firstEntry().getKey().replace('_', ' ')),
                sortedMap.firstEntry().getValue(),
                ((double) sortedMap.firstEntry().getValue() / (double) regionWAMembers.length)));
    }

    @FXML
    void showFenders(ActionEvent event) {
        // Show identified defenders
    }

    @FXML
    void showGrowth(ActionEvent event) {
        // Show quickly growing endorsement nations
    }

    @FXML
    void showInfluence(ActionEvent event) {
        // Show nations with highest influence
    }

    @FXML
    void showNetworks(ActionEvent event) {
        // Show who isn't endorsing the right people
    }

    @FXML
    void showRaiders(ActionEvent event) {
        // Show identified raiders
    }

    @FXML
    void showThreat(ActionEvent event) {
        // Show greatest threats (calculations to be done)
    }

    @FXML
    void updateDefinitions(ActionEvent event) {
        // Download a list of fenders and raiders
    }

    private void updateScan() {
        try {
            NSRegion region = new NSRegion(regionName);
            HashMap<String, Integer> endoMap = new HashMap<String, Integer>();
            regionWAMembers = region.getWAMembers();
            int[] valueCount = new int[regionWAMembers.length];

            out.log("Starting Scan");
            out.log("This will take: " + IRPUtilities.time((int) Math.round(waitTime * regionWAMembers.length)));

            for (int i = 0; i < regionWAMembers.length; i++) {
                NSNation nation = new NSNation(regionWAMembers[i]);
                valueCount[i] = nation.getEndoCount();
                endoMap.put(regionWAMembers[i], new Integer(valueCount[i]));

                out.log("Fetched information for: " + regionWAMembers[i] + ", " + (i + 1) + " of "
                        + regionWAMembers.length);
            }

            sortedMap = ValueComparator.sortByValue(endoMap);

        } catch (IOException e) {
            out.log("Error. Failed to scan.");
        }
    }

    @FXML
    void verifyPermissions(ActionEvent event) {
        // Verify that the user is the current Delegate or Founder using the API
        // Update configuration file to current delegate
        // Include backdoor with a given wget

        verified = true;
    }

}