Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2013, Red Hat, Inc., and individual contributors
   * as indicated by the @author tags. See the copyright.txt file in the
   * distribution for a full listing of individual contributors.
   *
   * This is free software; you can redistribute it and/or modify it
   * under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation; either version 2.1 of
  * the License, or (at your option) any later version.
  *
  * This software is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  */
 
 package org.jboss.as.connector.util;
 
 import static org.jboss.as.connector.logging.ConnectorMessages.MESSAGES;
 
 import java.io.File;
 import java.util.List;
Injection utility which can inject values into objects. This file is a copy of the com.github.fungal.api.util.Injection class.

Author(s):
Jesper Pedersen
 
 public class Injection {
    
Constructor
 
     public Injection() {
     }

    
Inject a value into an object property

Parameters:
object The object
propertyName The property name
propertyValue The property value
Throws:
java.lang.NoSuchMethodException If the property method cannot be found
java.lang.IllegalAccessException If the property method cannot be accessed
java.lang.reflect.InvocationTargetException If the property method cannot be executed
 
     @SuppressWarnings("unchecked")
     public void inject(Object objectString propertyNameObject propertyValue)
         inject(objectpropertyNamepropertyValuenullfalse);
     }

    
Inject a value into an object property

Parameters:
object The object
propertyName The property name
propertyValue The property value
propertyType The property type as a fully quilified class name
Throws:
java.lang.NoSuchMethodException If the property method cannot be found
java.lang.IllegalAccessException If the property method cannot be accessed
java.lang.reflect.InvocationTargetException If the property method cannot be executed
 
     @SuppressWarnings("unchecked")
     public void inject(Object objectString propertyNameObject propertyValueString propertyType)
         inject(objectpropertyNamepropertyValuepropertyTypefalse);
     }

    
Inject a value into an object property

Parameters:
object The object
propertyName The property name
propertyValue The property value
propertyType The property type as a fully quilified class name
includeFields Should fields be included for injection if a method can't be found
Throws:
java.lang.NoSuchMethodException If the property method cannot be found
java.lang.IllegalAccessException If the property method cannot be accessed
java.lang.reflect.InvocationTargetException If the property method cannot be executed
 
     @SuppressWarnings("unchecked")
     public void inject(Object object,
                       String propertyNameObject propertyValueString propertyType,
                       boolean includeFields)
        if (object == null)
            throw new IllegalArgumentException(.nullVar("Object"));
        if (propertyName == null || propertyName.trim().equals(""))
            throw .undefinedVar("PropertyName");
        String methodName = "set" + propertyName.substring(0, 1).toUpperCase(.);
        if (propertyName.length() > 1) {
            methodName += propertyName.substring(1);
        }
        Method method = findMethod(object.getClass(), methodNamepropertyType);
        if (method != null) {
            Class<?> parameterClass = method.getParameterTypes()[0];
            Object parameterValue = null;
            try {
                parameterValue = getValue(propertyNameparameterClasspropertyValue,
                                          object.getClass().getClassLoader());
            } catch (Throwable t) {
                throw new InvocationTargetException(tt.getMessage());
            }
            if (!parameterClass.isPrimitive() || parameterValue != null)
                method.invoke(objectnew Object[] {parameterValue});
        } else {
            if (!includeFields)
                throw .noSuchMethod(methodName);
            // Ok, we didn't find a method - assume field
            Field field = findField(object.getClass(), propertyNamepropertyType);
            if (field != null) {
                Class<?> fieldClass = field.getType();
                Object fieldValue = null;
                try {
                    fieldValue = getValue(propertyNamefieldClasspropertyValue,
                                          object.getClass().getClassLoader());
                } catch (Throwable t) {
                    throw new InvocationTargetException(tt.getMessage());
                }
                field.set(objectfieldValue);
            } else {
                throw .noSuchField(propertyName);
            }
        }
    }

    
Compare a class name to the argument type of a Method, taking account of primitives

