Search in sources :

Example 21 with Method

use of org.glassfish.hk2.external.org.objectweb.asm.commons.Method in project Payara by payara.

the class ResourceUtil method getMethodMetaData.

/**
 * Constructs and returns the resource method meta-data. This method is
 * called to get meta-data in case of update method (POST).
 *
 * @param configBeanModel the config bean associated with the resource.
 * @return MethodMetaData the meta-data store for the resource method.
 */
public static MethodMetaData getMethodMetaData(ConfigModel configBeanModel) {
    MethodMetaData methodMetaData = new MethodMetaData();
    Class<? extends ConfigBeanProxy> configBeanProxy = null;
    try {
        configBeanProxy = (Class<? extends ConfigBeanProxy>) configBeanModel.classLoaderHolder.loadClass(configBeanModel.targetTypeName);
        Set<String> attributeNames = configBeanModel.getAttributeNames();
        for (String attributeName : attributeNames) {
            String methodName = getAttributeMethodName(attributeName);
            Method method = null;
            try {
                method = configBeanProxy.getMethod(methodName);
            } catch (NoSuchMethodException e) {
                // Method not found, so let's try a brute force method if the method
                // can't be found via the method above.  For example: for
                // Ssl.getSSLInactivityTimeout(), we calculate getSslInactivityTimeout,
                // which doesn't match due to case.
                String booleanMethodName = getAttributeBooleanMethodName(attributeName);
                for (Method m : configBeanProxy.getMethods()) {
                    if (m.getName().equalsIgnoreCase(methodName) || m.getName().equalsIgnoreCase(booleanMethodName)) {
                        method = m;
                    }
                }
            }
            Attribute attribute = method.getAnnotation(Attribute.class);
            if (attribute != null) {
                ParameterMetaData parameterMetaData = getParameterMetaData(attribute);
                if (method.getAnnotation(Deprecated.class) != null) {
                    parameterMetaData.putAttribute(Constants.DEPRECATED, "true");
                }
                // camelCase the attributeName before passing out
                attributeName = eleminateHypen(attributeName);
                methodMetaData.putParameterMetaData(attributeName, parameterMetaData);
            }
        }
    } catch (MultiException e) {
        e.printStackTrace();
    }
    return methodMetaData;
}
Also used : Attribute(org.jvnet.hk2.config.Attribute) MethodMetaData(org.glassfish.admin.rest.provider.MethodMetaData) Method(java.lang.reflect.Method) MultiException(org.glassfish.hk2.api.MultiException) ParameterMetaData(org.glassfish.admin.rest.provider.ParameterMetaData)

Example 22 with Method

use of org.glassfish.hk2.external.org.objectweb.asm.commons.Method in project Payara by payara.

the class BtraceClientGenerator method generateBtraceClientClassData.

