use of com.laytonsmith.core.functions.Function in project CommandHelper by EngineHub.
the class StaticTest method TestBoilerplate.
/**
* Tests the boilerplate functions in a Function. While all functions should conform to at least this, it is useful
* to also use the more strict TestBoilerplate function.
*
* @param ff
* @param name
* @throws java.lang.Exception
*/
public static void TestBoilerplate(FunctionBase ff, String name) throws Exception {
if (!(ff instanceof Function)) {
return;
}
Function f = (Function) ff;
// For the "quality test code coverage" number, set this to true
boolean runQualityTestsOnly = false;
MCServer fakeServer = StaticTest.GetFakeServer();
MCPlayer fakePlayer = StaticTest.GetOnlinePlayer("Player01", fakeServer);
// make sure that these functions don't throw an exception. Any other results
// are fine
f.isRestricted();
f.runAsync();
f.preResolveVariables();
f.thrown();
// name should match the given value
if (!f.getName().equals(name)) {
fail("Expected name of function to be " + name + ", but was given " + f.getName());
}
// requirement set.
if (f.docs().length() <= 0) {
fail("docs must return a non-empty string");
}
TestDocs(f);
if (f.numArgs().length == 0) {
fail("numArgs must return an Integer array with more than zero values");
}
// If we are interested in tests that are specific to the functions however, we shouldn't run this.
if (!runQualityTestsOnly && f.getClass().getAnnotation(noboilerplate.class) == null) {
TestExec(f, fakePlayer, "fake player");
TestExec(f, null, "null command sender");
TestExec(f, StaticTest.GetFakeConsoleCommandSender(), "fake console command sender");
}
// Same thing for optimize/canOptimize and optimizeDynamic/canOptimizeDynamic
if (f instanceof Optimizable) {
Set<Optimizable.OptimizationOption> options = ((Optimizable) f).optimizationOptions();
if (options.contains(Optimizable.OptimizationOption.CONSTANT_OFFLINE) && options.contains(Optimizable.OptimizationOption.OPTIMIZE_CONSTANT)) {
fail(f.getName() + " declares both CONSTANT_OFFLINE and OPTIMIZE_CONSTANT, which are mutually exclusive.");
}
}
for (Method method : f.getClass().getDeclaredMethods()) {
if (method.getName().equals("execs")) {
if (!f.useSpecialExec()) {
fail(f.getName() + " declares execs, but returns false for useSpecialExec.");
}
}
if (f instanceof Optimizable) {
Set<Optimizable.OptimizationOption> options = ((Optimizable) f).optimizationOptions();
if (method.getName().equals("optimize")) {
if (!options.contains(Optimizable.OptimizationOption.OPTIMIZE_CONSTANT)) {
fail(f.getName() + " declares optimize, but does not declare that it can OPTIMIZE_CONSTANT");
}
}
if (method.getName().equals("optimizeDynamic")) {
if (!options.contains(Optimizable.OptimizationOption.OPTIMIZE_DYNAMIC)) {
fail(f.getName() + " declares optimizeDynamic, but does not declare that it can OPTIMIZE_DYNAMIC");
}
}
}
}
// now the only function left to test is exec. This cannot be abstracted, unfortunately.
}
use of com.laytonsmith.core.functions.Function in project CommandHelper by EngineHub.
the class RandomTests method testFunctionsAreOnlyDefinedOnce.
@Test
public void testFunctionsAreOnlyDefinedOnce() throws Exception {
Set<String> uhohs = new HashSet<>();
Set<Class<Function>> set = ClassDiscovery.getDefaultInstance().loadClassesThatExtend(Function.class);
for (Class<Function> cf1 : set) {
for (Class<Function> cf2 : set) {
if (cf1 == cf2) {
continue;
}
api cf1a = cf1.getAnnotation(api.class);
api cf2a = cf2.getAnnotation(api.class);
if (cf1a == null || cf2a == null) {
continue;
}
if (!Arrays.equals(cf1a.platform(), cf2a.platform())) {
continue;
}
Function f1 = ReflectionUtils.instantiateUnsafe(cf1);
Function f2 = ReflectionUtils.instantiateUnsafe(cf2);
if (f1.getName().equals(f2.getName())) {
uhohs.add(f1.getName() + " is implemented in two places, " + cf1 + " and " + cf2);
}
}
}
if (!uhohs.isEmpty()) {
fail(StringUtils.Join(uhohs, "\n"));
}
}
use of com.laytonsmith.core.functions.Function 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.
}
}
use of com.laytonsmith.core.functions.Function in project CommandHelper by EngineHub.
the class SyntaxHighlighters method macro.
private static String macro(String macroName) {
String[] split = macroName.split(":");
String type = split[0];
String datalist = split[1];
List<String> params = new ArrayList<>();
for (int i = 2; i < split.length; i++) {
params.add(split[i].toLowerCase());
}
List<String> base = new ArrayList<>();
if (datalist.equalsIgnoreCase("colors")) {
for (MCChatColor c : MCChatColor.values()) {
base.add(c.name());
}
} else if (datalist.equalsIgnoreCase("keywords")) {
for (String keyword : SimpleSyntaxHighlighter.KEYWORDS) {
base.add(keyword);
}
} else if (datalist.equalsIgnoreCase("functions")) {
for (Function f : GetFunctions()) {
if (SimpleSyntaxHighlighter.KEYWORDS.contains(f.getName())) {
// Keywords override functions
continue;
}
if (!f.appearInDocumentation()) {
continue;
}
if (params.contains("restricted") || params.contains("unrestricted")) {
if (params.contains("restricted") && f.isRestricted()) {
base.add(f.getName());
} else if (params.contains("unrestricted") && !f.isRestricted()) {
base.add(f.getName());
}
} else {
base.add(f.getName());
}
}
} else if (datalist.equalsIgnoreCase("events")) {
for (Documentation d : GetEvents()) {
base.add(d.getName());
}
} else if (datalist.equalsIgnoreCase("exceptions")) {
for (Class<? extends CREThrowable> c : ClassDiscovery.getDefaultInstance().loadClassesWithAnnotationThatExtend(typeof.class, CREThrowable.class)) {
base.add(c.getAnnotation(typeof.class).value());
}
} else if (datalist.equalsIgnoreCase("types")) {
base.addAll(NativeTypeList.getNativeTypeList());
// Null is technically in the list, but it shouldn't be added.
base.remove("null");
} else if (datalist.equalsIgnoreCase("enums")) {
Set<String> set = new HashSet<>();
Set<Class<? extends Enum>> enums = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotationThatExtend(MEnum.class, Enum.class);
for (Class<? extends Enum> e : enums) {
Enum[] es = e.getEnumConstants();
for (Enum ee : es) {
set.add(ee.name());
}
}
base.addAll(set);
} else if (datalist.equalsIgnoreCase("fileOptions")) {
for (Field f : FileOptions.class.getDeclaredFields()) {
base.add(f.getName());
}
}
String header = "";
String spliter = "IMPROPER FORMATTING";
String footer = "";
if (type.equalsIgnoreCase("space")) {
if (params.contains("quoted")) {
header = "'";
spliter = "' '";
footer = "'";
} else {
spliter = " ";
}
} else if (type.equalsIgnoreCase("comma")) {
if (params.contains("quoted")) {
header = "'";
spliter = "', '";
footer = "'";
} else {
spliter = ", ";
}
} else if (type.equalsIgnoreCase("pipe")) {
if (params.contains("quoted")) {
header = "'";
spliter = "|";
footer = "'";
} else {
spliter = "|";
}
} else if (type.equalsIgnoreCase("xml")) {
String tag = "PLEASE INCLUDE THE TAG NAME USING tag=tagname AS A PARAMETER";
for (String param : params) {
// Find the tag name
if (param.matches("tag=.*")) {
tag = param.substring(4);
break;
}
}
if (params.contains("quoted")) {
header = "<" + tag + ">'";
spliter = "'</" + tag + "><" + tag + ">'";
footer = "'</" + tag + ">";
} else {
header = "<" + tag + ">";
spliter = "</" + tag + "><" + tag + ">";
footer = "</" + tag + ">";
}
}
return header + Join(base, spliter) + footer;
}
use of com.laytonsmith.core.functions.Function in project CommandHelper by EngineHub.
the class SiteDeploy method deployAPI.
private void deployAPI() {
generateQueue.submit(new Runnable() {
@Override
public void run() {
try {
Set<Class<? extends Function>> functionClasses = new TreeSet<>(new Comparator<Class<? extends Function>>() {
@Override
public int compare(Class<? extends Function> o1, Class<? extends Function> o2) {
Function f1 = ReflectionUtils.instantiateUnsafe(o1);
Function f2 = ReflectionUtils.instantiateUnsafe(o2);
return f1.getName().compareTo(f2.getName());
}
});
functionClasses.addAll(ClassDiscovery.getDefaultInstance().loadClassesWithAnnotationThatExtend(api.class, Function.class));
// A map of where it maps the enclosing class to the list of function rows, which contains a list of
// table cells.
Map<Class<?>, List<List<String>>> data = new TreeMap<>(new Comparator<Class<?>>() {
@Override
public int compare(Class<?> o1, Class<?> o2) {
return o1.getCanonicalName().compareTo(o2.getCanonicalName());
}
});
List<String> hiddenFunctions = new ArrayList<>();
for (Class<? extends Function> functionClass : functionClasses) {
if (!data.containsKey(functionClass.getEnclosingClass())) {
data.put(functionClass.getEnclosingClass(), new ArrayList<List<String>>());
}
List<List<String>> d = data.get(functionClass.getEnclosingClass());
List<String> c = new ArrayList<>();
// function name, returns, arguments, throws, description, restricted
final Function f;
try {
f = ReflectionUtils.instantiateUnsafe(functionClass);
} catch (ReflectionUtils.ReflectionException ex) {
throw new RuntimeException("While trying to construct " + functionClass + ", got the following", ex);
}
final DocGen.DocInfo di = new DocGen.DocInfo(f.docs());
// If the function is hidden, we don't want to put it on the main page by default. Regardless,
// we do want to generate the function page, it will just remain unlinked.
generateQueue.submit(new Runnable() {
@Override
public void run() {
generateFunctionDocs(f, di);
}
});
if (f.since().equals(CHVersion.V0_0_0)) {
// Don't add these
continue;
}
if (f.getClass().getAnnotation(hide.class) != null) {
hiddenFunctions.add(f.getName());
}
c.add("[[API/functions/" + f.getName() + "|" + f.getName() + "]]()");
c.add(di.ret);
c.add(di.args);
List<String> exc = new ArrayList<>();
if (f.thrown() != null) {
for (Class<? extends CREThrowable> e : f.thrown()) {
CREThrowable ct = ReflectionUtils.instantiateUnsafe(e);
exc.add("{{object|" + ct.getName() + "}}");
}
}
c.add(StringUtils.Join(exc, "<br>"));
StringBuilder desc = new StringBuilder();
desc.append(HTMLUtils.escapeHTML(di.desc));
if (di.extendedDesc != null) {
desc.append(" [[functions/").append(f.getName()).append("|See more...]]<br>\n");
}
try {
if (f.examples() != null && f.examples().length > 0) {
desc.append("<br>([[API/functions/").append(f.getName()).append("#Examples|Examples...]])\n");
}
} catch (ConfigCompileException | NoClassDefFoundError ex) {
Logger.getLogger(SiteDeploy.class.getName()).log(Level.SEVERE, null, ex);
}
c.add(desc.toString());
c.add("<span class=\"api_" + (f.isRestricted() ? "yes" : "no") + "\">" + (f.isRestricted() ? "Yes" : "No") + "</span>");
d.add(c);
}
// data is now constructed.
StringBuilder b = new StringBuilder();
b.append("<ul id=\"TOC\">");
for (Class<?> clazz : data.keySet()) {
b.append("<li><a href=\"#").append(clazz.getSimpleName()).append("\">").append(clazz.getSimpleName()).append("</a></li>");
}
b.append("</ul>\n");
for (Map.Entry<Class<?>, List<List<String>>> e : data.entrySet()) {
Class<?> clazz = e.getKey();
List<List<String>> clazzData = e.getValue();
if (clazzData.isEmpty()) {
// if all the class's functions are hidden with @hide.
continue;
}
try {
b.append("== ").append(clazz.getSimpleName()).append(" ==\n");
String docs = (String) ReflectionUtils.invokeMethod(clazz, null, "docs");
b.append("<div>").append(docs).append("</div>\n\n");
b.append("{|\n|-\n");
b.append("! scope=\"col\" width=\"6%\" | Function Name\n" + "! scope=\"col\" width=\"5%\" | Returns\n" + "! scope=\"col\" width=\"10%\" | Arguments\n" + "! scope=\"col\" width=\"10%\" | Throws\n" + "! scope=\"col\" width=\"64%\" | Description\n" + "! scope=\"col\" width=\"5%\" | <span class=\"abbr\" title=\"Restricted\">Res</span>\n");
for (List<String> row : clazzData) {
b.append("|-");
if (hiddenFunctions.contains(row.get(0))) {
b.append(" class=\"hiddenFunction\"");
}
b.append("\n");
for (String cell : row) {
b.append("| ").append(cell).append("\n");
}
}
b.append("|}\n");
b.append("<p><a href=\"#TOC\">Back to top</a></p>\n");
} catch (Error ex) {
Logger.getLogger(SiteDeploy.class.getName()).log(Level.SEVERE, "While processing " + clazz + " got:", ex);
}
}
b.append("<div><a href=\"#\" id=\"showHidden\">Show hidden</a></div>");
b.append("<script type=\"text/javascript\">\n" + "pageRender.then(function() {\n" + "$('#showHidden').click(function(event){\n" + "$('.hiddenFunction').removeClass('hiddenFunction');\n" + "$('#showHidden').remove();\n" + "event.preventDefault();\nreturn false;\n" + "});\n" + "});\n" + "</script>");
writePage("API", b.toString(), "API.html", Arrays.asList(new String[] { "API", "functions" }), "A list of all " + Implementation.GetServerType().getBranding() + " functions");
currentGenerateTask.addAndGet(1);
} catch (Error ex) {
ex.printStackTrace(System.err);
}
}
});
totalGenerateTasks.addAndGet(1);
}
Aggregations