br.com.blackhubos.commandteleporter.Framework.java Source code

Java tutorial

Introduction

Here is the source code for br.com.blackhubos.commandteleporter.Framework.java

Source

/**
 *
 * CommandTeleporter - Simple & fast teleporter by command
 * Copyright  2016 BlackHub OS and contributors.
 *
 * 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 br.com.blackhubos.commandteleporter;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.Validate;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;

/**
 *
 * @author <a href="https://github.com/ReedFlake/">ReedFlake (blackthog@gmail.com)</a>
 *
 */
public final class Framework {

    @SuppressWarnings("unchecked")
    public static <T extends JavaPlugin> T getPlugin(final String name) {
        return (T) Bukkit.getPluginManager().getPlugin(name);
    }

    public static long reverseOf(final String tempo) {
        if (tempo == null) {
            return 0L;
        }

        final Pattern verifier = Pattern.compile("(([0-9]+)(h|m|s))", Pattern.CASE_INSENSITIVE);
        final Matcher m = verifier.matcher(tempo.toLowerCase());
        long delay = 0L;
        while (m.find()) {
            final int numero = Integer.parseInt(m.group(2));
            final char c = m.group(3).charAt(0);
            if (c == 's') {
                delay += numero * 20L;
            } else if (c == 'm') {
                delay += (numero * 60) * 20L;
            } else if (c == 'h') {
                delay += ((numero * 60) * 20L) * 60;
            }
        }

        return delay;
    }

    public static String fromLocation(final Location pos) {
        return String.format("World [%s] X [%s] Y [%s] Z [%s] Yaw [%s] Pitch [%s]", pos.getWorld().getName(),
                pos.getBlockX(), pos.getBlockY(), pos.getBlockZ(), pos.getYaw(), pos.getPitch());
    }