public static byte[] generateBtraceClientClassData(int clientID, Collection<FlashlightProbe> probes) {
    // create a unique name.  It does not matter what the name is.
    String generatedClassName = "com/sun/btrace/flashlight/BTrace_Flashlight_" + clientID;
    // Start of writing a class using ASM, which will be our BTrace Client
    int cwFlags = ClassWriter.COMPUTE_FRAMES + ClassWriter.COMPUTE_MAXS;
    ClassWriter cw = new ClassWriter(cwFlags);
    // Define the access identifiers for the BTrace Client class
    int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL;
    cw.visit(Opcodes.V1_5, access, generatedClassName, null, "java/lang/Object", null);
    // Need a @OnMethod annotation, so prepare your Annotation Visitor for that
    cw.visitAnnotation("Lcom/sun/btrace/annotations/BTrace;", true);
    // Iterate through the probes, so you will create one method for each probe
    int methodCounter = 0;
    for (FlashlightProbe probe : probes) {
        // Preparing the class method header and params (type) for @OnMethod annotation
        StringBuilder typeDesc = new StringBuilder("void ");
        StringBuilder methodDesc = new StringBuilder("void __");
        methodDesc.append(probe.getProviderJavaMethodName()).append("__");
        methodDesc.append(clientID).append("_").append(methodCounter).append("_");
        methodDesc.append("(");
        typeDesc.append("(");
        String delim = "";
        String typeDelim = "";
        Class[] paramTypes = probe.getParamTypes();
        for (int index = 0; index < paramTypes.length; index++) {
            Class paramType = paramTypes[index];
            methodDesc.append(delim).append(paramType.getName());
            // Dont add the param type for type desc, if self is the first index
            if (!(probe.hasSelf() && (index == 0))) {
                typeDesc.append(typeDelim).append(paramType.getName());
                typeDelim = ",";
            }
            delim = ", ";
        }
        methodDesc.append(")");
        typeDesc.append(")");
        // Creating the class method
        Method m = Method.getMethod(methodDesc.toString());
        GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC + Opcodes.ACC_STATIC, m, null, null, cw);
        // Add the @Self annotation
        if (probe.hasSelf()) {
            String[] paramNames = probe.getProbeParamNames();
            for (int index = 0; index < paramNames.length; index++) {
                if (paramNames[index].equalsIgnoreCase(FlashlightProbe.SELF)) {
                    AnnotationVisitor paramVisitor = gen.visitParameterAnnotation(index, "Lcom/sun/btrace/annotations/Self;", true);
                    paramVisitor.visitEnd();
                }
            }
        }
        // Add the @OnMethod annotation to this method
        AnnotationVisitor av = gen.visitAnnotation("Lcom/sun/btrace/annotations/OnMethod;", true);
        av.visit("clazz", "" + probe.getProviderClazz().getName());
        av.visit("method", probe.getProviderJavaMethodName());
        av.visit("type", typeDesc.toString());
        av.visitEnd();
        // Add the body
        gen.push(probe.getId());
        gen.loadArgArray();
        gen.invokeStatic(Type.getType(ProbeRegistry.class), Method.getMethod("void invokeProbe(int, Object[])"));
        gen.returnValue();
        gen.endMethod();
        methodCounter++;
    }
    BtraceClientGenerator.generateConstructor(cw);
    cw.visitEnd();
    byte[] classData = cw.toByteArray();
    writeClass(classData, generatedClassName);
    return classData;
}
Also used : FlashlightProbe(org.glassfish.flashlight.provider.FlashlightProbe) ProbeRegistry(org.glassfish.flashlight.provider.ProbeRegistry) Method(org.glassfish.hk2.external.org.objectweb.asm.commons.Method) ClassWriter(org.glassfish.hk2.external.org.objectweb.asm.ClassWriter) AnnotationVisitor(org.glassfish.hk2.external.org.objectweb.asm.AnnotationVisitor) GeneratorAdapter(org.glassfish.hk2.external.org.objectweb.asm.commons.GeneratorAdapter)

Example 23 with Method

use of org.glassfish.hk2.external.org.objectweb.asm.commons.Method in project Payara by payara.

the class ProviderImplGenerator method generateClassData.

