List of usage examples for org.objectweb.asm ClassVisitor ClassVisitor
public ClassVisitor(final int api)
From source file:org.apache.commons.weaver.normalizer.Normalizer.java
License:Apache License
/** * Create the normalized version of a given class in the configured target package. The {@link Normalizer} will * gladly do so in a package from which the normalized class will not actually be able to reference any types upon * which it relies; in such a situation you must specify the target package as the package of the supertype. * @param key used to generate the normalized classname. * @param classWrapper//from w ww.jav a 2s . c om * @return the generated classname. * @throws IOException */ private String copy(final Pair<String, String> key, final ClassWrapper classWrapper) throws IOException { env.debug("Copying %s to %s", key, targetPackage); final MessageDigest md5; try { md5 = MessageDigest.getInstance("MD5"); } catch (final NoSuchAlgorithmException e) { throw new IllegalStateException(e); } md5.update(key.getLeft().getBytes(StandardCharsets.UTF_8)); md5.update(key.getRight().getBytes(StandardCharsets.UTF_8)); final long digest = Conversion.byteArrayToLong(md5.digest(), 0, 0L, 0, Long.SIZE / Byte.SIZE); final String result = MessageFormat.format("{0}/$normalized{1,number,0;_0}", targetPackage, digest); env.debug("Copying class %s to %s", classWrapper.wrapped.getName(), result); try (InputStream bytecode = env.getClassfile(classWrapper.wrapped).getInputStream()) { final ClassReader reader = new ClassReader(bytecode); final ClassVisitor writeClass = new WriteClass(); // we're doing most of this by hand; we only read the original class to hijack signature, ctor exceptions, // etc.: reader.accept(new ClassVisitor(ASM_VERSION) { Type supertype; @Override @SuppressWarnings("PMD.UseVarargs") //overridden method public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { supertype = Type.getObjectType(superName); writeClass.visit(version, Opcodes.ACC_PUBLIC, result, signature, superName, interfaces); visitAnnotation(Type.getType(Marker.class).getDescriptor(), false); } @Override @SuppressWarnings("PMD.UseVarargs") //overridden method public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { if (INIT.equals(name)) { final Method staticCtor = new Method(INIT, key.getRight()); final Type[] argumentTypes = staticCtor.getArgumentTypes(); final Type[] exceptionTypes = toObjectTypes(exceptions); { final GeneratorAdapter mgen = new GeneratorAdapter(Opcodes.ACC_PUBLIC, staticCtor, signature, exceptionTypes, writeClass); mgen.visitCode(); mgen.loadThis(); for (int i = 0; i < argumentTypes.length; i++) { mgen.loadArg(i); } mgen.invokeConstructor(supertype, staticCtor); mgen.returnValue(); mgen.endMethod(); } /* * now declare a dummy constructor that will match, and discard, * any originally inner-class bound constructor i.e. that set up a this$0 field. * By doing this we can avoid playing with the stack that originally * invoked such a constructor and simply rewrite the method */ { final Method instanceCtor = new Method(INIT, Type.VOID_TYPE, ArrayUtils.insert(0, argumentTypes, OBJECT_TYPE)); final GeneratorAdapter mgen = new GeneratorAdapter(Opcodes.ACC_PUBLIC, instanceCtor, signature, exceptionTypes, writeClass); mgen.visitCode(); mgen.loadThis(); for (int i = 0; i < argumentTypes.length; i++) { mgen.loadArg(i + 1); } mgen.invokeConstructor(supertype, staticCtor); mgen.returnValue(); mgen.endMethod(); } return null; } return null; } @Override public void visitEnd() { writeClass.visitEnd(); } }, 0); } return result; }
From source file:org.apache.commons.weaver.privilizer.PrivilizerCleaner.java
License:Apache License
@Override public boolean clean(final WeaveEnvironment environment, final Scanner scanner) { final Privilizer privilizer = new Privilizer(environment); final List<String> toDelete = new ArrayList<>(); final ScanRequest scanRequest = new ScanRequest().add(WeaveInterest.of(Privilized.class, ElementType.TYPE)); environment.debug("Cleaning classes privilized with policy other than %s", privilizer.policy); for (final WeavableClass<?> weavableClass : scanner.scan(scanRequest).getClasses().with(Privilized.class)) { final Policy privilizedPolicy = Policy.valueOf(weavableClass.getAnnotation(Privilized.class).value()); if (privilizedPolicy == privilizer.policy) { continue; }/*from ww w .ja v a 2 s .c o m*/ final String className = weavableClass.getTarget().getName(); environment.debug("Class %s privilized with %s; deleting.", className, privilizedPolicy); try (InputStream bytecode = privilizer.env.getClassfile(className).getInputStream()) { final ClassReader classReader = new ClassReader(bytecode); classReader.accept(new ClassVisitor(Privilizer.ASM_VERSION) { @Override @SuppressWarnings("PMD.UseVarargs") // overridden method public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { toDelete.add(name); } @Override public void visitInnerClass(final String name, final String outerName, final String innerName, final int access) { if (toDelete.contains(outerName)) { toDelete.add(name); } } }, ClassReader.SKIP_CODE + ClassReader.SKIP_DEBUG + ClassReader.SKIP_FRAMES); } catch (final Exception e) { throw new IllegalStateException(e); } } boolean result = false; for (final String className : toDelete) { final String resourcePath = toResourcePath(className); final boolean success = environment.deleteResource(resourcePath); environment.debug("Deletion of resource %s was %ssuccessful.", resourcePath, success ? "" : "un"); result |= success; } return result; }
From source file:org.apache.deltaspike.proxy.impl.AsmDeltaSpikeProxyClassGenerator.java
License:Apache License
private static byte[] generateProxyClassBytes(Class<?> targetClass, String proxyName, String superAccessorMethodSuffix, Class<?>[] additionalInterfaces, java.lang.reflect.Method[] delegateMethods, java.lang.reflect.Method[] interceptMethods) { Class<?> superClass = targetClass; String[] interfaces = new String[] {}; if (targetClass.isInterface()) { superClass = Object.class; interfaces = new String[] { Type.getInternalName(targetClass) }; }/*from w w w. j a v a 2 s.co m*/ // add DeltaSpikeProxy as interface interfaces = Arrays.copyOf(interfaces, interfaces.length + 1); interfaces[interfaces.length - 1] = Type.getInternalName(DeltaSpikeProxy.class); if (additionalInterfaces != null && additionalInterfaces.length > 0) { interfaces = Arrays.copyOf(interfaces, interfaces.length + additionalInterfaces.length); for (int i = 0; i < additionalInterfaces.length; i++) { interfaces[(interfaces.length - 1) + i] = Type.getInternalName(additionalInterfaces[i]); } } Type superType = Type.getType(superClass); Type proxyType = Type.getObjectType(proxyName); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, proxyType.getInternalName(), null, superType.getInternalName(), interfaces); defineDefaultConstructor(cw, proxyType, superType); defineDeltaSpikeProxyFields(cw); defineDeltaSpikeProxyMethods(cw, proxyType); if (delegateMethods != null) { for (java.lang.reflect.Method method : delegateMethods) { defineMethod(cw, method, proxyType); } } if (interceptMethods != null) { for (java.lang.reflect.Method method : interceptMethods) { defineSuperAccessorMethod(cw, method, superType, superAccessorMethodSuffix); defineMethod(cw, method, proxyType); } } // copy all annotations from the source class try { // ClassVisitor to intercept all annotation visits on the class ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new CopyAnnotationVisitorAdapter(super.visitAnnotation(desc, visible), cw.visitAnnotation(desc, visible)); } }; // visit class to proxy with our visitor to copy all annotations from the source class to our ClassWriter String sourceClassFilename = targetClass.getName().replace('.', '/') + ".class"; ClassReader cr = new ClassReader(targetClass.getClassLoader().getResourceAsStream(sourceClassFilename)); cr.accept(cv, 0); } catch (Exception e) { throw new RuntimeException(e); } return cw.toByteArray(); }
From source file:org.apache.deltaspike.proxy.impl.AsmProxyClassGenerator.java
License:Apache License
private static byte[] generateProxyClassBytes(Class<?> targetClass, String proxyName, String superAccessorMethodSuffix, Class<?>[] additionalInterfaces, java.lang.reflect.Method[] delegateMethods, java.lang.reflect.Method[] interceptMethods) { Class<?> superClass = targetClass; String[] interfaces = new String[] {}; if (targetClass.isInterface()) { superClass = Object.class; interfaces = new String[] { Type.getInternalName(targetClass) }; }/*w ww . jav a 2s .c o m*/ // add DeltaSpikeProxy as interface interfaces = Arrays.copyOf(interfaces, interfaces.length + 1); interfaces[interfaces.length - 1] = Type.getInternalName(DeltaSpikeProxy.class); if (additionalInterfaces != null && additionalInterfaces.length > 0) { interfaces = Arrays.copyOf(interfaces, interfaces.length + additionalInterfaces.length); for (int i = 0; i < additionalInterfaces.length; i++) { interfaces[(interfaces.length - 1) + i] = Type.getInternalName(additionalInterfaces[i]); } } Type superType = Type.getType(superClass); Type proxyType = Type.getObjectType(proxyName); Type delegateInvocationHandlerType = Type.getType(InvocationHandler.class); final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC + Opcodes.ACC_SUPER, proxyType.getInternalName(), null, superType.getInternalName(), interfaces); defineInvocationHandlerField(cw, delegateInvocationHandlerType); defineDefaultConstructor(cw, proxyType, superType); defineDelegateInvocationHandlerConstructor(cw, proxyType, superType, delegateInvocationHandlerType); defineDeltaSpikeProxyMethods(cw, proxyType, delegateInvocationHandlerType); if (delegateMethods != null) { for (java.lang.reflect.Method method : delegateMethods) { defineMethod(cw, method, DelegateManualInvocationHandler.class); } } if (interceptMethods != null) { for (java.lang.reflect.Method method : interceptMethods) { defineSuperAccessorMethod(cw, method, superType, superAccessorMethodSuffix); defineMethod(cw, method, InterceptManualInvocationHandler.class); } } // copy all annotations from the source class try { // ClassVisitor to intercept all annotation visits on the class ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return new CopyAnnotationVisitorAdapter(super.visitAnnotation(desc, visible), cw.visitAnnotation(desc, visible)); } }; // visit class to proxy with our visitor to copy all annotations from the source class to our ClassWriter String sourceClassFilename = targetClass.getName().replace('.', '/') + ".class"; ClassReader cr = new ClassReader(targetClass.getClassLoader().getResourceAsStream(sourceClassFilename)); cr.accept(cv, 0); } catch (Exception e) { throw new RuntimeException(e); } return cw.toByteArray(); }
From source file:org.apache.ignite.internal.processors.hadoop.GridHadoopClassLoader.java
License:Apache License
/** * @param clsName Class name.// www. ja v a 2s . co m * @return {@code true} If the class has external dependencies. */ boolean hasExternalDependencies(final String clsName, final Set<String> visited) { if (isHadoop(clsName)) // Hadoop must not be in classpath but Idea sucks, so filtering explicitly as external. return true; // Try to get from parent to check if the type accessible. InputStream in = loadClassBytes(getParent(), clsName); if (in == null) // The class is external itself, it must be loaded from this class loader. return true; if (!isIgfsOrGgHadoop(clsName)) // Other classes should not have external dependencies. return false; final ClassReader rdr; try { rdr = new ClassReader(in); } catch (IOException e) { throw new RuntimeException("Failed to read class: " + clsName, e); } visited.add(clsName); final AtomicBoolean hasDeps = new AtomicBoolean(); rdr.accept(new ClassVisitor(Opcodes.ASM4) { AnnotationVisitor av = new AnnotationVisitor(Opcodes.ASM4) { // TODO }; FieldVisitor fv = new FieldVisitor(Opcodes.ASM4) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean b) { onType(desc); return av; } }; MethodVisitor mv = new MethodVisitor(Opcodes.ASM4) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean b) { onType(desc); return av; } @Override public AnnotationVisitor visitParameterAnnotation(int i, String desc, boolean b) { onType(desc); return av; } @Override public AnnotationVisitor visitAnnotationDefault() { return av; } @Override public void visitFieldInsn(int i, String owner, String name, String desc) { onType(owner); onType(desc); } @Override public void visitFrame(int i, int i2, Object[] locTypes, int i3, Object[] stackTypes) { for (Object o : locTypes) { if (o instanceof String) onType((String) o); } for (Object o : stackTypes) { if (o instanceof String) onType((String) o); } } @Override public void visitLocalVariable(String name, String desc, String signature, Label lb, Label lb2, int i) { onType(desc); } @Override public void visitMethodInsn(int i, String owner, String name, String desc) { onType(owner); } @Override public void visitMultiANewArrayInsn(String desc, int dim) { onType(desc); } @Override public void visitTryCatchBlock(Label lb, Label lb2, Label lb3, String e) { onType(e); } }; void onClass(String depCls) { assert validateClassName(depCls) : depCls; if (depCls.startsWith("java.")) // Filter out platform classes. return; if (visited.contains(depCls)) return; Boolean res = cache.get(depCls); if (res == Boolean.TRUE || (res == null && hasExternalDependencies(depCls, visited))) hasDeps.set(true); } void onType(String type) { if (type == null) return; int off = 0; while (type.charAt(off) == '[') off++; // Handle arrays. if (off != 0) type = type.substring(off); if (type.length() == 1) return; // Get rid of primitives. if (type.charAt(type.length() - 1) == ';') { assert type.charAt(0) == 'L' : type; type = type.substring(1, type.length() - 1); } type = type.replace('/', '.'); onClass(type); } @Override public void visit(int i, int i2, String name, String signature, String superName, String[] ifaces) { onType(superName); if (ifaces != null) { for (String iface : ifaces) onType(iface); } } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { onType(desc); return av; } @Override public void visitInnerClass(String name, String outerName, String innerName, int i) { onType(name); } @Override public FieldVisitor visitField(int i, String name, String desc, String signature, Object val) { onType(desc); return fv; } @Override public MethodVisitor visitMethod(int i, String name, String desc, String signature, String[] exceptions) { if (exceptions != null) { for (String e : exceptions) onType(e); } return mv; } }, 0); if (hasDeps.get()) // We already know that we have dependencies, no need to check parent. return true; // Here we are known to not have any dependencies but possibly we have a parent which have them. int idx = clsName.lastIndexOf('$'); if (idx == -1) // No parent class. return false; String parentCls = clsName.substring(0, idx); if (visited.contains(parentCls)) return false; Boolean res = cache.get(parentCls); if (res == null) res = hasExternalDependencies(parentCls, visited); return res; }
From source file:org.apache.ignite.internal.processors.hadoop.HadoopClassLoader.java
License:Apache License
/** * @param clsName Class name./*w w w .j a v a 2 s. c o m*/ * @return {@code true} If the class has external dependencies. */ boolean hasExternalDependencies(final String clsName, final Set<String> visited) { if (isHadoop(clsName)) // Hadoop must not be in classpath but Idea sucks, so filtering explicitly as external. return true; // Try to get from parent to check if the type accessible. InputStream in = loadClassBytes(getParent(), clsName); if (in == null) // The class is external itself, it must be loaded from this class loader. return true; if (!isHadoopIgfs(clsName)) // Other classes should not have external dependencies. return false; final ClassReader rdr; try { rdr = new ClassReader(in); } catch (IOException e) { throw new RuntimeException("Failed to read class: " + clsName, e); } visited.add(clsName); final AtomicBoolean hasDeps = new AtomicBoolean(); rdr.accept(new ClassVisitor(Opcodes.ASM4) { AnnotationVisitor av = new AnnotationVisitor(Opcodes.ASM4) { // TODO }; FieldVisitor fv = new FieldVisitor(Opcodes.ASM4) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean b) { onType(desc); return av; } }; MethodVisitor mv = new MethodVisitor(Opcodes.ASM4) { @Override public AnnotationVisitor visitAnnotation(String desc, boolean b) { onType(desc); return av; } @Override public AnnotationVisitor visitParameterAnnotation(int i, String desc, boolean b) { onType(desc); return av; } @Override public AnnotationVisitor visitAnnotationDefault() { return av; } @Override public void visitFieldInsn(int i, String owner, String name, String desc) { onType(owner); onType(desc); } @Override public void visitFrame(int i, int i2, Object[] locTypes, int i3, Object[] stackTypes) { for (Object o : locTypes) { if (o instanceof String) onType((String) o); } for (Object o : stackTypes) { if (o instanceof String) onType((String) o); } } @Override public void visitLocalVariable(String name, String desc, String signature, Label lb, Label lb2, int i) { onType(desc); } @Override public void visitMethodInsn(int i, String owner, String name, String desc) { onType(owner); } @Override public void visitMultiANewArrayInsn(String desc, int dim) { onType(desc); } @Override public void visitTryCatchBlock(Label lb, Label lb2, Label lb3, String e) { onType(e); } }; void onClass(String depCls) { assert validateClassName(depCls) : depCls; if (depCls.startsWith("java.")) // Filter out platform classes. return; if (visited.contains(depCls)) return; Boolean res = cache.get(depCls); if (res == Boolean.TRUE || (res == null && hasExternalDependencies(depCls, visited))) hasDeps.set(true); } void onType(String type) { if (type == null) return; int off = 0; while (type.charAt(off) == '[') off++; // Handle arrays. if (off != 0) type = type.substring(off); if (type.length() == 1) return; // Get rid of primitives. if (type.charAt(type.length() - 1) == ';') { assert type.charAt(0) == 'L' : type; type = type.substring(1, type.length() - 1); } type = type.replace('/', '.'); onClass(type); } @Override public void visit(int i, int i2, String name, String signature, String superName, String[] ifaces) { onType(superName); if (ifaces != null) { for (String iface : ifaces) onType(iface); } } @Override public AnnotationVisitor visitAnnotation(String desc, boolean visible) { onType(desc); return av; } @Override public void visitInnerClass(String name, String outerName, String innerName, int i) { onType(name); } @Override public FieldVisitor visitField(int i, String name, String desc, String signature, Object val) { onType(desc); return fv; } @Override public MethodVisitor visitMethod(int i, String name, String desc, String signature, String[] exceptions) { if (exceptions != null) { for (String e : exceptions) onType(e); } return mv; } }, 0); if (hasDeps.get()) // We already know that we have dependencies, no need to check parent. return true; // Here we are known to not have any dependencies but possibly we have a parent which have them. int idx = clsName.lastIndexOf('$'); if (idx == -1) // No parent class. return false; String parentCls = clsName.substring(0, idx); if (visited.contains(parentCls)) return false; Boolean res = cache.get(parentCls); if (res == null) res = hasExternalDependencies(parentCls, visited); return res; }
From source file:org.apache.lucene.validation.ForbiddenApisCheckTask.java
License:Apache License
/** Parses a class given as Resource and checks for valid method invocations */ private int checkClass(final ClassReader reader) { final int[] violations = new int[1]; reader.accept(new ClassVisitor(Opcodes.ASM4) { final String className = Type.getObjectType(reader.getClassName()).getClassName(); String source = null;//from w w w .j av a 2 s .c om @Override public void visitSource(String source, String debug) { this.source = source; } @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return new MethodVisitor(Opcodes.ASM4) { private int lineNo = -1; private ClassSignatureLookup lookupRelatedClass(String internalName) { ClassSignatureLookup c = classesToCheck.get(internalName); if (c == null) try { c = getClassFromClassLoader(internalName); } catch (BuildException be) { // we ignore lookup errors and simply ignore this related class c = null; } return c; } private boolean checkClassUse(String owner) { final String printout = forbiddenClasses.get(owner); if (printout != null) { log("Forbidden class use: " + printout, Project.MSG_ERR); return true; } return false; } private boolean checkMethodAccess(String owner, Method method) { if (checkClassUse(owner)) { return true; } final String printout = forbiddenMethods.get(owner + '\000' + method); if (printout != null) { log("Forbidden method invocation: " + printout, Project.MSG_ERR); return true; } final ClassSignatureLookup c = lookupRelatedClass(owner); if (c != null && !c.methods.contains(method)) { final String superName = c.reader.getSuperName(); if (superName != null && checkMethodAccess(superName, method)) { return true; } final String[] interfaces = c.reader.getInterfaces(); if (interfaces != null) { for (String intf : interfaces) { if (intf != null && checkMethodAccess(intf, method)) { return true; } } } } return false; } private boolean checkFieldAccess(String owner, String field) { if (checkClassUse(owner)) { return true; } final String printout = forbiddenFields.get(owner + '\000' + field); if (printout != null) { log("Forbidden field access: " + printout, Project.MSG_ERR); return true; } final ClassSignatureLookup c = lookupRelatedClass(owner); if (c != null && !c.fields.contains(field)) { final String superName = c.reader.getSuperName(); if (superName != null && checkFieldAccess(superName, field)) { return true; } final String[] interfaces = c.reader.getInterfaces(); if (interfaces != null) { for (String intf : interfaces) { if (intf != null && checkFieldAccess(intf, field)) { return true; } } } } return false; } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc) { if (checkMethodAccess(owner, new Method(name, desc))) { violations[0]++; reportSourceAndLine(); } } @Override public void visitFieldInsn(int opcode, String owner, String name, String desc) { if (checkFieldAccess(owner, name)) { violations[0]++; reportSourceAndLine(); } } private void reportSourceAndLine() { final StringBuilder sb = new StringBuilder(" in ").append(className); if (source != null && lineNo >= 0) { new Formatter(sb, Locale.ROOT).format(" (%s:%d)", source, lineNo).flush(); } log(sb.toString(), Project.MSG_ERR); } @Override public void visitLineNumber(int lineNo, Label start) { this.lineNo = lineNo; } }; } }, ClassReader.SKIP_FRAMES); return violations[0]; }
From source file:org.apache.maven.plugin.surefire.booterclient.ModularClasspathForkConfiguration.java
License:Apache License
@Nonnull String toModuleName(@Nonnull File moduleDescriptor) throws IOException { if (!moduleDescriptor.isFile()) { throw new IOException("No such Jigsaw module-descriptor exists " + moduleDescriptor.getAbsolutePath()); }/*from www . j a v a 2 s . co m*/ final StringBuilder sb = new StringBuilder(); new ClassReader(new FileInputStream(moduleDescriptor)).accept(new ClassVisitor(ASM6) { @Override public ModuleVisitor visitModule(String name, int access, String version) { sb.setLength(0); sb.append(name); return super.visitModule(name, access, version); } }, 0); return sb.toString(); }
From source file:org.apache.maven.plugins.shade.DefaultShaderTest.java
License:Apache License
public void testShaderWithRelocatedClassname() throws Exception { DefaultShader s = newShader();/*ww w. j a va2s .c o m*/ Set<File> set = new LinkedHashSet<File>(); set.add(new File("src/test/jars/test-project-1.0-SNAPSHOT.jar")); set.add(new File("src/test/jars/plexus-utils-1.4.1.jar")); List<Relocator> relocators = new ArrayList<Relocator>(); relocators.add( new SimpleRelocator("org/codehaus/plexus/util/", "_plexus/util/__", null, Arrays.<String>asList())); List<ResourceTransformer> resourceTransformers = new ArrayList<ResourceTransformer>(); resourceTransformers.add(new ComponentsXmlResourceTransformer()); List<Filter> filters = new ArrayList<Filter>(); File file = new File("target/foo-relocate-class.jar"); ShadeRequest shadeRequest = new ShadeRequest(); shadeRequest.setJars(set); shadeRequest.setUberJar(file); shadeRequest.setFilters(filters); shadeRequest.setRelocators(relocators); shadeRequest.setResourceTransformers(resourceTransformers); shadeRequest.setListShadedInJar(true); s.shade(shadeRequest); URLClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL() }); Class<?> c = cl.loadClass("_plexus.util.__StringUtils"); // first, ensure it works: Object o = c.newInstance(); assertEquals("", c.getMethod("clean", String.class).invoke(o, (String) null)); // now, check that its source file was rewritten: final String[] source = { null }; final ClassReader classReader = new ClassReader(cl.getResourceAsStream("_plexus/util/__StringUtils.class")); classReader.accept(new ClassVisitor(Opcodes.ASM4) { @Override public void visitSource(String arg0, String arg1) { super.visitSource(arg0, arg1); source[0] = arg0; } }, ClassReader.SKIP_CODE); assertEquals("__StringUtils.java", source[0]); testNumberOfShadedDeps(2, file); // Now we re-use the uber jar we just made so we can test nested shading // NOTE: there should be 4 list entrys 3 for the jar we just made // shaded stuff + it's name, and 1 for the new jar we are adding. set = new LinkedHashSet<File>(); set.add(new File("src/test/jars/test-artifact-1.0-SNAPSHOT.jar")); set.add(file); File newUber = new File("target/foo-relocate-class-nested.jar"); shadeRequest = new ShadeRequest(); shadeRequest.setJars(set); shadeRequest.setUberJar(newUber); shadeRequest.setFilters(filters); shadeRequest.setRelocators(relocators); shadeRequest.setResourceTransformers(resourceTransformers); shadeRequest.setListShadedInJar(true); s = newShader(); s.shade(shadeRequest); testNumberOfShadedDeps(4, newUber); // Now we test that we aren't doubling any entries, if we include the same jar twice it should // only be present in the list once set = new LinkedHashSet<File>(); set.add(newUber); newUber = new File("target/foo-relocate-class-nested-rep.jar"); shadeRequest = new ShadeRequest(); shadeRequest.setJars(set); shadeRequest.setUberJar(newUber); shadeRequest.setFilters(filters); shadeRequest.setRelocators(relocators); shadeRequest.setResourceTransformers(resourceTransformers); shadeRequest.setListShadedInJar(true); s = newShader(); s.shade(shadeRequest); // only an increase of one due to previous jar added testNumberOfShadedDeps(5, newUber); }
From source file:org.blockartistry.mod.DynSurround.world.WorldProviderWeatherHandle.java
License:MIT License
public WorldProviderWeatherHandle(final World world, final WorldProvider provider) { super(world, provider); if (provider.getClass() == WorldProviderSurface.class) return;/*from ww w. j av a2s . c om*/ ModLog.info("Processing inspection on world provider class %s for compat", provider.getClass().getName()); try { ModClassLoader modClassLoader = Loader.instance().getModClassLoader(); Field mainLoaderField = modClassLoader.getClass().getDeclaredField("mainClassLoader"); mainLoaderField.setAccessible(true); LaunchClassLoader classLoader = (LaunchClassLoader) mainLoaderField.get(modClassLoader); new ClassReader(classLoader.getClassBytes(provider.getClass().getName())) .accept(new ClassVisitor(Opcodes.ASM5) { @Override public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { if (name.equals("updateWeather")) { ModLog.info( "Visiting method %s with description %s named updateWeather() on WorldProvider", name, desc); patchWeather = false; return new MethodVisitor(Opcodes.ASM5) { boolean isTheMethod = true; @Override public void visitParameter(String name, int access) { this.isTheMethod = false; } @Override public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) { if (!this.isTheMethod) return; ModLog.info( "Visiting method call %s with description %s during inspection on WorldProvider#updateWeather(), for compat", name, desc); try { if (name.equals("updateWeatherBody") && desc.equals(Type.getMethodDescriptor( World.class.getMethod("updateWeatherBody")))) { patchWeather = true; ModLog.info( "Found World#updateWeatherBody() from WorldProvider#updateWeather()"); } else if (name.equals("updateWeather") && desc.equals(Type.getMethodDescriptor( WorldProvider.class.getMethod("updateWeather")))) { patchWeather = true; ModLog.info( "Found WorldProvider#updateWeather() from WorldProvider#updateWeather()"); } } catch (NoSuchMethodException exc) { Throwables.propagate(exc); } } }; } return null; } }, 0); } catch (IOException exc) { Throwables.propagate(exc); } catch (ReflectiveOperationException exc) { Throwables.propagate(exc); } }