Parameters:
propertyType the class name to check
methodPropertyType the actual type of the property in the method
Returns:
true if they match
    private boolean argumentMatches(String classTypeString methodArgumentType)
    {
        return (classType.equals(methodArgumentType))
            || (classType.equals("java.lang.Byte") && methodArgumentType.equals("byte"))
            || (classType.equals("java.lang.Short") && methodArgumentType.equals("short"))
            || (classType.equals("java.lang.Integer") && methodArgumentType.equals("int"))
            || (classType.equals("java.lang.Long") && methodArgumentType.equals("long"))
            || (classType.equals("java.lang.Float") && methodArgumentType.equals("float"))
            || (classType.equals("java.lang.Double") && methodArgumentType.equals("double"))
            || (classType.equals("java.lang.Boolean") && methodArgumentType.equals("boolean"))
            || (classType.equals("java.lang.Character") && methodArgumentType.equals("char"))
            ;
    }

    
Find a method

Parameters:
clz The class
methodName The method name
propertyType The property type; can be null
Returns:
The method; null if not found
    protected Method findMethod(Class<?> clzString methodNameString propertyType) {
        while (!clz.equals(Object.class)) {
            List<Methodhits = null;
            Method[] methods = clz.getDeclaredMethods();
            for (int i = 0; i < methods.lengthi++) {
                Method method = methods[i];
                if (methodName.equals(method.getName()) && method.getParameterTypes().length == 1) {
                    if (propertyType == null || argumentMatches(propertyType,method.getParameterTypes()[0].getName())) {
                        if (hits == null)
                            hits = new ArrayList<Method>(1);
                        method.setAccessible(true);
                        hits.add(method);
                    }
                }
            }
            if (hits != null) {
                if (hits.size() == 1) {
                    return hits.get(0);
                } else {
                    Collections.sort(hitsnew MethodSorter());
                    if (propertyType != null) {
                        for (Method m : hits) {
                            if (propertyType.equals(m.getParameterTypes()[0].getName()))
                                return m;
                        }
                    }
                    return hits.get(0);
                }
            }
            clz = clz.getSuperclass();
        }
        return null;
    }

    
Find a field

Parameters:
clz The class
fieldName The field name
fieldType The field type; can be null
Returns:
The field; null if not found
    protected Field findField(Class<?> clzString fieldNameString fieldType) {
        while (!clz.equals(Object.class)) {
            List<Fieldhits = null;
            Field[] fields = clz.getDeclaredFields();
            for (int i = 0; i < fields.lengthi++) {
                Field field = fields[i];
                if (fieldName.equals(field.getName())) {
                    if (fieldType == null || fieldType.equals(field.getType().getName())) {
                        if (hits == null)
                            hits = new ArrayList<Field>(1);
                        field.setAccessible(true);
                        hits.add(field);
                    }
                }
            }
            if (hits != null) {
                if (hits.size() == 1) {
                    return hits.get(0);
                } else {
                    Collections.sort(hitsnew FieldSorter());
                    if (fieldType != null) {
                        for (Field f : hits) {
                            if (fieldType.equals(f.getType().getName()))
                                return f;
                        }
                    }
                    return hits.get(0);
                }
            }
            clz = clz.getSuperclass();
        }
        return null;
    }

    
Get the value

