/** * Gets the ObjectLoader for the specified class. * * @param classtype the class * @return the ObjectLoader */ public static XML.ObjectLoader getLoader(Class classtype) { // look for registered loader first ObjectLoader loader = (ObjectLoader) loaders.get(classtype); // if no registered loader, look for static getLoader() method in class if (loader == null) { try { Method method = classtype.getMethod("getLoader", (Class[]) null); // $NON-NLS-1$ if (method != null && Modifier.isStatic(method.getModifiers())) { loader = (ObjectLoader) method.invoke(null, (Object[]) null); if (loader != null) { // register loader for future calls setLoader(classtype, loader); } } } catch (Exception ex) { /** empty block */ } } // if still no loader found, use the default loader if (loader == null) { if (defaultLoader == null) { defaultLoader = new XMLLoader(); } loader = defaultLoader; } return loader; }
static Method[] getOverridableMethods(Class c) { ArrayList<Method> list = new ArrayList<Method>(); HashSet<String> skip = new HashSet<String>(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } c = c.getSuperclass(); } return list.toArray(new Method[list.size()]); }
private static LinkedHashMap<String, Prop> createProps() { Field[] fs = Configuration.class.getDeclaredFields(); LinkedHashMap<String, Prop> res = new LinkedHashMap<String, Prop>(); for (Field f : fs) if (!Modifier.isStatic(f.getModifiers())) { Description annotation = f.getAnnotation(Description.class); if (annotation != null) { String name = f.getName().replace('_', '.'); res.put(name, new Prop(name, annotation.value(), f)); } } return res; }
static Method[] getOverridableMethods(Class c) { ArrayList list = new ArrayList(); while (c != null) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) continue; if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) list.add(methods[i]); } c = c.getSuperclass(); } return (Method[]) list.toArray(new Method[list.size()]); }
private MutableTreeNode populateAttributes(CavityDBObject obj) { DefaultMutableTreeNode tree = new DefaultMutableTreeNode("attrs"); Class cls = obj.getClass(); for (Field f : cls.getFields()) { int mod = f.getModifiers(); if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) { String fieldName = f.getName(); try { Object value = f.get(obj); tree.add( new DefaultMutableTreeNode(String.format("%s=%s", fieldName, String.valueOf(value)))); } catch (IllegalAccessException e) { // do nothing. } } } return tree; }
private static void appendOverridableMethods( Class<?> c, ArrayList<Method> list, HashSet<String> skip) { Method[] methods = c.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { String methodKey = methods[i].getName() + getMethodSignature(methods[i], methods[i].getParameterTypes()); if (skip.contains(methodKey)) continue; // skip this method int mods = methods[i].getModifiers(); if (Modifier.isStatic(mods)) continue; if (Modifier.isFinal(mods)) { // Make sure we don't add a final method to the list // of overridable methods. skip.add(methodKey); continue; } if (Modifier.isPublic(mods) || Modifier.isProtected(mods)) { list.add(methods[i]); skip.add(methodKey); } } }
/** Verify and invoke main if present in the specified class. */ public static void invokeApplicationMain(Class mainClass, String[] args) throws InvocationTargetException, IllegalAccessException, ClassNotFoundException { String err = localStrings.getLocalString("utility.no.main", "", new Object[] {mainClass}); // determine the main method using reflection // verify that it is public static void and takes // String[] as the only argument Method mainMethod = null; try { mainMethod = mainClass.getMethod("main", new Class[] {String[].class}); } catch (NoSuchMethodException msme) { _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility", msme); throw new ClassNotFoundException(err); } // check modifiers: public static int modifiers = mainMethod.getModifiers(); if (!Modifier.isPublic(modifiers) || !Modifier.isStatic(modifiers)) { err = localStrings.getLocalString( "utility.main.notpublicorstatic", "The main method is either not public or not static"); _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notpublicorstatic"); throw new ClassNotFoundException(err); } // check return type and exceptions if (!mainMethod.getReturnType().equals(Void.TYPE)) { err = localStrings.getLocalString( "utility.main.notvoid", "The main method's return type is not void "); _logger.log(Level.SEVERE, "enterprise_util.excep_in_utility_main.notvoid"); throw new ClassNotFoundException(err); } // build args to the main and call it Object params[] = new Object[1]; params[0] = args; mainMethod.invoke(null, params); }
public static String generateProxy(Class interfaceClass) throws Exception { StringBuilder b = new StringBuilder(); b.append("#include <jni.h>\n"); b.append("#ifdef _WIN32\n"); b.append("#define PROXY_EXPORT __declspec(dllexport)\n"); b.append("#else\n"); b.append("#define PROXY_EXPORT\n"); b.append("#endif\n"); b.append( "#define FIND_GLOBAL_CLASS(name) (*env)->NewGlobalRef(env, (*env)->FindClass(env, name))\n"); List<ProxiedMethod> methods = new ArrayList<ProxiedMethod>(); int iClassName = 0, iMethodName = 0; Map<Class, String> classVarNames = new HashMap<Class, String>(); for (Method m : interfaceClass.getDeclaredMethods()) { try { ProxiedMethod pm = getProxiedMethod(m); String classVarName = classVarNames.get(pm.owner); if (classVarName == null) classVarNames.put(pm.owner, classVarName = "gClass" + (++iClassName)); pm.classVarName = classVarName; pm.methodVarName = "gMethod" + (++iMethodName); methods.add(pm); } catch (Throwable th) { // th.printStackTrace(); } } b.append("jboolean inited = JNI_FALSE;\n"); String instanceVarName = "gProxiedInstance"; b.append("JNIEnv* env = NULL;\n"); b.append("JavaVM* jvm = NULL;\n"); b.append("jobject ").append(instanceVarName).append(" = NULL;\n"); for (String n : classVarNames.values()) b.append("jclass ").append(n).append(" = NULL;\n"); for (ProxiedMethod pm : methods) b.append("jmethodID ").append(pm.methodVarName).append(" = NULL;\n"); String jniInit = "jni_init"; b.append("void ").append(jniInit).append("(JNIEnv* env) {\n"); b.append("\tif (inited) return; else inited = JNI_TRUE;\n"); for (Map.Entry<Class, String> e : classVarNames.entrySet()) { String n = e.getValue(); Class c = e.getKey(); b.append("\t") .append(n) .append(" = ") .append("FIND_GLOBAL_CLASS(\"") .append(name(c)) .append("\");\n"); } for (ProxiedMethod pm : methods) { int mods = pm.method.getModifiers(); b.append("\t") .append(pm.methodVarName) .append(" = ") .append("(*env)->") .append(Modifier.isStatic(mods) ? "GetStaticMethodID" : "GetMethodID") .append("(env, ") .append(pm.classVarName) .append(", \"") .append(pm.name) .append("\", \"") .append(pm.jni_signature) .append("\");\n"); } b.append("}\n"); for (ProxiedMethod pm : methods) { b.append("PROXY_EXPORT ").append(pm.c_signature).append(" {\n"); int mods = pm.method.getModifiers(); b.append("\t").append(jniInit).append("();\n"); b.append("\t"); if (pm.method.getReturnType() != null && !pm.method.getReturnType().equals(void.class)) b.append("return "); StringBuilder r = new StringBuilder(); boolean stat = Modifier.isStatic(mods); r.append("(*env)->") .append("Call" + (stat ? "Static" : "") + pm.retCapitalized + "Method") .append("(env, "); if (stat) r.append(pm.classVarName); else r.append(instanceVarName); for (String argValue : pm.argValues) { r.append(", \n\t\t"); r.append(argValue); } // TODO... r.append("\n\t)"); b.append(c_signature(pm.method.getReturnType(), r.toString())[2]); b.append(";\n"); b.append("}\n"); } return b.toString(); }
@Override public boolean apply(Field f) { int modifiers = f.getModifiers(); return !Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers); }
/** * {@inheritDoc} * * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, * java.lang.Object[]) */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (MBeanServerConnection.class != method.getDeclaringClass()) { return method.invoke(Modifier.isStatic(method.getModifiers()) ? null : this, args); } if (channel.getPipeline().get(getClass().getSimpleName()) == null) { throw new IOException("This MBeanServerConnection has been closed", new Throwable()); } // SimpleLogger.debug("MBeanServerConnection [", method.getName(), "] Payload Size [", // sargs.length+6+4, "]"); final int reqId = requestId.incrementAndGet(); if ("addNotificationListener".equals(method.getName()) && !method.getParameterTypes()[1].equals(ObjectName.class)) { NotificationListener listener = (NotificationListener) args[1]; args[1] = reqId; addRegisteredListener(reqId, listener); } else if ("removeNotificationListener".equals(method.getName()) && !method.getParameterTypes()[1].equals(ObjectName.class)) { removeRegisteredListener((NotificationListener) args[1]); args = new Object[0]; } byte[] sargs = getOutput(args); ChannelBuffer cb = ChannelBuffers.directBuffer(1 + domainInfoData.length + 4 + 1 + 4 + sargs.length); cb.writeByte(OpCode.JMX_REQUEST.op()); // 1 cb.writeBytes(domainInfoData); // domain data cb.writeInt(reqId); // 4 cb.writeByte(methodToKey.get(method)); // 1 cb.writeInt(sargs.length); // 4 cb.writeBytes(sargs); // sargs.length if (listener == null) { synchTimeoutMap.addListener( new TimeoutListener<Integer, CountDownLatch>() { @Override public void onTimeout(Integer key, CountDownLatch value) { if (reqId == key) { synchTimeoutMap.remove(key); synchTimeoutMap.removeListener(this); onSynchronousResponse( reqId, new IOException( "Operation timed out after [" + timeout + "] ms.", new Throwable())); } } }); } else { asynchTimeoutMap.put(reqId, listener, timeout); asynchTimeoutMap.addListener( new TimeoutListener<Integer, AsynchJMXResponseListener>() { @Override public void onTimeout(Integer key, AsynchJMXResponseListener value) { if (reqId == key) { asynchTimeoutMap.remove(key); listener.onTimeout(reqId, timeout); asynchTimeoutMap.removeListener(this); } } }); } channel .write(cb, remoteAddress) .addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { SimpleLogger.debug("Sent JMX Request to [", remoteAddress, "]"); } else { SimpleLogger.error( "Failed to send JMX Request to [", remoteAddress, "]", future.getCause()); } } }); if (listener == null) { waitForSynchronousResponse(reqId, timeout); Object result = synchResultMap.get(reqId); if (result != null && result instanceof Throwable) { throw (Throwable) result; } return result; } return null; }
public static byte[] createAdapterCode( ObjToIntMap functionNames, String adapterName, Class<?> superClass, Class<?>[] interfaces, String scriptClassName) { ClassFileWriter cfw = new ClassFileWriter(adapterName, superClass.getName(), "<adapter>"); cfw.addField( "factory", "Laurora/javascript/ContextFactory;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField( "delegee", "Laurora/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField( "self", "Laurora/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); int interfacesCount = interfaces == null ? 0 : interfaces.length; for (int i = 0; i < interfacesCount; i++) { if (interfaces[i] != null) cfw.addInterface(interfaces[i].getName()); } String superName = superClass.getName().replace('.', '/'); Constructor<?>[] ctors = superClass.getConstructors(); for (Constructor<?> ctor : ctors) { generateCtor(cfw, adapterName, superName, ctor); } generateSerialCtor(cfw, adapterName, superName); if (scriptClassName != null) { generateEmptyCtor(cfw, adapterName, superName, scriptClassName); } ObjToIntMap generatedOverrides = new ObjToIntMap(); ObjToIntMap generatedMethods = new ObjToIntMap(); // generate methods to satisfy all specified interfaces. for (int i = 0; i < interfacesCount; i++) { Method[] methods = interfaces[i].getMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) { continue; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); if (!functionNames.has(methodName)) { try { superClass.getMethod(methodName, argTypes); // The class we're extending implements this method and // the JavaScript object doesn't have an override. See // bug 61226. continue; } catch (NoSuchMethodException e) { // Not implemented by superclass; fall through } } // make sure to generate only one instance of a particular // method/signature. String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (!generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); } } } // Now, go through the superclass's methods, checking for abstract // methods or additional methods to override. // generate any additional overrides that the object might contain. Method[] methods = getOverridableMethods(superClass); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); // if a method is marked abstract, must implement it or the // resulting class won't be instantiable. otherwise, if the object // has a property of the same name, then an override is intended. boolean isAbstractMethod = Modifier.isAbstract(mods); String methodName = method.getName(); if (isAbstractMethod || functionNames.has(methodName)) { // make sure to generate only one instance of a particular // method/signature. Class<?>[] argTypes = method.getParameterTypes(); String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (!generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); // if a method was overridden, generate a "super$method" // which lets the delegate call the superclass' version. if (!isAbstractMethod) { generateSuper( cfw, adapterName, superName, methodName, methodSignature, argTypes, method.getReturnType()); } } } } // Generate Java methods for remaining properties that are not // overrides. ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames); for (iter.start(); !iter.done(); iter.next()) { String functionName = (String) iter.getKey(); if (generatedMethods.has(functionName)) continue; int length = iter.getValue(); Class<?>[] parms = new Class[length]; for (int k = 0; k < length; k++) parms[k] = ScriptRuntime.ObjectClass; generateMethod(cfw, adapterName, functionName, parms, ScriptRuntime.ObjectClass, false); } return cfw.toByteArray(); }
public TypeUniverse() { Providers providers = Graal.getRequiredCapability(RuntimeProvider.class).getHostBackend().getProviders(); metaAccess = providers.getMetaAccess(); constantReflection = providers.getConstantReflection(); snippetReflection = Graal.getRequiredCapability(SnippetReflectionProvider.class); Unsafe theUnsafe = null; try { theUnsafe = Unsafe.getUnsafe(); } catch (Exception e) { try { Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeField.setAccessible(true); theUnsafe = (Unsafe) theUnsafeField.get(null); } catch (Exception e1) { throw (InternalError) new InternalError("unable to initialize unsafe").initCause(e1); } } unsafe = theUnsafe; Class<?>[] initialClasses = { void.class, boolean.class, byte.class, short.class, char.class, int.class, float.class, long.class, double.class, Object.class, Class.class, ClassLoader.class, String.class, Serializable.class, Cloneable.class, Test.class, TestMetaAccessProvider.class, List.class, Collection.class, Map.class, Queue.class, HashMap.class, LinkedHashMap.class, IdentityHashMap.class, AbstractCollection.class, AbstractList.class, ArrayList.class }; for (Class<?> c : initialClasses) { addClass(c); } for (Field f : Constant.class.getDeclaredFields()) { int mods = f.getModifiers(); if (f.getType() == Constant.class && Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) { try { Constant c = (Constant) f.get(null); if (c != null) { constants.add(c); } } catch (Exception e) { } } } for (Class<?> c : classes) { if (c != void.class && !c.isArray()) { constants.add(snippetReflection.forObject(Array.newInstance(c, 42))); } } constants.add(snippetReflection.forObject(new ArrayList<>())); constants.add(snippetReflection.forObject(new IdentityHashMap<>())); constants.add(snippetReflection.forObject(new LinkedHashMap<>())); constants.add(snippetReflection.forObject(new TreeMap<>())); constants.add(snippetReflection.forObject(new ArrayDeque<>())); constants.add(snippetReflection.forObject(new LinkedList<>())); constants.add(snippetReflection.forObject("a string")); constants.add(snippetReflection.forObject(42)); constants.add(snippetReflection.forObject(String.class)); constants.add(snippetReflection.forObject(String[].class)); }