Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2011, FuseSource Corp. All rights reserved. http://fusesource.com The software in this package is published under the terms of the CDDL license a copy of which has been included with this distribution in the license.txt file.
  
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
 
 package org.fusesource.fabric.dosgi.util;
 
 import java.util.Map;
 
 
 
 public final class IntrospectionSupport {
 	
     private IntrospectionSupport() {
     }
 
     public static boolean getProperties(Object targetMap propsString optionPrefix) {
 
         boolean rc = false;
         if (target == null) {
             throw new IllegalArgumentException("target was null.");
         }
         if (props == null) {
             throw new IllegalArgumentException("props was null.");
         }
 
         if (optionPrefix == null) {
             optionPrefix = "";
         }
 
         Class<?> clazz = target.getClass();
         Method[] methods = clazz.getMethods();
         for (int i = 0; i < methods.lengthi++) {
             Method method = methods[i];
             String name = method.getName();
             Class<?> type = method.getReturnType();
             Class<?> params[] = method.getParameterTypes();
             if ((name.startsWith("is") || name.startsWith("get")) && params.length == 0 && type != null && isSettableType(type)) {
 
                 try {
 
                     Object value = method.invoke(targetnew Object[] {});
                     if (value == null) {
                         continue;
                     }
 
                     String strValue = convertToString(valuetype);
                     if (strValue == null) {
                         continue;
                     }
                     if (name.startsWith("get")) {
                         name = name.substring(3, 4).toLowerCase()
                                 + name.substring(4);
                     } else {
                         name = name.substring(2, 3).toLowerCase()
                                 + name.substring(3);
                     }
                     props.put(optionPrefix + namestrValue);
                     rc = true;
 
                 } catch (Throwable ignore) {
                 }
 
             }
         }
 
         return rc;
     }
 
    public static boolean setProperties(Object targetMap<String, ?> propsString optionPrefix) {
        boolean rc = false;
        if (target == null) {
            throw new IllegalArgumentException("target was null.");
        }
        if (props == null) {
            throw new IllegalArgumentException("props was null.");
        }
        for (Iterator<Stringiter = props.keySet().iterator(); iter.hasNext();) {
            String name = iter.next();
            if (name.startsWith(optionPrefix)) {
                Object value = props.get(name);
                name = name.substring(optionPrefix.length());
                if (setProperty(targetnamevalue)) {
                    iter.remove();
                    rc = true;
                }
            }
        }
        return rc;
    }
    public static Map<StringObjectextractProperties(Map propsString optionPrefix) {
        if (props == null) {
            throw new IllegalArgumentException("props was null.");
        }
        HashMap<StringObjectrc = new HashMap<StringObject>(props.size());
        for (Iterator<Entryiter = props.entrySet().iterator(); iter.hasNext();) {
            Entry entry = iter.next();
            String name = (String)entry.getKey();
            if (name.startsWith(optionPrefix)) {
                name = name.substring(optionPrefix.length());
                rc.put(nameentry.getValue());
                iter.remove();
            }
        }
        return rc;
    }
    public static boolean setProperties(Object targetMap props) {
        boolean rc = false;
        if (target == null) {
            throw new IllegalArgumentException("target was null.");
        }
        if (props == null) {
            throw new IllegalArgumentException("props was null.");
        }
        for (Iterator<Entryiter = props.entrySet().iterator(); iter.hasNext();) {
            Map.Entry entry = iter.next();
            if (setProperty(target, (String)entry.getKey(), entry.getValue())) {
                iter.remove();
                rc = true;
            }
        }
        return rc;
    }
    public static Class<?> getPropertyType(Object targetString name) {
        Class<?> clazz = target.getClass();
        Method setter = findSetterMethod(clazzname);
        if (setter == null) {
            return null;
        }
        return setter.getParameterTypes()[0];
    }
    
    public static boolean setProperty(Object targetString nameObject value) {
        try {
            Class<?> clazz = target.getClass();
            Method setter = findSetterMethod(clazzname);
            if (setter == null) {
                return false;
            }
            // If the type is null or it matches the needed type, just use the
            // value directly
            if (value == null || value.getClass() == setter.getParameterTypes()[0]) {
                setter.invoke(targetnew Object[] {value});
            } else {
                // We need to convert it
                setter.invoke(targetnew Object[] {convert(valuesetter.getParameterTypes()[0])});
            }
            return true;
        } catch (Throwable ignore) {
            return false;
        }
    }
    private static Object convert(Object valueClass<?> type) {
        iftype.isArray() ) {
            ifvalue.getClass().isArray() ) {
                int length = Array.getLength(value);
                Class<?> componentType = type.getComponentType();
                Object rc = Array.newInstance(componentTypelength);
                for (int i = 0; i < lengthi++) {
                    Object o = Array.get(valuei);
                    Array.set(rciconvert(ocomponentType));
                }
                return rc;
            }
        }
        PropertyEditor editor = PropertyEditorManager.findEditor(type);
        if (editor != null) {
            editor.setAsText(value.toString());
            return editor.getValue();
        }
        return null;
    }
    public static String convertToString(Object valueClass<?> type) {
        PropertyEditor editor = PropertyEditorManager.findEditor(type);
        if (editor != null) {
            editor.setValue(value);
            return editor.getAsText();
        }
        return null;
    }
    private static Method findSetterMethod(Class<?> clazzString name) {
        // Build the method name.
        name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);
        Method[] methods = clazz.getMethods();
        for (int i = 0; i < methods.lengthi++) {
            Method method = methods[i];
            Class<?> params[] = method.getParameterTypes();
            if (method.getName().equals(name) && params.length == 1 ) {
                return method;
            }
        }
        return null;
    }
    private static boolean isSettableType(Class<?> clazz) {
        if (PropertyEditorManager.findEditor(clazz) != null) {
            return true;
        }
        	
        return false;
    }
    public static String toString(Object target) {
        return toString(targetObject.classnull, (String[])null);
    }
    
    public static String toString(Object targetString...fields) {
        return toString(targetObject.classnullfields);
    }
    
    public static String toString(Object targetClass<?> stopClass) {
    	return toString(targetstopClassnull, (String[])null);
    }
    public static String toString(Object targetMap<StringObjectoverrideFieldsString...fields) {
        return toString(targetObject.classoverrideFieldsfields);
    }
    public static String toString(Object targetClass<?> stopClassMap<StringObjectoverrideFieldsString ... fields) {
        try {
            LinkedHashMap<StringObjectmap = new LinkedHashMap<StringObject>();
            addFields(targettarget.getClass(), stopClassmap);
            if (overrideFields != null) {
            	for(String key : overrideFields.keySet()) {
            	    Object value = overrideFields.get(key);
            	    map.put(keyvalue);
            	}
            }
            
            iffields!=null ) {
                map.keySet().retainAll(Arrays.asList(fields));
            }
           
            boolean useMultiLine=false;
            LinkedHashMap<StringStringprops = new LinkedHashMap<StringString>();
            for (Entry<StringObjectentry : map.entrySet()) {
                String key = entry.getKey();
                String value = null;
                ifentry.getValue() !=null ) {
                    value = entry.getValue().toString();
                    ifvalue!=null && ( value.indexOf('\n')>=0 || (key.length()+value.length())>70 ) ) {
                        useMultiLine=true;
                    }
                }
                props.put(keyvalue);
            }
            
            StringBuffer buffer = new StringBuffer();
            ifuseMultiLine) {
                buffer.append("{\n");
                boolean first = true;
                for (Entry<StringStringentry : props.entrySet()) {
                    if (first) {
                        first = false;
                    } else {
                        buffer.append(",\n");
                    }
                    buffer.append("  ");
                    buffer.append(entry.getKey());
                    buffer.append(": ");
                    buffer.append(StringSupport.indent(entry.getValue(), 2));
                }
                buffer.append("\n}");
            } else {
                buffer.append("{");
                boolean first = true;
                for (Entry<StringStringentry : props.entrySet()) {
                    if (first) {
                        first = false;
                    } else {
                        buffer.append(", ");
                    }
                    buffer.append(entry.getKey());
                    buffer.append(": ");
                    String value = entry.getValue();
                    buffer.append(value);
                }
                buffer.append("}");
            }
            return buffer.toString();
        } catch (Throwable e) {
            e.printStackTrace();
            return "Could not toString: "+e.toString();
        }
    }
    public static String simpleName(Class<?> clazz) {
        String name = clazz.getName();
        int p = name.lastIndexOf(".");
        if (p >= 0) {
            name = name.substring(p + 1);
        }
        return name;
    }
    private static void addFields(Object targetClass<?> startClassClass<?> stopClassLinkedHashMap<StringObjectmap) {
        if (startClass != stopClass) {
            addFields(targetstartClass.getSuperclass(), stopClassmap);
        }
        Field[] fields = startClass.getDeclaredFields();
        for (int i = 0; i < fields.lengthi++) {
            Field field = fields[i];
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            try {
                field.setAccessible(true);
                Object o = field.get(target);
                if (o != null && o.getClass().isArray()) {
                    try {
                        o = Arrays.asList((Object[])o);
                    } catch (Throwable e) {
                    }
                }
                map.put(field.getName(), o);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
    }
New to GrepCode? Check out our FAQ X