    public static Location toLocation(final String serial) {
        final Pattern pattern = Pattern.compile(
                "^World\\s*\\[([a-zA-Z0-9_-]+)\\]\\s*X\\s*\\[([0-9-]+)\\]\\s*Y\\s*\\[([0-9-]+)\\]\\s*Z\\s*\\[([0-9-]+)\\](\\s*Yaw\\s*\\[([0-9-\\.]+)\\]\\s*Pitch\\s*\\[([0-9-\\.]+)\\])?");
        final Matcher m = pattern.matcher(serial);
        if (m.matches()) {
            if ((m.groupCount() >= 5) && (m.group(5) != null) && (m.group(6) != null) && (m.group(7) != null)) {
                return new Location(Framework.getWorld(m.group(1)), Integer.parseInt(m.group(2)),
                        Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)), Float.parseFloat(m.group(6)),
                        Float.parseFloat(m.group(7)));
            } else {
                return new Location(Framework.getWorld(m.group(1)), Integer.parseInt(m.group(2)),
                        Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)));
            }
        } else {
            return null;
        }
    }

    public static World getWorld(final String name) {
        return Bukkit.getWorld(name);
    }

    public static final class LoggerManager<T extends JavaPlugin> {

        protected Integer task = 0;
        private final T plugin;
        private final java.util.Vector<Log> log = new java.util.Vector<Log>();
        private final File parent;

        @SuppressWarnings("unchecked")
        public LoggerManager(final Plugin plugin, final File parent) {
            this.plugin = (T) plugin;
            this.parent = parent;
        }

        public LoggerManager<T> init(final String time) {
            this.task = Bukkit.getScheduler().runTaskTimer(this.plugin, new Runnable() {
                @Override
                public void run() {
                    LoggerManager.this.write();
                }
            }, Framework.reverseOf(time), Framework.reverseOf(time)).getTaskId();
            return this;
        }

        public void cancel() {
            Bukkit.getScheduler().cancelTask(this.task);
        }

        public void restart(final String newTime) {
            this.cancel();
            this.init(newTime);
        }

        public void addLog(final Log l) {
            if (!this.log.contains(l)) {
                this.log.add(l);
            }
        }

        public void addLog(final Date d, final String msg) {
            this.log.add(new Log(d, msg));
        }

        public void addLog(final String msg) {
            this.log.add(new Log(new Date(), msg));
        }

        public void removeLogFromCache(final Log l) {
            if (this.log.contains(l)) {
                this.log.remove(l);
            }
        }

        public java.util.Vector<Log> getCache() {
            final java.util.Vector<Log> log2 = new java.util.Vector<Log>();
            log2.addAll(this.log);
            return log2;
        }

        public void write() {
            final java.util.Vector<Log> saving_log = this.getCache();
            if (saving_log.size() == 0) {
                return;
            }
            this.log.clear();
            new LogWriter(saving_log).start();
        }

        private final class LogWriter extends Thread {
            private java.util.Vector<Log> saving_log = null;

            public LogWriter(final java.util.Vector<Log> l) {
                this.saving_log = l;
            }

            @Override
            public void run() {
                if (!LoggerManager.this.parent.exists()) {
                    LoggerManager.this.parent.mkdir();
                }
                final HashMap<String, java.util.Vector<Log>> date_log = new HashMap<String, java.util.Vector<Log>>();
                for (final Log l : this.saving_log) {
                    final String n = LoggerManager.this.getFilename(l.getDate());
                    final File f = new File(LoggerManager.this.parent, n);
                    if (!f.exists()) {
                        try {
                            f.createNewFile();
                        } catch (final Exception e) {
                        }
                    }
                    if (date_log.containsKey(n)) {
                        date_log.get(n).add(l);
                    } else {
                        final java.util.Vector<Log> ll = new java.util.Vector<Log>();
                        ll.add(l);
                        date_log.put(n, ll);
                    }
                }
                for (final String n : date_log.keySet()) {
                    final File f = new File(LoggerManager.this.parent, n);
                    BufferedWriter writer = null;
                    try {
                        writer = new BufferedWriter(new FileWriter(f, true));
                        for (final Log l : date_log.get(n)) {
                            writer.write(LoggerManager.this.format(l.getDate(), l.getMessage()));
                            writer.newLine();
                        }
                    } catch (final Exception e) {
                    } finally {
                        try {
                            writer.close();
                        } catch (final Exception e) {
                        }
                    }
                }
            }
        }

        public String getFilename(final Date d) {
            final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
            return df.format(d) + ".txt";
        }

        public File getFile(final Date d) {
            return new File(this.parent, this.getFilename(d));
        }

        public String format(final Date d, final String msg) {
            final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
            return "[" + df.format(d) + "] " + msg;
        }
    }

    public static final class Log implements Serializable {

        private static final long serialVersionUID = -2950841356281211210L;
        private Date date = null;
        private String msg = "";

        public Log(final Date d, final String msg) {
            this.date = d;
            this.msg = msg;
        }

        public String getMessage() {
            return this.msg;
        }

        public void setMessage(final String msg) {
            this.msg = msg;
        }

        public Date getDate() {
            return this.date;
        }

        public void setDate(final Date d) {
            this.date = d;
        }

    }

    public static final class Configuration extends YamlConfiguration {

        private boolean copied;

        public Configuration() {
            this.copied = false;
        }

        public Configuration(final Plugin plugin, final File file) {
            if (!file.exists()) {
                plugin.saveResource(file.getName(), false);
                this.copied = true;
            }

            try {
                this.load(file);
            } catch (IOException | InvalidConfigurationException e) {
                e.printStackTrace();
            }
        }

        public Configuration(final Plugin plugin, final String resource, final File file) {
            if (!file.exists()) {
                plugin.saveResource(resource, false);
                new File(plugin.getDataFolder(), resource).renameTo(file);
                this.copied = true;
            }

            try {
                this.load(file);
            } catch (IOException | InvalidConfigurationException e) {
                e.printStackTrace();
            }
        }

        public boolean copied() {
            return this.copied;
        }

        @Override
        public void load(final InputStream stream) throws IOException, InvalidConfigurationException {
            Validate.notNull(stream, "Stream cannot be null");

            final InputStreamReader reader = new InputStreamReader(stream, Charset.forName("UTF-8"));
            final StringBuilder builder = new StringBuilder();
            final BufferedReader input = new BufferedReader(reader);

            try {
                String line;

                while ((line = input.readLine()) != null) {
                    builder.append(line);
                    builder.append('\n');
                }
            } finally {
                input.close();
            }

            this.loadFromString(builder.toString());
        }

        @Override
        public void save(final File file) throws IOException {
            Validate.notNull(file, "File cannot be null");
            com.google.common.io.Files.createParentDirs(file);
            final String data = this.saveToString();
            final FileOutputStream stream = new FileOutputStream(file);
            final OutputStreamWriter writer = new OutputStreamWriter(stream, Charset.forName("UTF-8"));

            try {
                writer.write(data);
            } finally {
                writer.close();
            }
        }
    }

}