List of usage examples for org.objectweb.asm Type getInternalName
public static String getInternalName(final Class<?> clazz)
From source file:blue.lapis.pore.event.PoreListenerGenerator.java
License:Open Source License
private static byte[] generate(String name, Class<?> pore, Class<?> sponge, EventPriority priority, Order order) {/*from w ww . j av a2s .c om*/ name = name.replace('.', '/'); String poreName = Type.getInternalName(pore); String spongeSignature = "(L" + Type.getInternalName(sponge) + ";)V"; ClassWriter cw = new ClassWriter(0); MethodVisitor mv; AnnotationVisitor av; cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, name, null, "java/lang/Object", null); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "on" + sponge.getSimpleName(), spongeSignature, null, null); { av = mv.visitAnnotation(ANNOTATION_DESCRIPTOR, true); av.visitEnum("order", ORDER_DESCRIPTOR, order.name()); av.visitEnd(); } mv.visitCode(); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESTATIC, EVENT_WRAPPER_CLASS, "get", GET_CACHE, false); mv.visitTypeInsn(CHECKCAST, poreName); mv.visitVarInsn(ASTORE, 2); mv.visitVarInsn(ALOAD, 2); Label l0 = new Label(); mv.visitJumpInsn(IFNONNULL, l0); mv.visitVarInsn(ALOAD, 1); mv.visitTypeInsn(NEW, poreName); mv.visitInsn(DUP); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKESPECIAL, poreName, "<init>", spongeSignature, false); mv.visitInsn(DUP); mv.visitVarInsn(ASTORE, 2); mv.visitMethodInsn(INVOKESTATIC, EVENT_WRAPPER_CLASS, "set", SET_CACHE, false); mv.visitLabel(l0); mv.visitFrame(F_APPEND, 1, new Object[] { poreName }, 0, null); mv.visitVarInsn(ALOAD, 2); mv.visitFieldInsn(GETSTATIC, PRIORITY_CLASS, priority.name(), PRIORITY_DESCRIPTOR); mv.visitMethodInsn(INVOKESTATIC, EVENT_WRAPPER_CLASS, "call", CALL_EVENT, false); mv.visitInsn(RETURN); mv.visitMaxs(4, 3); mv.visitEnd(); } cw.visitEnd(); return cw.toByteArray(); }
From source file:bluejelly.runtime.ModuleLoader.java
License:BSD License
/** * Generate a {@link Caf} subclass for the given method information. * //from w ww .j a va2s . c o m * @param module module declaring the method to process * @param ci code info for the method to process * * @return * a {@link Caf} subclass whose <code>fastEnter</code> will call * module.ci.getMethod() with an {@link ExecutionContext} as argument. */ @SuppressWarnings("unchecked") private Class<Caf> generateCaf(Module module, CodeInfo ci) { String nodeName = this.genNodeName(ci); String cafName = Type.getInternalName(Caf.class); String moduleName = Type.getInternalName(module.getClass()); String methodName = ci.getMethod().getName(); ClassWriter cw = new ClassWriter(0); cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL, nodeName, null, cafName, null); { String consDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(Module.class), Type.getType(String.class) }); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", consDesc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ALOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitMethodInsn(INVOKESPECIAL, cafName, "<init>", consDesc); mv.visitInsn(RETURN); mv.visitMaxs(3, 3); mv.visitEnd(); } this.generateFastEnter(cw, cafName, moduleName, methodName); cw.visitEnd(); byte[] b = cw.toByteArray(); Class<?> clazz = this.loader.defineClass(nodeName, b); return (Class<Caf>) clazz; }
From source file:bluejelly.runtime.ModuleLoader.java
License:BSD License
/** * Generate a {@link Code} subclass for the given method information. * // w w w .ja v a 2s. c o m * @param module module declaring the method to process * @param ci code info for the method to process * * @return * a {@link Code} subclass whose <code>fastEnter</code> will call * module.ci.getMethod() with an {@link ExecutionContext} as argument. */ @SuppressWarnings("unchecked") private Class<Code> generateCode(Module module, CodeInfo ci) { String nodeName = this.genNodeName(ci); String codeName = Type.getInternalName(Code.class); String moduleName = Type.getInternalName(module.getClass()); String methodName = ci.getMethod().getName(); ClassWriter cw = new ClassWriter(0); cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL, nodeName, null, codeName, null); { String consDesc = Type.getMethodDescriptor(Type.VOID_TYPE, new Type[] { Type.getType(int.class), Type.getType(Module.class), Type.getType(String.class) }); MethodVisitor mv = cw.visitMethod(ACC_PUBLIC, "<init>", consDesc, null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitVarInsn(ILOAD, 1); mv.visitVarInsn(ALOAD, 2); mv.visitVarInsn(ALOAD, 3); mv.visitMethodInsn(INVOKESPECIAL, codeName, "<init>", consDesc); mv.visitInsn(RETURN); mv.visitMaxs(4, 4); mv.visitEnd(); } this.generateFastEnter(cw, codeName, moduleName, methodName); cw.visitEnd(); byte[] b = cw.toByteArray(); Class<?> clazz = this.loader.defineClass(nodeName, b); return (Class<Code>) clazz; }
From source file:blusunrize.immersiveengineering.common.util.compat.jei.arcfurnace.ArcFurnaceRecipeWrapper.java
private static Class<? extends ArcFurnaceRecipeWrapper> createSubWrapper(String subtype) throws Exception { String entitySuperClassName = Type.getInternalName(ArcFurnaceRecipeWrapper.class); String entityProxySubClassName = ArcFurnaceRecipeWrapper.class.getSimpleName().concat(subtype); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, entityProxySubClassName, null, entitySuperClassName, null); cw.visitSource(entityProxySubClassName.concat(".java"), null); //create constructor String methodDescriptor = "(L" + Type.getInternalName(ArcFurnaceRecipe.class) + ";)V"; MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", methodDescriptor, null, null); mv.visitCode();/*from w w w .j a v a2s.com*/ mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitVarInsn(Opcodes.ALOAD, 1); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, entitySuperClassName, "<init>", methodDescriptor, false); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(0, 0); mv.visitEnd(); cw.visitEnd(); return (Class<? extends ArcFurnaceRecipeWrapper>) new ProxyClassLoader( Thread.currentThread().getContextClassLoader(), cw.toByteArray()) .loadClass(entityProxySubClassName.replaceAll("/", ".")); }
From source file:cn.annoreg.asm.DelegateGenerator.java
License:Open Source License
public static MethodVisitor generateStaticMethod(ClassVisitor parentClass, MethodVisitor parent, String className, String methodName, String desc, final Side side) { //This method is a little bit complicated. //We need to generate a delegate class implementing NetworkCallDelegate and a redirect //the code that originally generated here in parent, into the delegate class, //by returning a MethodVisitor under the ClassVisitor of the delegate class. //Besides, we should generate a call to NetworkCallManager into parent. //Above is the original method. Now it has a little bit change. To allow private call in //here, we need to generate the delegate method in this class instead of in a delegate class. //We make the delegate method public so that the delegate class can call it. //delegateName is a string used by both sides to identify a network-call delegate. final String delegateName = className + ":" + methodName + ":" + desc; final Type[] args = Type.getArgumentTypes(desc); final Type ret = Type.getReturnType(desc); //Check types for (Type t : args) { //TODO support these types if (!t.getDescriptor().startsWith("L") && !t.getDescriptor().startsWith("[")) { throw new RuntimeException("Unsupported argument type in network call. in method " + methodName + ", " + t.getDescriptor()); }/*from www. j a v a 2s .c om*/ } if (!ret.equals(Type.VOID_TYPE)) { throw new RuntimeException( "Unsupported return value type in network call. " + "Only void is supported."); } //Generate call to NetworkCallManager in parent. parent.visitCode(); //First parameter parent.visitLdcInsn(delegateName); //Second parameter: object array pushIntegerConst(parent, args.length); //array size parent.visitTypeInsn(Opcodes.ANEWARRAY, Type.getInternalName(Object.class)); for (int i = 0; i < args.length; ++i) { parent.visitInsn(Opcodes.DUP); pushIntegerConst(parent, i); parent.visitVarInsn(Opcodes.ALOAD, i); parent.visitInsn(Opcodes.AASTORE); } //Call cn.annoreg.mc.network.NetworkCallManager.onNetworkCall parent.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(NetworkCallManager.class), "onNetworkCall", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(String.class), Type.getType(Object[].class))); parent.visitInsn(Opcodes.RETURN); parent.visitMaxs(5, args.length); parent.visitEnd(); //Create delegate object. final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); final String delegateId = Integer.toString(delegateNextID++); final Type delegateClassType = Type.getType("cn/annoreg/asm/NetworkCallDelegate_" + delegateId); cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, delegateClassType.getInternalName(), null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(NetworkCallDelegate.class) }); //package cn.annoreg.asm; //class NetworkCallDelegate_? implements NetworkCallDelegate { { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } //public NetworkCallDelegate_?() {} final String delegateFunctionName = methodName + "_delegate_" + delegateId; { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object[].class)), null, null); mv.visitCode(); for (int i = 0; i < args.length; ++i) { mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this pushIntegerConst(mv, i); mv.visitInsn(Opcodes.AALOAD); mv.visitTypeInsn(Opcodes.CHECKCAST, args[i].getInternalName()); } mv.visitMethodInsn(Opcodes.INVOKESTATIC, //delegateClassType.getInternalName(), //changed to original class className.replace('.', '/'), delegateFunctionName, desc); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(args.length + 2, 2); mv.visitEnd(); } //@Override public void invoke(Object[] args) { // xxxx.xxxx_delegated_xxx((Type0) args[0], (Type1) args[1], ...); //} //The returned MethodVisitor will visit the original version of the method, //including its annotation, where we can get StorageOptions. return new MethodVisitor(Opcodes.ASM4, parentClass.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, delegateFunctionName, desc, null, null)) { //Remember storage options for each argument StorageOption.Option[] options = new StorageOption.Option[args.length]; int targetIndex = -1; StorageOption.Target.RangeOption range = StorageOption.Target.RangeOption.SINGLE; double sendRange = -1; { for (int i = 0; i < options.length; ++i) { options[i] = StorageOption.Option.NULL; //set default value } } @Override public AnnotationVisitor visitParameterAnnotation(final int parameter, String desc, boolean visible) { Type type = Type.getType(desc); if (type.equals(Type.getType(StorageOption.Data.class))) { options[parameter] = StorageOption.Option.DATA; } else if (type.equals(Type.getType(StorageOption.Instance.class))) { //INSTANCE as defualt options[parameter] = StorageOption.Option.INSTANCE; //Change to NULLABLE_INSTANCE if nullable set to true return new AnnotationVisitor(this.api, super.visitParameterAnnotation(parameter, desc, visible)) { @Override public void visit(String name, Object value) { if (name.equals("nullable")) { if ((Boolean) value == true) { options[parameter] = StorageOption.Option.NULLABLE_INSTANCE; } } super.visit(name, value); } }; } else if (type.equals(Type.getType(StorageOption.Update.class))) { options[parameter] = StorageOption.Option.UPDATE; } else if (type.equals(Type.getType(StorageOption.Null.class))) { options[parameter] = StorageOption.Option.NULL; } else if (type.equals(Type.getType(StorageOption.Target.class))) { if (!args[parameter].equals(Type.getType(EntityPlayer.class))) { throw new RuntimeException("Target annotation can only be used on EntityPlayer."); } if (targetIndex != -1) { throw new RuntimeException("You can not specify multiple targets."); } options[parameter] = StorageOption.Option.INSTANCE; targetIndex = parameter; return new AnnotationVisitor(this.api, super.visitParameterAnnotation(parameter, desc, visible)) { @Override public void visitEnum(String name, String desc, String value) { super.visitEnum(name, desc, value); range = StorageOption.Target.RangeOption.valueOf(value); } }; } else if (type.equals(Type.getType(StorageOption.RangedTarget.class))) { if (targetIndex != -1) { throw new RuntimeException("You can not specify multiple targets."); } range = null; targetIndex = parameter; return new AnnotationVisitor(this.api, super.visitParameterAnnotation(parameter, desc, visible)) { @Override public void visit(String name, Object value) { super.visit(name, value); sendRange = (double) value; } }; } return super.visitParameterAnnotation(parameter, desc, visible); } @Override public void visitEnd() { super.visitEnd(); //This is the last method in the delegate class. //Finish the class and do the registration. cw.visitEnd(); try { Class<?> clazz = classLoader.defineClass(delegateClassType.getClassName(), cw.toByteArray()); NetworkCallDelegate delegateObj = (NetworkCallDelegate) clazz.newInstance(); if (side == Side.CLIENT) { NetworkCallManager.registerClientDelegateClass(delegateName, delegateObj, options, targetIndex, range, sendRange); } else { NetworkCallManager.registerServerDelegateClass(delegateName, delegateObj, options); } } catch (Throwable e) { throw new RuntimeException("Can not create delegate for network call.", e); } } }; //public static void delegated(Type0 arg0, Type1, arg1, ...) { // //Code generated by caller. //} //} }
From source file:cn.annoreg.asm.DelegateGenerator.java
License:Open Source License
public static MethodVisitor generateNonStaticMethod(ClassVisitor parentClass, MethodVisitor parent, String className, String methodName, String desc, final Side side) { //convert desc to a non-static method form String nonstaticDesc;//ww w .j a v a 2 s .c o m { Type staticType = Type.getMethodType(desc); Type retType = staticType.getReturnType(); Type[] argsType = staticType.getArgumentTypes(); Type[] argsTypeWithThis = new Type[argsType.length + 1]; argsTypeWithThis[0] = Type.getType('L' + className.replace('.', '/') + ';'); System.arraycopy(argsType, 0, argsTypeWithThis, 1, argsType.length); nonstaticDesc = Type.getMethodDescriptor(retType, argsTypeWithThis); } //delegateName is a string used by both sides to identify a network-call delegate. final String delegateName = className + ":" + methodName + ":" + desc; final Type[] args = Type.getArgumentTypes(nonstaticDesc); final Type ret = Type.getReturnType(nonstaticDesc); //Check types for (Type t : args) { //TODO support these types if (!t.getDescriptor().startsWith("L") && !t.getDescriptor().startsWith("[")) { throw new RuntimeException("Unsupported argument type in network call. "); } } if (!ret.equals(Type.VOID_TYPE)) { throw new RuntimeException( "Unsupported return value type in network call. " + "Only void is supported."); } //Generate call to NetworkCallManager in parent. parent.visitCode(); //First parameter parent.visitLdcInsn(delegateName); //Second parameter: object array pushIntegerConst(parent, args.length); //this (0) has been included parent.visitTypeInsn(Opcodes.ANEWARRAY, "java/lang/Object"); for (int i = 0; i < args.length; ++i) { parent.visitInsn(Opcodes.DUP); pushIntegerConst(parent, i); parent.visitVarInsn(Opcodes.ALOAD, i); parent.visitInsn(Opcodes.AASTORE); } //Call cn.annoreg.mc.network.NetworkCallManager.onNetworkCall parent.visitMethodInsn(Opcodes.INVOKESTATIC, Type.getInternalName(NetworkCallManager.class), "onNetworkCall", "(Ljava/lang/String;[Ljava/lang/Object;)V"); parent.visitInsn(Opcodes.RETURN); parent.visitMaxs(5, args.length); parent.visitEnd(); //Create delegate object. final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); final String delegateId = Integer.toString(delegateNextID++); final Type delegateClassType = Type.getType("cn/annoreg/asm/NetworkCallDelegate_" + delegateId); cw.visit(Opcodes.V1_5, Opcodes.ACC_PUBLIC, delegateClassType.getInternalName(), null, Type.getInternalName(Object.class), new String[] { Type.getInternalName(NetworkCallDelegate.class) }); //package cn.annoreg.asm; //class NetworkCallDelegate_? implements NetworkCallDelegate { { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(Opcodes.ALOAD, 0); mv.visitMethodInsn(Opcodes.INVOKESPECIAL, Type.getInternalName(Object.class), "<init>", "()V"); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } //public NetworkCallDelegate_?() {} final String delegateMethodName = methodName + "_delegate_" + delegateId; { MethodVisitor mv = cw.visitMethod(Opcodes.ACC_PUBLIC, "invoke", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Object[].class)), null, null); mv.visitCode(); //check if this is null mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this pushIntegerConst(mv, 0); mv.visitInsn(Opcodes.AALOAD); Label lblEnd = new Label(); mv.visitJumpInsn(Opcodes.IFNULL, lblEnd); for (int i = 0; i < args.length; ++i) { mv.visitVarInsn(Opcodes.ALOAD, 1); //0 is this pushIntegerConst(mv, i); mv.visitInsn(Opcodes.AALOAD); mv.visitTypeInsn(Opcodes.CHECKCAST, args[i].getInternalName()); } mv.visitMethodInsn(Opcodes.INVOKESTATIC, //delegateClassType.getInternalName(), className.replace('.', '/'), delegateMethodName, nonstaticDesc); mv.visitLabel(lblEnd); mv.visitInsn(Opcodes.RETURN); mv.visitMaxs(args.length + 2, 2); mv.visitEnd(); } //@Override public void invoke(Object[] args) { // delegated((Type0) args[0], (Type1) args[1], ...); //} //The returned MethodVisitor will visit the original version of the method, //including its annotation, where we can get StorageOptions. return new MethodVisitor(Opcodes.ASM4, parentClass.visitMethod(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, delegateMethodName, nonstaticDesc, null, null)) { //Remember storage options for each argument StorageOption.Option[] options = new StorageOption.Option[args.length]; int targetIndex = -1; double sendRange = -1; StorageOption.Target.RangeOption range = StorageOption.Target.RangeOption.SINGLE; { for (int i = 0; i < options.length; ++i) { options[i] = StorageOption.Option.NULL; //set default value } options[0] = StorageOption.Option.INSTANCE; } @Override public AnnotationVisitor visitParameterAnnotation(int parameter_in_func, String desc, boolean visible) { final int parameter = parameter_in_func + 1; //skip this Type type = Type.getType(desc); if (type.equals(Type.getType(StorageOption.Data.class))) { options[parameter] = StorageOption.Option.DATA; } else if (type.equals(Type.getType(StorageOption.Instance.class))) { //INSTANCE as defualt options[parameter] = StorageOption.Option.INSTANCE; //Change to NULLABLE_INSTANCE if nullable set to true return new AnnotationVisitor(this.api, super.visitParameterAnnotation(parameter, desc, visible)) { @Override public void visit(String name, Object value) { if (name.equals("nullable")) { if ((Boolean) value == true) { options[parameter] = StorageOption.Option.NULLABLE_INSTANCE; } } super.visit(name, value); } }; } else if (type.equals(Type.getType(StorageOption.Update.class))) { options[parameter] = StorageOption.Option.UPDATE; } else if (type.equals(Type.getType(StorageOption.Null.class))) { options[parameter] = StorageOption.Option.NULL; } else if (type.equals(Type.getType(StorageOption.Target.class))) { if (!args[parameter].equals(Type.getType(EntityPlayer.class))) { throw new RuntimeException("Target annotation can only be used on EntityPlayer."); } if (targetIndex != -1) { throw new RuntimeException("You can not specify multiple targets."); } options[parameter] = StorageOption.Option.INSTANCE; targetIndex = parameter; return new AnnotationVisitor(this.api, super.visitParameterAnnotation(parameter, desc, visible)) { @Override public void visitEnum(String name, String desc, String value) { super.visitEnum(name, desc, value); range = StorageOption.Target.RangeOption.valueOf(value); } }; } else if (type.equals(Type.getType(StorageOption.RangedTarget.class))) { if (targetIndex != -1) { throw new RuntimeException("You can not specify multiple targets."); } targetIndex = parameter; range = null; return new AnnotationVisitor(this.api, super.visitParameterAnnotation(parameter, desc, visible)) { @Override public void visit(String name, Object value) { super.visit(name, value); sendRange = (double) value; } }; } return super.visitParameterAnnotation(parameter, desc, visible); } //TODO this option (from annotation) @Override public void visitEnd() { super.visitEnd(); //This is the last method in the delegate class. //Finish the class and do the registration. cw.visitEnd(); try { Class<?> clazz = classLoader.defineClass(delegateClassType.getClassName(), cw.toByteArray()); NetworkCallDelegate delegateObj = (NetworkCallDelegate) clazz.newInstance(); if (side == Side.CLIENT) { NetworkCallManager.registerClientDelegateClass(delegateName, delegateObj, options, targetIndex, range, sendRange); } else { NetworkCallManager.registerServerDelegateClass(delegateName, delegateObj, options); } } catch (Throwable e) { throw new RuntimeException("Can not create delegate for network call.", e); } } }; //public static void delegated(Type0 arg0, Type1, arg1, ...) { // //Code generated by caller. //} //} }
From source file:co.cask.cdap.data2.dataset2.DatasetClassRewriterTest.java
License:Apache License
private ClassDefinition rewrite(Class<? extends Dataset> dataset) throws Exception { DatasetClassRewriter rewriter = new DatasetClassRewriter(); URL url = dataset.getClassLoader().getResource(dataset.getName().replace('.', '/') + ".class"); Assert.assertNotNull(url);//from ww w .j a v a 2s . c o m try (InputStream is = url.openStream()) { return new ClassDefinition(rewriter.rewriteClass(dataset.getName(), is), Type.getInternalName(dataset)); } }
From source file:co.cask.cdap.internal.app.runtime.adapter.PluginTest.java
License:Apache License
private static File generateClass(Class<?> fromClass, final String className, File directory) throws IOException { // Generate a class dynamically using ASM from another class, but use a different class name, // so that it won't be in the test class path. try (InputStream byteCode = fromClass.getClassLoader() .getResourceAsStream(Type.getInternalName(fromClass) + ".class")) { ClassReader reader = new ClassReader(byteCode); ClassWriter writer = new ClassWriter(0); reader.accept(new ClassVisitor(Opcodes.ASM5, writer) { @Override// w ww .j a va 2s . c o m public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { super.visit(version, access, className.replace('.', '/'), signature, superName, interfaces); } }, 0); File target = new File(directory, className.replace('.', File.separatorChar) + ".class"); DirUtils.mkdirs(target.getParentFile()); Files.write(writer.toByteArray(), target); return target; } }
From source file:co.cask.cdap.internal.app.runtime.batch.distributed.ContainerLauncherGenerator.java
License:Apache License
/** * Generates a JAR file for launching MapReduce containers. The generated jar contains three classes inside * * <ul>/*from ww w.j a v a 2 s .c om*/ * <li>{@link org.apache.hadoop.mapreduce.v2.app.MRAppMaster}</li> * <li>{@link org.apache.hadoop.mapred.YarnChild YarnChild}</li> * <li>{@link MapReduceContainerLauncher}</li> * </ul> * * @see MapReduceContainerLauncher */ public static void generateLauncherJar(String launcherClassPath, String classLoaderName, OutputSupplier<? extends OutputStream> outputSupplier) throws IOException { try (JarOutputStream output = new JarOutputStream(outputSupplier.getOutput())) { generateLauncherClass(launcherClassPath, classLoaderName, "org.apache.hadoop.mapreduce.v2.app.MRAppMaster", output); generateLauncherClass(launcherClassPath, classLoaderName, "org.apache.hadoop.mapred.YarnChild", output); // Includes the launcher class in the JAR as well. No need to trace dependency as the launcher // class must be dependency free. String containerLauncherName = Type.getInternalName(MapReduceContainerLauncher.class) + ".class"; output.putNextEntry(new JarEntry(containerLauncherName)); URL launcherURL = ContainerLauncherGenerator.class.getClassLoader().getResource(containerLauncherName); // Can never be null Preconditions.checkState(launcherURL != null); Resources.copy(launcherURL, output); } }
From source file:co.cask.cdap.internal.app.runtime.batch.distributed.ContainerLauncherGenerator.java
License:Apache License
/** * Generates the bytecode for a main class and writes to the given {@link JarOutputStream}. * The generated class looks like this://from w w w .j a va 2 s . c om * * <pre>{@code * class className { * public static void main(String[] args) { * MapReduceContainerLauncher.launch(launcherClassPath, classLoaderName, className, args); * } * } * } * </pre> * * The {@code launcherClassPath}, {@code classLoaderName} and {@code className} are represented as * string literals in the generated class. */ private static void generateLauncherClass(String launcherClassPath, String classLoaderName, String className, JarOutputStream output) throws IOException { String internalName = className.replace('.', '/'); ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES); classWriter.visit(Opcodes.V1_7, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, internalName, null, Type.getInternalName(Object.class), null); Method constructor = Methods.getMethod(void.class, "<init>"); // Constructor // MRAppMaster() GeneratorAdapter mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC, constructor, null, null, classWriter); mg.loadThis(); mg.invokeConstructor(Type.getType(Object.class), constructor); mg.returnValue(); mg.endMethod(); // Main method. // public static void main(String[] args) { // MapReduceContainerLauncher.launch(launcherClassPath, classLoaderName, className, args); // } Method mainMethod = Methods.getMethod(void.class, "main", String[].class); mg = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, mainMethod, null, new Type[] { Type.getType(Exception.class) }, classWriter); mg.getStatic(Type.getType(System.class), "out", Type.getType(PrintStream.class)); mg.visitLdcInsn("Launch class " + className); mg.invokeVirtual(Type.getType(PrintStream.class), Methods.getMethod(void.class, "println", String.class)); // The Launcher classpath, classloader name and main classname are stored as string literal in the generated class mg.visitLdcInsn(launcherClassPath); mg.visitLdcInsn(classLoaderName); mg.visitLdcInsn(className); mg.loadArg(0); mg.invokeStatic(Type.getType(MapReduceContainerLauncher.class), Methods.getMethod(void.class, "launch", String.class, String.class, String.class, String[].class)); mg.returnValue(); mg.endMethod(); classWriter.visitEnd(); output.putNextEntry(new JarEntry(internalName + ".class")); output.write(classWriter.toByteArray()); }