/** * Get the bsh method matching the specified signature declared in this name space or a parent. * * <p>Note: this method is primarily intended for use internally. If you use this method outside * of the bsh package you will have to be familiar with BeanShell's use of the Primitive wrapper * class. * * @see bsh.Primitive * @return the BshMethod or null if not found * @param declaredOnly if true then only methods declared directly in this namespace will be found * and no inherited or imported methods will be visible. */ public BshMethod getMethod(String name, Class[] sig, boolean declaredOnly) throws UtilEvalError { BshMethod method = null; // Change import precedence if we are a class body/instance // Get import first. if (method == null && isClass && !declaredOnly) method = getImportedMethod(name, sig); if (method == null && methods != null) { List<BshMethod> list = methods.get(name); if (list != null) { // Apply most specific signature matching Class[][] candidates = new Class[list.size()][]; for (int i = 0; i < candidates.length; i++) candidates[i] = list.get(i).getParameterTypes(); int match = Reflect.findMostSpecificSignature(sig, candidates); if (match != -1) method = list.get(match); } } if (method == null && !isClass && !declaredOnly) method = getImportedMethod(name, sig); // try parent if (!declaredOnly && (method == null) && (parent != null)) return parent.getMethod(name, sig); return method; }
@Override public Item item(final QueryContext qc, final InputInfo ii) throws QueryException { checkCreate(qc); final String driver = string(toToken(exprs[0], qc)); if (Reflect.find(driver) == null) throw BXSQ_DRIVER_X.get(info, driver); return null; }
public static Object invokeSuperclassMethodImpl( BshClassManager bcm, Object instance, String methodName, Object[] args) throws UtilEvalError, ReflectError, InvocationTargetException { String superName = ClassGeneratorUtil.BSHSUPER + methodName; // look for the specially named super delegate method Class clas = instance.getClass(); Method superMethod = Reflect.resolveJavaMethod(bcm, clas, superName, Types.getTypes(args), false /*onlyStatic*/); if (superMethod != null) return Reflect.invokeMethod(superMethod, instance, args); // No super method, try to invoke regular method // could be a superfluous "super." which is legal. Class superClass = clas.getSuperclass(); superMethod = Reflect.resolveExpectedJavaMethod( bcm, superClass, instance, methodName, args, false /*onlyStatic*/); return Reflect.invokeMethod(superMethod, instance, args); }
protected Variable getImportedVar(String name) throws UtilEvalError { // Try object imports if (importedObjects != null) for (int i = 0; i < importedObjects.size(); i++) { Object object = importedObjects.get(i); Class clas = object.getClass(); Field field = Reflect.resolveJavaField(clas, name, false /*onlyStatic*/); if (field != null) return new Variable(name, field.getType(), new LHS(object, field)); } // Try static imports if (importedStatic != null) for (int i = 0; i < importedStatic.size(); i++) { Class clas = importedStatic.get(i); Field field = Reflect.resolveJavaField(clas, name, true /*onlyStatic*/); if (field != null) return new Variable(name, field.getType(), new LHS(field)); } return null; }
protected BshMethod getImportedMethod(String name, Class[] sig) throws UtilEvalError { // Try object imports if (importedObjects != null) for (int i = 0; i < importedObjects.size(); i++) { Object object = importedObjects.get(i); Class clas = object.getClass(); Method method = Reflect.resolveJavaMethod(getClassManager(), clas, name, sig, false /*onlyStatic*/); if (method != null) return new BshMethod(method, object); } // Try static imports if (importedStatic != null) for (int i = 0; i < importedStatic.size(); i++) { Class clas = importedStatic.get(i); Method method = Reflect.resolveJavaMethod(getClassManager(), clas, name, sig, true /*onlyStatic*/); if (method != null) return new BshMethod(method, null /*object*/); } return null; }
@Override public JapaneseTokenizer init(final byte[] txt) { String source = string(txt); if (wc) { // convert wide-space to space source = source.replace('\u3000', '\u0020'); } final ArrayList<?> morpheme = (ArrayList<?>) Reflect.invoke(parse, tagger, source); final ArrayList<Morpheme> list = new ArrayList<>(); try { int prev = 0; final int ms = morpheme.size(); for (int i = 0; i < ms; i++) { final Object m = morpheme.get(i); final String srfc = surface.get(m).toString(); final String ftr = feature.get(m).toString(); final int strt = start.getInt(m); if (i != 0) { final int l = strt - prev; if (l != 0) { list.add(new Morpheme(source.substring(strt - 1, strt + l - 1), KIGOU_FEATURE)); } } prev = srfc.length() + strt; // separates continuous mark (ASCII) boolean cont = true; final ArrayList<Morpheme> marks = new ArrayList<>(); final int sl = srfc.length(); for (int s = 0; s < sl; s++) { final String c = String.valueOf(srfc.charAt(s)); final byte[] t = token(c); if (t.length == 1) { if (letter(t[0]) || digit(t[0])) cont = false; else marks.add(new Morpheme(c, KIGOU_FEATURE)); } else { cont = false; } } if (cont) list.addAll(marks); else list.add(new Morpheme(srfc, ftr)); } } catch (final Exception ex) { Util.errln(Util.className(this) + ": " + ex); } tokenList = list; tokens = list.iterator(); return this; }
public void initialize( ModelBiped modelBipedMain, ModelBiped modelArmorChestplate, ModelBiped modelArmor, float shadowSize) { this.mainModel = modelBipedMain; this.shadowSize = shadowSize; Reflect.SetField( net.minecraft.client.renderer.entity.RenderPlayer.class, this, SmartRenderInstall.RenderPlayer_modelBipedMain, modelBipedMain); Reflect.SetField( net.minecraft.client.renderer.entity.RenderPlayer.class, this, SmartRenderInstall.RenderPlayer_modelArmorChestplate, this.modelArmorChestplate = modelArmorChestplate); Reflect.SetField( net.minecraft.client.renderer.entity.RenderPlayer.class, this, SmartRenderInstall.RenderPlayer_modelArmor, this.modelArmor = modelArmor); }
private void throwTypeError(Class baseType, Object initializer, int argNum, CallStack callstack) throws EvalError { String rhsType; if (initializer instanceof Primitive) rhsType = ((Primitive) initializer).getType().getName(); else rhsType = Reflect.normalizeClassName(initializer.getClass()); throw new EvalError( "Incompatible type: " + rhsType + " in initializer of array type: " + baseType + " at position: " + argNum, this, callstack); }
static { IOFile dic = null; if (Reflect.available(PATTERN)) { dic = new IOFile(LANG); if (!dic.exists()) { dic = new IOFile(Prop.HOME, "etc/" + LANG); if (!dic.exists()) { available = false; } } } else { available = false; } if (available) { Class<?> clz = Reflect.find(PATTERN); if (clz == null) { Util.debug("Could not initialize Igo Japanese lexer."); } else { /* Igo constructor. */ final Constructor<?> tgr = Reflect.find(clz, String.class); tagger = Reflect.get(tgr, dic.path()); if (tagger == null) { available = false; Util.debug("Could not initialize Igo Japanese lexer."); } else { parse = Reflect.method(clz, "parse", CharSequence.class); if (parse == null) { Util.debug("Could not initialize Igo lexer method."); } clz = Reflect.find("net.reduls.igo.Morpheme"); surface = Reflect.field(clz, "surface"); feature = Reflect.field(clz, "feature"); start = Reflect.field(clz, "start"); } } } }
/** * Converts an HTML document to XML. * * @param io io reference * @param opts html options * @return parser * @throws IOException I/O exception */ private static IO toXML(final IO io, final HtmlOptions opts) throws IOException { // reader could not be initialized; fall back to XML if (READER == null) return io; try { // tries to extract the encoding from the input final TextInput ti = new TextInput(io); String enc = ti.encoding(); final byte[] content = ti.content(); // looks for a charset definition final byte[] encoding = token("charset="); int cs = indexOf(content, encoding); if (cs > 0) { // extracts the encoding string cs += encoding.length; int ce = cs; final int cl = content.length; while (++ce < cl && content[ce] > 0x28) ; enc = string(substring(content, cs, ce)); } // define input final InputSource is = new InputSource(new ArrayInput(content)); is.setEncoding(supported(enc) ? normEncoding(enc) : UTF8); // define output final StringWriter sw = new StringWriter(); final XMLReader reader = (XMLReader) Reflect.get(READER); final Object writer = Reflect.get(WRITER, sw); // set TagSoup options if (opts.get(HtmlOptions.HTML)) { reader.setFeature("http://xml.org/sax/features/namespaces", false); opt("method", "html"); opt("omit-xml-declaration", "yes"); } if (opts.get(HtmlOptions.NONS)) reader.setFeature("http://xml.org/sax/features/namespaces", false); if (opts.get(HtmlOptions.OMITXML)) opt("omit-xml-declaration", "yes"); if (opts.get(HtmlOptions.NOBOGONS)) reader.setFeature(FEATURES + "ignore-bogons", true); if (opts.get(HtmlOptions.NODEFAULTS)) reader.setFeature(FEATURES + "default-attributes", false); if (opts.get(HtmlOptions.NOCOLONS)) reader.setFeature(FEATURES + "translate-colons", true); if (opts.get(HtmlOptions.NORESTART)) reader.setFeature(FEATURES + "restart-elements", false); if (opts.get(HtmlOptions.IGNORABLE)) reader.setFeature(FEATURES + "ignorable-whitespace", true); if (opts.get(HtmlOptions.EMPTYBOGONS)) reader.setFeature(FEATURES + "bogons-empty", true); if (opts.get(HtmlOptions.ANY)) reader.setFeature(FEATURES + "bogons-empty", false); if (opts.get(HtmlOptions.NOROOTBOGONS)) reader.setFeature(FEATURES + "root-bogons", false); if (opts.get(HtmlOptions.NOCDATA)) reader.setFeature(FEATURES + "cdata-elements", false); if (opts.get(HtmlOptions.LEXICAL)) reader.setProperty("http://xml.org/sax/properties/lexical-handler", writer); if (opts.contains(HtmlOptions.METHOD)) opt("method", opts.get(HtmlOptions.METHOD)); if (opts.contains(HtmlOptions.DOCTYPESYS)) opt("doctype-system", opts.get(HtmlOptions.DOCTYPESYS)); if (opts.contains(HtmlOptions.DOCTYPEPUB)) opt("doctype-public", opts.get(HtmlOptions.DOCTYPEPUB)); if (opts.contains(HtmlOptions.ENCODING)) is.setEncoding(opts.get(HtmlOptions.ENCODING)); // end TagSoup options reader.setContentHandler((ContentHandler) writer); reader.parse(is); return new IOContent(token(sw.toString()), io.name()); } catch (final SAXException ex) { Util.errln(ex); return io; } }
/** * This class uses TagSoup to convert HTML input to well-formed XML. If TagSoup is not found in the * classpath, the original document is passed on. * * <p>TagSoup was written by John Cowan and is based on the Apache 2.0 License: {@code * http://home.ccil.org/~cowan/XML/tagsoup/}. * * @author BaseX Team 2005-14, BSD License * @author Christian Gruen */ public final class HtmlParser extends XMLParser { /** Name of HTML Parser. */ private static final String NAME = "TagSoup"; /** TagSoup URL. */ private static final String FEATURES = "http://www.ccil.org/~cowan/tagsoup/features/"; /** XML parser class string. */ private static final String PCLASS = "org.ccil.cowan.tagsoup.Parser"; /** XML writer class string. */ private static final String WCLASS = "org.ccil.cowan.tagsoup.XMLWriter"; /** HTML reader. */ private static final Class<?> READER = Reflect.find(PCLASS); /** HTML writer. */ private static final Constructor<?> WRITER = Reflect.find(Reflect.find(WCLASS), Writer.class); /** XML writer output property method. */ private static final Method METHOD = Reflect.method( Reflect.find(WCLASS), "setOutputProperty", new Class[] {String.class, String.class}); /** * Checks if a CatalogResolver is available. * * @return result of check */ public static boolean available() { return READER != null; } /** * Returns the name of the parser, or an empty string. * * @return name of parser */ public static String parser() { return available() ? NAME : ""; } /** * Constructor. * * @param source document source * @param opts database options * @throws IOException I/O exception */ public HtmlParser(final IO source, final MainOptions opts) throws IOException { this(source, opts, opts.get(MainOptions.HTMLPARSER)); } /** * Constructor. * * @param source document source * @param opts database options * @param hopts html options * @throws IOException I/O exception */ public HtmlParser(final IO source, final MainOptions opts, final HtmlOptions hopts) throws IOException { super(toXML(source, hopts), opts); } /** * Converts an HTML document to XML. * * @param io io reference * @param opts html options * @return parser * @throws IOException I/O exception */ private static IO toXML(final IO io, final HtmlOptions opts) throws IOException { // reader could not be initialized; fall back to XML if (READER == null) return io; try { // tries to extract the encoding from the input final TextInput ti = new TextInput(io); String enc = ti.encoding(); final byte[] content = ti.content(); // looks for a charset definition final byte[] encoding = token("charset="); int cs = indexOf(content, encoding); if (cs > 0) { // extracts the encoding string cs += encoding.length; int ce = cs; final int cl = content.length; while (++ce < cl && content[ce] > 0x28) ; enc = string(substring(content, cs, ce)); } // define input final InputSource is = new InputSource(new ArrayInput(content)); is.setEncoding(supported(enc) ? normEncoding(enc) : UTF8); // define output final StringWriter sw = new StringWriter(); final XMLReader reader = (XMLReader) Reflect.get(READER); final Object writer = Reflect.get(WRITER, sw); // set TagSoup options if (opts.get(HtmlOptions.HTML)) { reader.setFeature("http://xml.org/sax/features/namespaces", false); opt("method", "html"); opt("omit-xml-declaration", "yes"); } if (opts.get(HtmlOptions.NONS)) reader.setFeature("http://xml.org/sax/features/namespaces", false); if (opts.get(HtmlOptions.OMITXML)) opt("omit-xml-declaration", "yes"); if (opts.get(HtmlOptions.NOBOGONS)) reader.setFeature(FEATURES + "ignore-bogons", true); if (opts.get(HtmlOptions.NODEFAULTS)) reader.setFeature(FEATURES + "default-attributes", false); if (opts.get(HtmlOptions.NOCOLONS)) reader.setFeature(FEATURES + "translate-colons", true); if (opts.get(HtmlOptions.NORESTART)) reader.setFeature(FEATURES + "restart-elements", false); if (opts.get(HtmlOptions.IGNORABLE)) reader.setFeature(FEATURES + "ignorable-whitespace", true); if (opts.get(HtmlOptions.EMPTYBOGONS)) reader.setFeature(FEATURES + "bogons-empty", true); if (opts.get(HtmlOptions.ANY)) reader.setFeature(FEATURES + "bogons-empty", false); if (opts.get(HtmlOptions.NOROOTBOGONS)) reader.setFeature(FEATURES + "root-bogons", false); if (opts.get(HtmlOptions.NOCDATA)) reader.setFeature(FEATURES + "cdata-elements", false); if (opts.get(HtmlOptions.LEXICAL)) reader.setProperty("http://xml.org/sax/properties/lexical-handler", writer); if (opts.contains(HtmlOptions.METHOD)) opt("method", opts.get(HtmlOptions.METHOD)); if (opts.contains(HtmlOptions.DOCTYPESYS)) opt("doctype-system", opts.get(HtmlOptions.DOCTYPESYS)); if (opts.contains(HtmlOptions.DOCTYPEPUB)) opt("doctype-public", opts.get(HtmlOptions.DOCTYPEPUB)); if (opts.contains(HtmlOptions.ENCODING)) is.setEncoding(opts.get(HtmlOptions.ENCODING)); // end TagSoup options reader.setContentHandler((ContentHandler) writer); reader.parse(is); return new IOContent(token(sw.toString()), io.name()); } catch (final SAXException ex) { Util.errln(ex); return io; } } /** * Reflection invoke XMLWriter.setOutputProperty(). * * @param name property * @param value value */ private static void opt(final String name, final String value) { Reflect.invoke(METHOD, WRITER, name, value); } }
/** * Reflection invoke XMLWriter.setOutputProperty(). * * @param name property * @param value value */ private static void opt(final String name, final String value) { Reflect.invoke(METHOD, WRITER, name, value); }
/** * Parse the BSHBlock for for the class definition and generate the class using ClassGenerator. */ public static Class generateClassImpl( String name, Modifiers modifiers, Class[] interfaces, Class superClass, BSHBlock block, boolean isInterface, CallStack callstack, Interpreter interpreter) throws EvalError { // Scripting classes currently requires accessibility // This can be eliminated with a bit more work. try { Capabilities.setAccessibility(true); } catch (Capabilities.Unavailable e) { throw new EvalError( "Defining classes currently requires reflective Accessibility.", block, callstack); } NameSpace enclosingNameSpace = callstack.top(); String packageName = enclosingNameSpace.getPackage(); String className = enclosingNameSpace.isClass ? (enclosingNameSpace.getName() + "$" + name) : name; String fqClassName = packageName == null ? className : packageName + "." + className; BshClassManager bcm = interpreter.getClassManager(); // Race condition here... bcm.definingClass(fqClassName); // Create the class static namespace NameSpace classStaticNameSpace = new NameSpace(enclosingNameSpace, className); classStaticNameSpace.isClass = true; callstack.push(classStaticNameSpace); // Evaluate any inner class class definitions in the block // effectively recursively call this method for contained classes first block.evalBlock(callstack, interpreter, true /*override*/, ClassNodeFilter.CLASSCLASSES); // Generate the type for our class Variable[] variables = getDeclaredVariables(block, callstack, interpreter, packageName); DelayedEvalBshMethod[] methods = getDeclaredMethods(block, callstack, interpreter, packageName); ClassGeneratorUtil classGenerator = new ClassGeneratorUtil( modifiers, className, packageName, superClass, interfaces, variables, methods, classStaticNameSpace, isInterface); byte[] code = classGenerator.generateClass(); // if debug, write out the class file to debugClasses directory if (DEBUG_DIR != null) try { FileOutputStream out = new FileOutputStream(DEBUG_DIR + '/' + className + ".class"); out.write(code); out.close(); } catch (IOException e) { throw new IllegalStateException( "cannot create file " + DEBUG_DIR + '/' + className + ".class", e); } // Define the new class in the classloader Class genClass = bcm.defineClass(fqClassName, code); // import the unq name into parent enclosingNameSpace.importClass(fqClassName.replace('$', '.')); try { classStaticNameSpace.setLocalVariable( ClassGeneratorUtil.BSHINIT, block, false /*strictJava*/); } catch (UtilEvalError e) { throw new InterpreterError("unable to init static: " + e); } // Give the static space its class static import // important to do this after all classes are defined classStaticNameSpace.setClassStatic(genClass); // evaluate the static portion of the block in the static space block.evalBlock(callstack, interpreter, true /*override*/, ClassNodeFilter.CLASSSTATIC); callstack.pop(); if (!genClass.isInterface()) { // Set the static bsh This callback String bshStaticFieldName = ClassGeneratorUtil.BSHSTATIC + className; try { LHS lhs = Reflect.getLHSStaticField(genClass, bshStaticFieldName); lhs.assign(classStaticNameSpace.getThis(interpreter), false /*strict*/); } catch (Exception e) { throw new InterpreterError("Error in class gen setup: " + e); } } bcm.doneDefiningClass(fqClassName); return genClass; }
/** Hack - The real method is in Reflect.java which is not public. */ public static String normalizeClassName(Class type) { return Reflect.normalizeClassName(type); }
/** Sets up a default logger based on the name of the current class. */ public TestCase() { this.$log = LoggerFactory.getLogger("TestCase." + Reflect.getShortClassName(this)); }
/* Cast or check a cast of a primitive type to another type. Normally both types are primitive (e.g. numeric), but a null value (no type) may be cast to any type. <p/> @param toType is the target type of the cast. It is normally a java primitive TYPE, but in the case of a null cast can be any object type. @param fromType is the java primitive TYPE type of the primitive to be cast or null, to indicate that the fromValue was null or void. @param fromValue is, optionally, the value to be converted. If checkOnly is true fromValue must be null. If checkOnly is false, fromValue must be non-null (Primitive.NULL is of course valid). */ static Primitive castPrimitive( Class toType, Class fromType, Primitive fromValue, boolean checkOnly, int operation) throws UtilEvalError { /* Lots of preconditions checked here... Once things are running smoothly we might comment these out (That's what assertions are for). */ if (checkOnly && fromValue != null) throw new InterpreterError("bad cast param 1"); if (!checkOnly && fromValue == null) throw new InterpreterError("bad cast param 2"); if (fromType != null && !fromType.isPrimitive()) throw new InterpreterError("bad fromType:" + fromType); if (fromValue == Primitive.NULL && fromType != null) throw new InterpreterError("inconsistent args 1"); if (fromValue == Primitive.VOID && fromType != Void.TYPE) throw new InterpreterError("inconsistent args 2"); // can't cast void to anything if (fromType == Void.TYPE) if (checkOnly) return Types.INVALID_CAST; else throw Types.castError(Reflect.normalizeClassName(toType), "void value", operation); // unwrap Primitive fromValue to its wrapper value, etc. Object value = null; if (fromValue != null) value = fromValue.getValue(); if (toType.isPrimitive()) { // Trying to cast null to primitive type? if (fromType == null) if (checkOnly) return Types.INVALID_CAST; else throw Types.castError("primitive type:" + toType, "Null value", operation); // fall through } else { // Trying to cast primitive to an object type // Primitive.NULL can be cast to any object type if (fromType == null) return checkOnly ? Types.VALID_CAST : Primitive.NULL; if (checkOnly) return Types.INVALID_CAST; else throw Types.castError("object type:" + toType, "primitive value", operation); } // can only cast boolean to boolean if (fromType == Boolean.TYPE) { if (toType != Boolean.TYPE) if (checkOnly) return Types.INVALID_CAST; else throw Types.castError(toType, fromType, operation); return checkOnly ? Types.VALID_CAST : fromValue; } // Do numeric cast // Only allow legal Java assignment unless we're a CAST operation if (operation == Types.ASSIGNMENT && !Types.isJavaAssignable(toType, fromType)) { if (checkOnly) return Types.INVALID_CAST; else throw Types.castError(toType, fromType, operation); } return checkOnly ? Types.VALID_CAST : new Primitive(castWrapper(toType, value)); }