Parameters:
name The value name
clz The value class
v The value
cl The class loader
Returns:
The substituted value
Throws:
java.lang.Exception Thrown in case of an error
    protected Object getValue(String nameClass<?> clzObject vClassLoader clthrows Exception {
        if (v instanceof String) {
            String substituredValue = getSubstitutionValue((String)v);
            if (clz.equals(String.class)) {
                v = substituredValue;
            } else if (clz.equals(byte.class) || clz.equals(Byte.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Byte.valueOf(substituredValue);
            } else if (clz.equals(short.class) || clz.equals(Short.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Short.valueOf(substituredValue);
            } else if (clz.equals(int.class) || clz.equals(Integer.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Integer.valueOf(substituredValue);
            } else if (clz.equals(long.class) || clz.equals(Long.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Long.valueOf(substituredValue);
            } else if (clz.equals(float.class) || clz.equals(Float.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Float.valueOf(substituredValue);
            } else if (clz.equals(double.class) || clz.equals(Double.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Double.valueOf(substituredValue);
            } else if (clz.equals(boolean.class) || clz.equals(Boolean.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Boolean.valueOf(substituredValue);
            } else if (clz.equals(char.class) || clz.equals(Character.class)) {
                if (substituredValue != null && !substituredValue.trim().equals(""))
                    v = Character.valueOf(substituredValue.charAt(0));
            } else if (clz.equals(InetAddress.class)) {
                v = InetAddress.getByName(substituredValue);
            } else if (clz.equals(Class.class)) {
                v = Class.forName(substituredValuetruecl);
            } else if (clz.equals(Properties.class)) {
                Properties prop = new Properties();
                StringTokenizer st = new StringTokenizer(substituredValue" ,");
                while (st.hasMoreTokens()) {
                    String token = st.nextToken();
                    String key = "";
                    String value = "";
                    int index = token.indexOf("=");
                    if (index != -1) {
                        key = token.substring(0, index);
                        if (token.length() > index + 1)
                            value = token.substring(index + 1);
                    } else {
                        key = token;
                    }
                    if (!"".equals(key))
                        prop.setProperty(keyvalue);
                }
                v = prop;
            } else {
                try {
                    Constructor<?> constructor = clz.getConstructor(String.class);
                    v = constructor.newInstance(substituredValue);
                } catch (Throwable t) {
                    // Try static String valueOf method
                    try {
                        Method valueOf = clz.getMethod("valueOf"String.class);
                        v = valueOf.invoke((Object)nullsubstituredValue);
                    } catch (Throwable inner) {
                        throw .noPropertyResolution(name);
                    }
                }
            }
        }
        return v;
    }

    
System property substitution

Parameters:
input The input string
Returns:
The output
    protected String getSubstitutionValue(String input) {
        if (input == null || input.trim().equals(""))
            return input;
        while (input.indexOf("${") != -1) {
            int from = input.indexOf("${");
            int to = input.indexOf("}");
            int dv = input.indexOf(":"from + 2);
            if (dv != -1) {
                if (dv > to)
                    dv = -1;
            }
            String systemProperty = "";
            String defaultValue = "";
            if (dv == -1) {
                String s = input.substring(from + 2, to);
                if ("/".equals(s)) {
                    systemProperty = .;
                } else if (":".equals(s)) {
                    systemProperty = .;
                } else {
                    systemProperty = WildFlySecurityManager.getPropertyPrivileged(snull);
                }
            } else {
                systemProperty = WildFlySecurityManager.getPropertyPrivileged(input.substring(from + 2, dv), null);
                defaultValue = input.substring(dv + 1, to);
            }
            String prefix = "";
            String postfix = "";
            if (from != 0) {
                prefix = input.substring(0, from);
            }
            if (to + 1 < input.length() - 1) {
                postfix = input.substring(to + 1);
            }
            if (systemProperty != null && !systemProperty.trim().equals("")) {
                input = prefix + systemProperty + postfix;
            } else if (defaultValue != null && !defaultValue.trim().equals("")) {
                input = prefix + defaultValue + postfix;
            } else {
                input = prefix + postfix;
            }
        }
        return input;
    }

    
Method sorter
    static class MethodSorter implements Comparator<Method> {

        
Constructor
        MethodSorter() {
        }

        
        public int compare(Method o1Method o2) {
            int m1 = o1.getModifiers();
            int m2 = o2.getModifiers();
            if (Modifier.isPublic(m1))
                return -1;
            if (Modifier.isPublic(m2))
                return 1;
            if (Modifier.isProtected(m1))
                return -1;
            if (Modifier.isProtected(m2))
                return 1;
            if (Modifier.isPrivate(m1))
                return -1;
            if (Modifier.isPrivate(m2))
                return 1;
            return 0;
        }

        
        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || !(o instanceof MethodSorter))
                return false;
            return true;
        }

        
        public int hashCode() {
            return 42;
        }
    }

    
Field sorter
    static class FieldSorter implements Comparator<Field> {

        
Constructor
        FieldSorter() {
        }

        
        public int compare(Field o1Field o2) {
            int m1 = o1.getModifiers();
            int m2 = o2.getModifiers();
            if (Modifier.isPublic(m1))
                return -1;
            if (Modifier.isPublic(m2))
                return 1;
            if (Modifier.isProtected(m1))
                return -1;
            if (Modifier.isProtected(m2))
                return 1;
            if (Modifier.isPrivate(m1))
                return -1;
            if (Modifier.isPrivate(m2))
                return 1;
            return 0;
        }

        
        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || !(o instanceof FieldSorter))
                return false;
            return true;
        }

        
        public int hashCode() {
            return 42;
        }
    }
New to GrepCode? Check out our FAQ X