public byte[] generateClassData(FlashlightProbeProvider provider, Class providerClazz, String generatedClassName) {
    Type classType = Type.getType(providerClazz);
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("** classType: " + classType);
        logger.fine("** classDesc: " + Type.getDescriptor(providerClazz));
        logger.fine("Generating for: " + generatedClassName);
    }
    generatedClassName = generatedClassName.replace('.', '/');
    int cwFlags = ClassWriter.COMPUTE_FRAMES + ClassWriter.COMPUTE_MAXS;
    ClassWriter cw = new ClassWriter(cwFlags);
    int access = Opcodes.ACC_PUBLIC + Opcodes.ACC_FINAL;
    String[] interfaces = new String[] { providerClazz.getName().replace('.', '/') };
    cw.visit(Opcodes.V1_5, access, generatedClassName, null, "java/lang/Object", interfaces);
    for (FlashlightProbe probe : provider.getProbes()) {
        Type probeType = Type.getType(FlashlightProbe.class);
        int fieldAccess = Opcodes.ACC_PUBLIC;
        String fieldName = "_flashlight_" + probe.getProbeName();
        cw.visitField(fieldAccess, fieldName, probeType.getDescriptor(), null, null);
    }
    Type probeType = Type.getType(FlashlightProbe.class);
    for (FlashlightProbe probe : provider.getProbes()) {
        StringBuilder methodDesc = new StringBuilder();
        methodDesc.append("void ").append(probe.getProviderJavaMethodName());
        methodDesc.append("(");
        String delim = "";
        for (Class paramType : probe.getParamTypes()) {
            methodDesc.append(delim).append(paramType.getName());
            delim = ", ";
        }
        methodDesc.append(")");
        Method m = Method.getMethod(methodDesc.toString());
        GeneratorAdapter gen = new GeneratorAdapter(Opcodes.ACC_PUBLIC, m, null, null, cw);
        String fieldName = "_flashlight_" + probe.getProbeName();
        gen.loadThis();
        gen.visitFieldInsn(Opcodes.GETFIELD, generatedClassName, fieldName, probeType.getDescriptor());
        int index = gen.newLocal(probeType);
        gen.storeLocal(index);
        gen.loadLocal(index);
        gen.invokeVirtual(probeType, Method.getMethod("boolean isEnabled()"));
        gen.push(true);
        Label enabledLabel = new Label();
        Label notEnabledLabel = new Label();
        gen.ifCmp(Type.getType(boolean.class), GeneratorAdapter.EQ, enabledLabel);
        gen.goTo(notEnabledLabel);
        gen.visitLabel(enabledLabel);
        gen.loadLocal(index);
        gen.loadArgArray();
        gen.invokeVirtual(probeType, Method.getMethod("void fireProbe(Object[])"));
        gen.visitLabel(notEnabledLabel);
        gen.returnValue();
        gen.endMethod();
    }
    generateConstructor(cw, generatedClassName, provider);
    cw.visitEnd();
    byte[] classData = cw.toByteArray();
    int index = generatedClassName.lastIndexOf('.');
    String clsName = generatedClassName.substring(index + 1);
    if (Boolean.parseBoolean(System.getenv("AS_DEBUG"))) {
        if (logger.isLoggable(Level.FINE))
            logger.fine("Generated ClassDATA " + clsName);
        // the path is horribly long.  Let's just write t directly into the
        // lib dir.  It is not for loading as a class but just for us humans
        // to decompile to figure out what is going on.  No need to make it even harder!
        clsName = clsName.replace('.', '/');
        // just in case Windows?  unlikely...
        clsName = clsName.replace('\\', '/');
        index = clsName.lastIndexOf("/");
        if (index >= 0)
            clsName = clsName.substring(index + 1);
        FileOutputStream fos = null;
        try {
            String rootPath = System.getProperty(SystemPropertyConstants.INSTALL_ROOT_PROPERTY) + File.separator + "lib" + File.separator;
            String fileName = rootPath + clsName + ".class";
            if (logger.isLoggable(Level.FINE))
                logger.fine("ClassFile: " + fileName);
            File file = new File(fileName);
            if (FileUtils.mkdirsMaybe(file.getParentFile())) {
                fos = new FileOutputStream(file);
                fos.write(classData);
                fos.flush();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
            } catch (Exception e) {
            // nothing can be done...
            }
        }
    }
    return classData;
}
Also used : FlashlightProbe(org.glassfish.flashlight.provider.FlashlightProbe) Label(org.glassfish.hk2.external.org.objectweb.asm.Label) Method(org.glassfish.hk2.external.org.objectweb.asm.commons.Method) ClassWriter(org.glassfish.hk2.external.org.objectweb.asm.ClassWriter) PrivilegedActionException(java.security.PrivilegedActionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Type(org.glassfish.hk2.external.org.objectweb.asm.Type) FileOutputStream(java.io.FileOutputStream) GeneratorAdapter(org.glassfish.hk2.external.org.objectweb.asm.commons.GeneratorAdapter) File(java.io.File)

Example 24 with Method

use of org.glassfish.hk2.external.org.objectweb.asm.commons.Method in project Payara by payara.

the class InjectionManager method syncDoInject.

/**
 * Initializes the component by performing injection.
 *
 * @param component component instance to inject
 * @param onBehalfOf the inhabitant to do injection on behalf of
 * @param type component class
 * @param targets the injection resolvers to resolve all injection points
 * @throws ComponentException
 *      if injection failed for some reason.
 */
protected void syncDoInject(Object component, Class type, InjectionResolver... targets) {
    assert component != null;
    try {
        Class currentClass = type;
        while (currentClass != null && Object.class != currentClass) {
            // get the list of the instances variable
            for (Field field : currentClass.getDeclaredFields()) {
                Annotation nonOptionalAnnotation = null;
                boolean injected = false;
                for (InjectionResolver target : targets) {
                    Annotation inject = field.getAnnotation(target.type);
                    if (inject == null)
                        continue;
                    Type genericType = field.getGenericType();
                    Class fieldType = field.getType();
                    try {
                        Object value = target.getValue(component, field, genericType, fieldType);
                        if (value != null) {
                            AccessController.doPrivileged(new PrivilegedAction<Field>() {

                                @Override
                                public Field run() {
                                    field.setAccessible(true);
                                    return field;
                                }
                            });
                            field.set(component, value);
                            injected = true;
                            break;
                        } else {
                            if (!target.isOptional(field, inject)) {
                                nonOptionalAnnotation = inject;
                            }
                        }
                    } catch (MultiException e) {
                        error_injectionException(target, inject, field, e);
                    } catch (IllegalAccessException e) {
                        error_injectionException(target, inject, field, e);
                    } catch (RuntimeException e) {
                        error_injectionException(target, inject, field, e);
                    } catch (Exception ex) {
                        error_injectionException(target, inject, field, ex);
                    }
                }
                // exhausted all injection managers,
                if (!injected && nonOptionalAnnotation != null) {
                    throw new UnsatisfiedDependencyException(field, nonOptionalAnnotation);
                }
            }
            for (Method method : currentClass.getDeclaredMethods()) {
                for (InjectionResolver target : targets) {
                    Annotation inject = method.getAnnotation(target.type);
                    if (inject == null)
                        continue;
                    Method setter = target.getSetterMethod(method, inject);
                    if (setter.getReturnType() != void.class) {
                        if (Collection.class.isAssignableFrom(setter.getReturnType())) {
                            injectCollection(component, setter, target.getValue(component, method, null, setter.getReturnType()));
                            continue;
                        }
                        error_InjectMethodIsNotVoid(method);
                    }
                    Class<?>[] paramTypes = setter.getParameterTypes();
                    Type[] genericParamTypes = setter.getGenericParameterTypes();
                    if (allowInjection(method, paramTypes)) {
                        try {
                            if (1 == paramTypes.length) {
                                Object value = target.getValue(component, method, genericParamTypes[0], paramTypes[0]);
                                if (value != null) {
                                    AccessController.doPrivileged(new PrivilegedAction<Method>() {

                                        @Override
                                        public Method run() {
                                            setter.setAccessible(true);
                                            return setter;
                                        }
                                    });
                                    setter.invoke(component, value);
                                } else {
                                    if (!target.isOptional(method, inject)) {
                                        throw new UnsatisfiedDependencyException(method, inject);
                                    }
                                }
                            } else {
                                // multi params
                                AccessController.doPrivileged(new PrivilegedAction<Method>() {

                                    @Override
                                    public Method run() {
                                        setter.setAccessible(true);
                                        return setter;
                                    }
                                });
                                Type[] gparamType = setter.getGenericParameterTypes();
                                Object[] params = new Object[paramTypes.length];
                                for (int i = 0; i < paramTypes.length; i++) {
                                    Object value = target.getValue(component, method, gparamType[i], paramTypes[i]);
                                    if (value != null) {
                                        params[i] = value;
                                    } else {
                                        if (!target.isOptional(method, inject)) {
                                            throw new UnsatisfiedDependencyException(method, inject);
                                        }
                                    }
                                }
                                setter.invoke(component, params);
                            }
                        } catch (MultiException e) {
                            error_injectionException(target, inject, setter, e);
                        } catch (IllegalAccessException e) {
                            error_injectionException(target, inject, setter, e);
                        } catch (InvocationTargetException e) {
                            error_injectionException(target, inject, setter, e);
                        } catch (RuntimeException e) {
                            error_injectionException(target, inject, setter, e);
                        }
                    }
                }
            }
            currentClass = currentClass.getSuperclass();
        }
    } catch (final LinkageError e) {
        // reflection could trigger additional classloading and resolution, so it can cause linkage error.
        // report more information to assist diagnosis.
        // can't trust component.toString() as the object could be in an inconsistent state.
        final Class<?> cls = type;
        AccessController.doPrivileged(new PrivilegedAction<Object>() {

            @Override
            public Object run() {
                LinkageError x = new LinkageError("injection failed on " + cls + " from " + cls.getClassLoader());
                x.initCause(e);
                throw x;
            }
        });
    }
}
Also used : Annotation(java.lang.annotation.Annotation) MultiException(org.glassfish.hk2.api.MultiException) PrivilegedAction(java.security.PrivilegedAction) MultiException(org.glassfish.hk2.api.MultiException)

Example 25 with Method

use of org.glassfish.hk2.external.org.objectweb.asm.commons.Method in project jersey by jersey.

the class ContextInjectionResolverImpl method resolve.

/**
     * Jersey Injection Resolver method that just populate HK2 injectee object and delegates the processing to HK2 Injection
     * Resolver.
     *
     * @param injectee The injection point this value is being injected into
     * @return result of the injection processing.
     */
@Override
public Object resolve(org.glassfish.jersey.internal.inject.Injectee injectee) {
    InjecteeImpl hk2injectee = new InjecteeImpl() {

        @Override
        public Class<?> getInjecteeClass() {
            return injectee.getInjecteeClass();
        }
    };
    hk2injectee.setRequiredType(injectee.getRequiredType());
    hk2injectee.setRequiredQualifiers(injectee.getRequiredQualifiers());
    if (injectee.getInjecteeDescriptor() != null) {
        hk2injectee.setInjecteeDescriptor((ActiveDescriptor<?>) injectee.getInjecteeDescriptor().get());
    }
    // Delegate the call to HK2 Resolver, Service Handle is not need in the delegated processing.
    return resolve(hk2injectee, null);
}
Also used : InjecteeImpl(org.glassfish.hk2.utilities.InjecteeImpl)

Aggregations

MultiException (org.glassfish.hk2.api.MultiException)18 Method (java.lang.reflect.Method)16 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)12 GeneratorAdapter (org.glassfish.hk2.external.org.objectweb.asm.commons.GeneratorAdapter)8 Method (org.glassfish.hk2.external.org.objectweb.asm.commons.Method)8 PrivilegedActionException (java.security.PrivilegedActionException)7 ConnectorRuntimeException (com.sun.appserv.connectors.internal.api.ConnectorRuntimeException)6 URISyntaxException (java.net.URISyntaxException)6 ExecutionException (java.util.concurrent.ExecutionException)6 ResourceAdapterInternalException (javax.resource.spi.ResourceAdapterInternalException)6 ConfigBeanProxy (org.jvnet.hk2.config.ConfigBeanProxy)6 File (java.io.File)5 HashMap (java.util.HashMap)5 ConfigModel (org.jvnet.hk2.config.ConfigModel)5 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 Attribute (org.jvnet.hk2.config.Attribute)4 PropertyVetoException (java.beans.PropertyVetoException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 HashSet (java.util.HashSet)3