Search in sources :

Example 1 with SimpleVersion

use of com.laytonsmith.PureUtilities.SimpleVersion in project CommandHelper by EngineHub.

the class Script method eval.

/**
 * Given the parse tree and environment, executes the tree.
 *
 * @param c
 * @param env
 * @return
 * @throws CancelCommandException
 */
public Construct eval(ParseTree c, final Environment env) throws CancelCommandException {
    if (env.getEnv(GlobalEnv.class).IsInterrupted()) {
        // unconditionally.
        throw new CancelCommandException("", Target.UNKNOWN);
    }
    final Construct m = c.getData();
    CurrentEnv = env;
    if (m.getCType() != ConstructType.FUNCTION) {
        if (m.getCType() == ConstructType.VARIABLE) {
            return new CString(m.val(), m.getTarget());
        } else {
            return m;
        }
    }
    StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
    boolean addedRootStackElement = false;
    try {
        // If it's an unknown target, this is not user generated code, and we want to skip adding the element here.
        if (stManager.isStackEmpty() && !m.getTarget().equals(Target.UNKNOWN)) {
            stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<main code>>", m.getTarget()));
            addedRootStackElement = true;
        }
        stManager.setCurrentTarget(c.getTarget());
        env.getEnv(GlobalEnv.class).SetScript(this);
        if (m.val().charAt(0) == '_' && m.val().charAt(1) != '_') {
            // Not really a function, so we can't put it in Function.
            Procedure p = getProc(m.val());
            if (p == null) {
                throw new CREInvalidProcedureException("Unknown procedure \"" + m.val() + "\"", m.getTarget());
            }
            Environment newEnv = env;
            try {
                newEnv = env.clone();
            } catch (CloneNotSupportedException e) {
            }
            ProfilePoint pp = env.getEnv(GlobalEnv.class).GetProfiler().start(m.val() + " execution", LogLevel.INFO);
            Construct ret;
            try {
                ret = p.cexecute(c.getChildren(), newEnv, m.getTarget());
            } finally {
                pp.stop();
            }
            return ret;
        }
        final Function f;
        try {
            f = (Function) FunctionList.getFunction(m);
        } catch (ConfigCompileException e) {
            // Turn it into a config runtime exception. This shouldn't ever happen though.
            throw ConfigRuntimeException.CreateUncatchableException("Unable to find function " + m.val(), m.getTarget());
        }
        ArrayList<Construct> args = new ArrayList<>();
        try {
            if (f.isRestricted() && !Static.hasCHPermission(f.getName(), env)) {
                throw new CREInsufficientPermissionException("You do not have permission to use the " + f.getName() + " function.", m.getTarget());
            }
            if (f.useSpecialExec()) {
                ProfilePoint p = null;
                if (f.shouldProfile() && env.getEnv(GlobalEnv.class).GetProfiler() != null && env.getEnv(GlobalEnv.class).GetProfiler().isLoggable(f.profileAt())) {
                    p = env.getEnv(GlobalEnv.class).GetProfiler().start(f.profileMessageS(c.getChildren()), f.profileAt());
                }
                Construct ret;
                try {
                    ret = f.execs(m.getTarget(), env, this, c.getChildren().toArray(new ParseTree[] {}));
                } finally {
                    if (p != null) {
                        p.stop();
                    }
                }
                return ret;
            }
            for (ParseTree c2 : c.getChildren()) {
                args.add(eval(c2, env));
            }
            Object[] a = args.toArray();
            Construct[] ca = new Construct[a.length];
            for (int i = 0; i < a.length; i++) {
                ca[i] = (Construct) a[i];
                // CArray, CBoolean, CDouble, CInt, CNull, CString, CVoid, CEntry, CLabel (only to sconcat).
                if (!(ca[i] instanceof CArray || ca[i] instanceof CBoolean || ca[i] instanceof CDouble || ca[i] instanceof CInt || ca[i] instanceof CNull || ca[i] instanceof CString || ca[i] instanceof CVoid || ca[i] instanceof IVariable || ca[i] instanceof CEntry || ca[i] instanceof CLabel) && (!f.getName().equals("__autoconcat__") && (ca[i] instanceof CLabel))) {
                    throw new CRECastException("Invalid Construct (" + ca[i].getClass() + ") being passed as an argument to a function (" + f.getName() + ")", m.getTarget());
                }
                while (f.preResolveVariables() && ca[i] instanceof IVariable) {
                    IVariable cur = (IVariable) ca[i];
                    ca[i] = env.getEnv(GlobalEnv.class).GetVarList().get(cur.getVariableName(), cur.getTarget()).ival();
                }
            }
            {
                // It takes a moment to generate the toString of some things, so lets not do it
                // if we actually aren't going to profile
                ProfilePoint p = null;
                if (f.shouldProfile() && env.getEnv(GlobalEnv.class).GetProfiler() != null && env.getEnv(GlobalEnv.class).GetProfiler().isLoggable(f.profileAt())) {
                    p = env.getEnv(GlobalEnv.class).GetProfiler().start(f.profileMessage(ca), f.profileAt());
                }
                Construct ret;
                try {
                    ret = f.exec(m.getTarget(), env, ca);
                } finally {
                    if (p != null) {
                        p.stop();
                    }
                }
                return ret;
            }
        // We want to catch and rethrow the ones we know how to catch, and then
        // catch and report anything else.
        } catch (ConfigRuntimeException | ProgramFlowManipulationException e) {
            if (e instanceof AbstractCREException) {
                ((AbstractCREException) e).freezeStackTraceElements(stManager);
            }
            throw e;
        } catch (InvalidEnvironmentException e) {
            if (!e.isDataSet()) {
                e.setData(f.getName());
            }
            throw e;
        } catch (Exception e) {
            String brand = Implementation.GetServerType().getBranding();
            SimpleVersion version = Static.getVersion();
            String culprit = brand;
            outer: for (ExtensionTracker tracker : ExtensionManager.getTrackers().values()) {
                for (FunctionBase b : tracker.getFunctions()) {
                    if (b.getName().equals(f.getName())) {
                        // name instead of the core plugin's name.
                        for (Extension extension : tracker.getExtensions()) {
                            culprit = extension.getName();
                            break outer;
                        }
                    }
                }
            }
            String emsg = TermColors.RED + "Uh oh! You've found an error in " + TermColors.CYAN + culprit + TermColors.RED + ".\n" + "This happened while running your code, so you may be able to find a workaround," + " but is ultimately an issue in " + culprit + ".\n" + "The following code caused the error:\n" + TermColors.WHITE;
            List<String> args2 = new ArrayList<>();
            Map<String, String> vars = new HashMap<>();
            for (Construct cc : args) {
                if (cc instanceof IVariable) {
                    Construct ccc = env.getEnv(GlobalEnv.class).GetVarList().get(((IVariable) cc).getVariableName(), cc.getTarget()).ival();
                    String vval = ccc.val();
                    if (ccc instanceof CString) {
                        vval = ccc.asString().getQuote();
                    }
                    vars.put(((IVariable) cc).getVariableName(), vval);
                }
                if (cc == null) {
                    args2.add("java-null");
                } else if (cc instanceof CString) {
                    args2.add(cc.asString().getQuote());
                } else if (cc instanceof IVariable) {
                    args2.add(((IVariable) cc).getVariableName());
                } else {
                    args2.add(cc.val());
                }
            }
            if (!vars.isEmpty()) {
                emsg += StringUtils.Join(vars, " = ", "\n") + "\n";
            }
            emsg += f.getName() + "(";
            emsg += StringUtils.Join(args2, ", ");
            emsg += ")\n";
            emsg += TermColors.RED + "on or around " + TermColors.YELLOW + m.getTarget().file() + TermColors.WHITE + ":" + TermColors.CYAN + m.getTarget().line() + TermColors.RED + ".\n";
            // Server might not be available in this platform, so let's be sure to ignore those exceptions
            String modVersion;
            try {
                modVersion = StaticLayer.GetConvertor().GetServer().getAPIVersion();
            } catch (Exception ex) {
                modVersion = Implementation.GetServerType().name();
            }
            String extensionData = "";
            for (ExtensionTracker tracker : ExtensionManager.getTrackers().values()) {
                for (Extension extension : tracker.getExtensions()) {
                    try {
                        extensionData += TermColors.CYAN + extension.getName() + TermColors.RED + " (" + TermColors.RESET + extension.getVersion() + TermColors.RED + ")\n";
                    } catch (AbstractMethodError ex) {
                        // This happens with an old style extensions. Just skip it.
                        extensionData += TermColors.CYAN + "Unknown Extension" + TermColors.RED + "\n";
                    }
                }
            }
            if (extensionData.isEmpty()) {
                extensionData = "NONE\n";
            }
            emsg += "Please report this to the developers, and be sure to include the version numbers:\n" + TermColors.CYAN + "Server" + TermColors.RED + " version: " + TermColors.RESET + modVersion + TermColors.RED + ";\n" + TermColors.CYAN + brand + TermColors.RED + " version: " + TermColors.RESET + version + TermColors.RED + ";\n" + "Loaded extensions and versions:\n" + extensionData + "Here's the stacktrace:\n" + TermColors.RESET + Static.GetStacktraceString(e);
            Static.getLogger().log(Level.SEVERE, emsg);
            throw new CancelCommandException(null, Target.UNKNOWN);
        }
    } finally {
        if (addedRootStackElement && stManager.isStackSingle()) {
            stManager.popStackTraceElement();
        }
    }
}
Also used : CLabel(com.laytonsmith.core.constructs.CLabel) InvalidEnvironmentException(com.laytonsmith.core.environments.InvalidEnvironmentException) FunctionBase(com.laytonsmith.core.functions.FunctionBase) IVariable(com.laytonsmith.core.constructs.IVariable) ArrayList(java.util.ArrayList) CArray(com.laytonsmith.core.constructs.CArray) CREInvalidProcedureException(com.laytonsmith.core.exceptions.CRE.CREInvalidProcedureException) ExtensionTracker(com.laytonsmith.core.extensions.ExtensionTracker) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) CString(com.laytonsmith.core.constructs.CString) Function(com.laytonsmith.core.functions.Function) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) SimpleVersion(com.laytonsmith.PureUtilities.SimpleVersion) FunctionList(com.laytonsmith.core.functions.FunctionList) List(java.util.List) ArrayList(java.util.ArrayList) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CREInsufficientPermissionException(com.laytonsmith.core.exceptions.CRE.CREInsufficientPermissionException) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) CBoolean(com.laytonsmith.core.constructs.CBoolean) CDouble(com.laytonsmith.core.constructs.CDouble) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) StackTraceManager(com.laytonsmith.core.exceptions.StackTraceManager) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) InvalidEnvironmentException(com.laytonsmith.core.environments.InvalidEnvironmentException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CREInsufficientPermissionException(com.laytonsmith.core.exceptions.CRE.CREInsufficientPermissionException) LoopBreakException(com.laytonsmith.core.exceptions.LoopBreakException) CREInvalidProcedureException(com.laytonsmith.core.exceptions.CRE.CREInvalidProcedureException) LoopContinueException(com.laytonsmith.core.exceptions.LoopContinueException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) CVoid(com.laytonsmith.core.constructs.CVoid) Extension(com.laytonsmith.core.extensions.Extension) CInt(com.laytonsmith.core.constructs.CInt) Construct(com.laytonsmith.core.constructs.Construct) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Environment(com.laytonsmith.core.environments.Environment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) CEntry(com.laytonsmith.core.constructs.CEntry) Map(java.util.Map) HashMap(java.util.HashMap) CNull(com.laytonsmith.core.constructs.CNull)

Example 2 with SimpleVersion

use of com.laytonsmith.PureUtilities.SimpleVersion in project CommandHelper by EngineHub.

the class CommandHelperPlugin method onLoad.

@Override
public void onLoad() {
    Implementation.setServerType(Implementation.Type.BUKKIT);
    CommandHelperFileLocations.setDefault(new CommandHelperFileLocations());
    CommandHelperFileLocations.getDefault().getCacheDirectory().mkdirs();
    CommandHelperFileLocations.getDefault().getPreferencesDirectory().mkdirs();
    UpgradeLog upgradeLog = new UpgradeLog(CommandHelperFileLocations.getDefault().getUpgradeLogFile());
    upgradeLog.addUpgradeTask(new UpgradeLog.UpgradeTask() {

        String version = null;

        @Override
        public boolean doRun() {
            try {
                version = "versionUpgrade-" + Main.loadSelfVersion();
                return !hasBreadcrumb(version);
            } catch (Exception ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }
        }

        @Override
        public void run() {
            leaveBreadcrumb(version);
        }
    });
    upgradeLog.addUpgradeTask(new UpgradeLog.UpgradeTask() {

        File oldPreferences = new File(CommandHelperFileLocations.getDefault().getConfigDirectory(), "preferences.txt");

        @Override
        public boolean doRun() {
            return oldPreferences.exists() && !CommandHelperFileLocations.getDefault().getPreferencesFile().exists();
        }

        @Override
        public void run() {
            try {
                Prefs.init(oldPreferences);
                Prefs.SetColors();
                Logger.getLogger("Minecraft").log(Level.INFO, TermColors.YELLOW + "[" + Implementation.GetServerType().getBranding() + "] Old preferences.txt file detected. Moving preferences.txt to preferences.ini." + TermColors.reset());
                FileUtil.copy(oldPreferences, CommandHelperFileLocations.getDefault().getPreferencesFile(), true);
                oldPreferences.deleteOnExit();
            } catch (IOException ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    upgradeLog.addUpgradeTask(new UpgradeLog.UpgradeTask() {

        File cd = CommandHelperFileLocations.getDefault().getConfigDirectory();

        private final String breadcrumb = "move-preference-files-v1.0";

        @Override
        public boolean doRun() {
            return !hasBreadcrumb(breadcrumb) && new File(cd, "preferences.ini").exists();
        }

        @Override
        public void run() {
            // We need to move the following files:
            // 1. persistance.config to prefs/persistence.ini (note the correct spelling)
            // 2. preferences.ini to prefs/preferences.ini
            // 3. profiler.config to prefs/profiler.ini
            // 4. sql-profiles.xml to prefs/sql-profiles.xml
            // 5. We are not moving loggerPreferences.txt, instead just deleting it,
            // because the defaults have changed. Most people aren't using this feature
            // anyways. (The new one will write itself out upon installation.)
            // Other than the config/prefs directory, we are hardcoding all the values, so
            // we know they are correct (for old values). Any errors will be reported, but will not
            // stop the entire process.
            CommandHelperFileLocations p = CommandHelperFileLocations.getDefault();
            try {
                FileUtil.move(new File(cd, "persistance.config"), p.getPersistenceConfig());
            } catch (IOException ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                FileUtil.move(new File(cd, "preferences.ini"), p.getPreferencesFile());
            } catch (IOException ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                FileUtil.move(new File(cd, "profiler.config"), p.getProfilerConfigFile());
            } catch (IOException ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                FileUtil.move(new File(cd, "sql-profiles.xml"), p.getProfilesFile());
            } catch (IOException ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
            new File(cd, "logs/debug/loggerPreferences.txt").delete();
            leaveBreadcrumb(breadcrumb);
            StreamUtils.GetSystemOut().println("CommandHelper: Your preferences files have all been relocated to " + p.getPreferencesDirectory());
            StreamUtils.GetSystemOut().println("CommandHelper: The loggerPreferences.txt file has been deleted and re-created, as the defaults have changed.");
        }
    });
    // Renames the sql-profiles.xml file to the new name.
    upgradeLog.addUpgradeTask(new UpgradeLog.UpgradeTask() {

        // This should never change
        private final File oldProfilesFile = new File(MethodScriptFileLocations.getDefault().getPreferencesDirectory(), "sql-profiles.xml");

        @Override
        public boolean doRun() {
            return oldProfilesFile.exists();
        }

        @Override
        public void run() {
            try {
                FileUtil.move(oldProfilesFile, MethodScriptFileLocations.getDefault().getProfilesFile());
                StreamUtils.GetSystemOut().println("CommandHelper: sql-profiles.xml has been renamed to " + MethodScriptFileLocations.getDefault().getProfilesFile().getName());
            } catch (IOException ex) {
                Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
    try {
        upgradeLog.runTasks();
    } catch (IOException ex) {
        Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        Prefs.init(CommandHelperFileLocations.getDefault().getPreferencesFile());
    } catch (IOException ex) {
        Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
    }
    Prefs.SetColors();
    CHLog.initialize(CommandHelperFileLocations.getDefault().getConfigDirectory());
    Installer.Install(CommandHelperFileLocations.getDefault().getConfigDirectory());
    if (new SimpleVersion(System.getProperty("java.version")).lt(new SimpleVersion("1.8"))) {
        CHLog.GetLogger().w(CHLog.Tags.GENERAL, "You appear to be running a version of Java older than Java 8. You should have plans" + " to upgrade at some point, as " + Implementation.GetServerType().getBranding() + " may require it at some point.", Target.UNKNOWN);
    }
    self = this;
    ClassDiscoveryCache cdc = new ClassDiscoveryCache(CommandHelperFileLocations.getDefault().getCacheDirectory());
    cdc.setLogger(Logger.getLogger(CommandHelperPlugin.class.getName()));
    ClassDiscovery.getDefaultInstance().setClassDiscoveryCache(cdc);
    ClassDiscovery.getDefaultInstance().addDiscoveryLocation(ClassDiscovery.GetClassContainer(CommandHelperPlugin.class));
    StreamUtils.GetSystemOut().println("[CommandHelper] Running initial class discovery," + " this will probably take a few seconds...");
    StreamUtils.GetSystemOut().println("[CommandHelper] Loading extensions in the background...");
    loadingThread = new Thread("extensionloader") {

        @Override
        public void run() {
            ExtensionManager.AddDiscoveryLocation(CommandHelperFileLocations.getDefault().getExtensionsDirectory());
            if (OSUtils.GetOS() == OSUtils.OS.WINDOWS) {
                // Using StreamUtils.GetSystemOut() here instead of the logger as the logger doesn't
                // immediately print to the console.
                StreamUtils.GetSystemOut().println("[CommandHelper] Caching extensions...");
                ExtensionManager.Cache(CommandHelperFileLocations.getDefault().getExtensionCacheDirectory());
                StreamUtils.GetSystemOut().println("[CommandHelper] Extension caching complete.");
            }
            ExtensionManager.Initialize(ClassDiscovery.getDefaultInstance());
            StreamUtils.GetSystemOut().println("[CommandHelper] Extension loading complete.");
        }
    };
    loadingThread.start();
}
Also used : UpgradeLog(com.laytonsmith.core.UpgradeLog) SimpleVersion(com.laytonsmith.PureUtilities.SimpleVersion) IOException(java.io.IOException) File(java.io.File) InvocationTargetException(java.lang.reflect.InvocationTargetException) EventException(org.bukkit.event.EventException) IOException(java.io.IOException) ClassDiscoveryCache(com.laytonsmith.PureUtilities.ClassLoading.ClassDiscoveryCache)

Example 3 with SimpleVersion

use of com.laytonsmith.PureUtilities.SimpleVersion in project CommandHelper by EngineHub.

the class ExtensionManager method Initialize.

/**
 * Initializes the extension manager. This operation is not necessarily required, and must be guaranteed to not run
 * more than once per ClassDiscovery object.
 *
 * @param cd the ClassDiscovery to use for loading files.
 */
public static void Initialize(ClassDiscovery cd) {
    extensions.clear();
    // Look in the extension folder for jars, add them to our class discover,
    // then initialize everything
    List<File> toProcess = new ArrayList<>();
    // Grab files from the cache if on Windows. Otherwise just load
    // directly from the stored locations.
    boolean onWindows = (OSUtils.GetOS() == OSUtils.OS.WINDOWS);
    if (onWindows) {
        toProcess.addAll(getFiles(CommandHelperFileLocations.getDefault().getExtensionCacheDirectory()));
    } else {
        for (File location : locations) {
            toProcess.addAll(getFiles(location));
        }
    }
    DynamicClassLoader dcl = new DynamicClassLoader();
    cd.setDefaultClassLoader(dcl);
    for (File f : toProcess) {
        if (f.getName().endsWith(".jar")) {
            try {
                // First, load it with our custom class loader
                URL jar = f.toURI().toURL();
                dcl.addJar(jar);
                cd.addDiscoveryLocation(jar);
                CHLog.GetLogger().Log(CHLog.Tags.EXTENSIONS, LogLevel.DEBUG, "Loaded " + f.getAbsolutePath(), Target.UNKNOWN);
            } catch (MalformedURLException ex) {
                Static.getLogger().log(Level.SEVERE, null, ex);
            }
        }
    }
    // one found defines the internal name.
    for (ClassMirror<? extends AbstractExtension> extmirror : cd.getClassesWithAnnotationThatExtend(MSExtension.class, AbstractExtension.class)) {
        if (extmirror.equals(new ClassMirror<>(AbstractExtension.class))) {
            continue;
        }
        Extension ext;
        URL url = extmirror.getContainer();
        Class<? extends AbstractExtension> extcls;
        if (extmirror.getModifiers().isAbstract()) {
            Static.getLogger().log(Level.SEVERE, "Probably won't be able to" + " instantiate " + extmirror.getClassName() + ": The" + " class is marked as abstract! Will try anyway.");
        }
        try {
            extcls = extmirror.loadClass(dcl, true);
        } catch (Throwable ex) {
            // May throw anything, and kill the loading process.
            // Lets prevent that!
            Static.getLogger().log(Level.SEVERE, "Could not load class '" + extmirror.getClassName() + "'");
            ex.printStackTrace();
            continue;
        }
        try {
            ext = extcls.newInstance();
        } catch (InstantiationException | IllegalAccessException ex) {
            // Error, but skip this one, don't throw an exception ourselves, just log it.
            Static.getLogger().log(Level.SEVERE, "Could not instantiate " + extcls.getName() + ": " + ex.getMessage());
            continue;
        }
        ExtensionTracker trk = extensions.get(url);
        if (trk == null) {
            trk = new ExtensionTracker(url, cd, dcl);
            extensions.put(url, trk);
        }
        // use it.
        if (trk.identifier == null) {
            trk.identifier = ext.getName();
            try {
                trk.version = ext.getVersion();
            } catch (AbstractMethodError ex) {
                // getVersion() was added later. This is a temporary fix
                // to allow extension authors some time to update.
                // TODO: Remove this soon.
                trk.version = new SimpleVersion("0.0.0");
            }
        }
        trk.allExtensions.add(ext);
    }
    // Lets store info about the functions and events extensions have.
    // This will aide in gracefully unloading stuff later.
    Set<ClassMirror<?>> classes = cd.getClassesWithAnnotation(api.class);
    // Temp tracking for loading messages later on.
    List<String> events = new ArrayList<>();
    List<String> functions = new ArrayList<>();
    // and store the instances in their trackers.
    for (ClassMirror klass : classes) {
        URL url = klass.getContainer();
        if (cd.doesClassExtend(klass, Event.class) || cd.doesClassExtend(klass, Function.class)) {
            Class c;
            try {
                c = klass.loadClass(dcl, true);
            } catch (Throwable ex) {
                // May throw anything, and kill the loading process.
                // Lets prevent that!
                Static.getLogger().log(Level.SEVERE, "Could not load class '" + klass.getClassName() + "'");
                ex.printStackTrace();
                continue;
            }
            ExtensionTracker trk = extensions.get(url);
            if (trk == null) {
                trk = new ExtensionTracker(url, cd, dcl);
                extensions.put(url, trk);
            }
            // Instantiate, register and store.
            try {
                if (Event.class.isAssignableFrom(c)) {
                    Class<Event> cls = (Class<Event>) c;
                    if (klass.getModifiers().isAbstract()) {
                        // Abstract? Looks like they accidently @api'd
                        // a cheater class. We can't be sure that it is fully
                        // defined, so complain to the console.
                        CHLog.GetLogger().Log(CHLog.Tags.EXTENSIONS, LogLevel.ERROR, "Class " + c.getName() + " in " + url + " is" + " marked as an event but is also abstract." + " Bugs might occur! Bug someone about this!", Target.UNKNOWN);
                    }
                    Event e = cls.newInstance();
                    events.add(e.getName());
                    trk.registerEvent(e);
                } else if (Function.class.isAssignableFrom(c)) {
                    Class<Function> cls = (Class<Function>) c;
                    if (klass.getModifiers().isAbstract()) {
                        // Abstract? Looks like they accidently @api'd
                        // a cheater class. We can't be sure that it is fully
                        // defined, so complain to the console.
                        CHLog.GetLogger().Log(CHLog.Tags.EXTENSIONS, LogLevel.ERROR, "Class " + c.getName() + " in " + url + " is" + " marked as a function but is also abstract." + " Bugs might occur! Bug someone about this!", Target.UNKNOWN);
                    }
                    Function f = cls.newInstance();
                    functions.add(f.getName());
                    trk.registerFunction(f);
                }
            } catch (InstantiationException ex) {
                Static.getLogger().log(Level.SEVERE, ex.getMessage(), ex);
            } catch (IllegalAccessException ex) {
                Static.getLogger().log(Level.SEVERE, null, ex);
            }
        }
    }
    // Lets print out the details to the console, if we are in debug mode.
    try {
        if (Prefs.DebugMode()) {
            Collections.sort(events);
            String eventString = StringUtils.Join(events, ", ", ", and ", " and ");
            Collections.sort(functions);
            String functionString = StringUtils.Join(functions, ", ", ", and ", " and ");
            StreamUtils.GetSystemOut().println(Implementation.GetServerType().getBranding() + ": Loaded the following functions: " + functionString.trim());
            StreamUtils.GetSystemOut().println(Implementation.GetServerType().getBranding() + ": Loaded " + functions.size() + " function" + (functions.size() == 1 ? "." : "s."));
            StreamUtils.GetSystemOut().println(Implementation.GetServerType().getBranding() + ": Loaded the following events: " + eventString.trim());
            StreamUtils.GetSystemOut().println(Implementation.GetServerType().getBranding() + ": Loaded " + events.size() + " event" + (events.size() == 1 ? "." : "s."));
        }
    } catch (Throwable e) {
    // Prefs weren't loaded, probably caused by running tests.
    }
}
Also used : DynamicClassLoader(com.laytonsmith.PureUtilities.ClassLoading.DynamicClassLoader) MalformedURLException(java.net.MalformedURLException) ArrayList(java.util.ArrayList) ClassMirror(com.laytonsmith.PureUtilities.ClassLoading.ClassMirror.ClassMirror) URL(java.net.URL) CFunction(com.laytonsmith.core.constructs.CFunction) Function(com.laytonsmith.core.functions.Function) SimpleVersion(com.laytonsmith.PureUtilities.SimpleVersion) Event(com.laytonsmith.core.events.Event) File(java.io.File)

Example 4 with SimpleVersion

use of com.laytonsmith.PureUtilities.SimpleVersion in project CommandHelper by EngineHub.

the class Main method loadSelfVersion.

@SuppressWarnings({ "ThrowableInstanceNotThrown", "ThrowableInstanceNeverThrown" })
public static SimpleVersion loadSelfVersion() throws Exception {
    File file = new File(new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI()), "plugin.yml");
    ZipReader reader = new ZipReader(file);
    if (!reader.exists()) {
        throw new FileNotFoundException(String.format("%s does not exist", file.getPath()));
    }
    try {
        String contents = reader.getFileContents();
        Yaml yaml = new Yaml();
        Map<String, Object> map = (Map<String, Object>) yaml.load(contents);
        return new SimpleVersion((String) map.get("version"));
    } catch (RuntimeException | IOException ex) {
        throw new Exception(ex);
    }
}
Also used : FileNotFoundException(java.io.FileNotFoundException) ZipReader(com.laytonsmith.PureUtilities.ZipReader) CString(com.laytonsmith.core.constructs.CString) IOException(java.io.IOException) Yaml(org.yaml.snakeyaml.Yaml) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) HeadlessException(java.awt.HeadlessException) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) SimpleVersion(com.laytonsmith.PureUtilities.SimpleVersion) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap)

Example 5 with SimpleVersion

use of com.laytonsmith.PureUtilities.SimpleVersion in project CommandHelper by EngineHub.

the class CommandHelperPlugin method onEnable.

/**
 * Called on plugin enable.
 */
@Override
public void onEnable() {
    if (loadingThread.isAlive()) {
        StreamUtils.GetSystemOut().println("[CommandHelper] Waiting for extension loading to complete...");
        try {
            loadingThread.join();
        } catch (InterruptedException ex) {
            Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    myServer = StaticLayer.GetServer();
    BukkitMCEntityType.build();
    BukkitMCBiomeType.build();
    BukkitMCSound.build();
    // Metrics
    try {
        Metrics m = new Metrics(this);
        Metrics.Graph graph = m.createGraph("Player count");
        graph.addPlotter(new Metrics.Plotter("Player count") {

            @Override
            public int getValue() {
                return Static.getServer().getOnlinePlayers().size();
            }
        });
        m.addGraph(graph);
        m.start();
    } catch (IOException e) {
    // Failed to submit the stats :-(
    }
    try {
        // This may seem redundant, but on a /reload, we want to refresh these
        // properties.
        Prefs.init(CommandHelperFileLocations.getDefault().getPreferencesFile());
    } catch (IOException ex) {
        Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (Prefs.UseSudoFallback()) {
        Logger.getLogger(CommandHelperPlugin.class.getName()).log(Level.WARNING, "In your preferences, use-sudo-fallback is turned on. Consider turning this off if you can.");
    }
    CHLog.initialize(CommandHelperFileLocations.getDefault().getConfigDirectory());
    version = new SimpleVersion(getDescription().getVersion());
    String script_name = Prefs.ScriptName();
    String main_file = Prefs.MainFile();
    boolean showSplashScreen = Prefs.ShowSplashScreen();
    if (showSplashScreen) {
        StreamUtils.GetSystemOut().println(TermColors.reset());
        // StreamUtils.GetSystemOut().flush();
        StreamUtils.GetSystemOut().println("\n\n" + Static.Logo());
    }
    ac = new AliasCore(new File(CommandHelperFileLocations.getDefault().getConfigDirectory(), script_name), CommandHelperFileLocations.getDefault().getLocalPackagesDirectory(), CommandHelperFileLocations.getDefault().getPreferencesFile(), new File(CommandHelperFileLocations.getDefault().getConfigDirectory(), main_file), this);
    ac.reload(null, null, true);
    // Clear out our hostname cache
    hostnameLookupCache = new ConcurrentHashMap<>();
    // Create a new thread pool, with a custom ThreadFactory,
    // so we can more clearly name our threads.
    hostnameLookupThreadPool = Executors.newFixedThreadPool(3, new ThreadFactory() {

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "CommandHelperHostnameLookup-" + (++hostnameThreadPoolID));
        }
    });
    for (Player p : getServer().getOnlinePlayers()) {
        // Repopulate our cache for currently online players.
        // New players that join later will get a lookup done
        // on them at that time.
        Static.HostnameCache(p.getName(), p.getAddress());
    }
    BukkitDirtyRegisteredListener.PlayDirty();
    registerEvents(playerListener);
    // interpreter events
    registerEvents(interpreterListener);
    registerEvents(serverListener);
    // Script events
    StaticLayer.Startup(this);
    playerListener.loadGlobalAliases();
    interpreterListener.reload();
    Static.getLogger().log(Level.INFO, "[CommandHelper] CommandHelper {0} enabled", getDescription().getVersion());
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) Player(org.bukkit.entity.Player) BukkitMCPlayer(com.laytonsmith.abstraction.bukkit.entities.BukkitMCPlayer) MCPlayer(com.laytonsmith.abstraction.MCPlayer) AliasCore(com.laytonsmith.core.AliasCore) IOException(java.io.IOException) Metrics(org.mcstats.Metrics) SimpleVersion(com.laytonsmith.PureUtilities.SimpleVersion) File(java.io.File)

Aggregations

SimpleVersion (com.laytonsmith.PureUtilities.SimpleVersion)5 File (java.io.File)4 IOException (java.io.IOException)3 CString (com.laytonsmith.core.constructs.CString)2 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)2 ConfigCompileGroupException (com.laytonsmith.core.exceptions.ConfigCompileGroupException)2 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)2 Function (com.laytonsmith.core.functions.Function)2 ClassDiscoveryCache (com.laytonsmith.PureUtilities.ClassLoading.ClassDiscoveryCache)1 ClassMirror (com.laytonsmith.PureUtilities.ClassLoading.ClassMirror.ClassMirror)1 DynamicClassLoader (com.laytonsmith.PureUtilities.ClassLoading.DynamicClassLoader)1 ZipReader (com.laytonsmith.PureUtilities.ZipReader)1 MCPlayer (com.laytonsmith.abstraction.MCPlayer)1 BukkitMCPlayer (com.laytonsmith.abstraction.bukkit.entities.BukkitMCPlayer)1 AliasCore (com.laytonsmith.core.AliasCore)1 UpgradeLog (com.laytonsmith.core.UpgradeLog)1 CArray (com.laytonsmith.core.constructs.CArray)1 CBoolean (com.laytonsmith.core.constructs.CBoolean)1 CDouble (com.laytonsmith.core.constructs.CDouble)1 CEntry (com.laytonsmith.core.constructs.CEntry)1