Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package bpiwowar.argparser;
  
 
This class is is a utility class for searching for handlers

Author(s):
B. Piwowarski
 
 public class Handlers {
     final static private Logger logger = Logger.getLogger(Logger.class);
 
     private static void log(Level levelString formatObject... objects) {
         .log(level, String.format(formatobjects));
     }

    
The list of potential handlers and the class that checks for their adequacy
 
     static private ArrayList<Pair<Class<? extends Handler>, TypeCheckerInterface>> defaultHandlers = new ArrayList<Pair<Class<? extends Handler>, TypeCheckerInterface>>();
 
     // --- Initialize the handlers ---
     static {
         ArrayList<Class<?>> classes = Introspection.getClasses(
                 new Introspection.Checker() {
                     public boolean accepts(Class<?> aClass) {
                         return true;
                     }
                 }, ArgParser.class.getPackage().getName() + ".handlers", -1);
         for (Class<?> c : classes) {
             .debug("Holders list: examining " + c + " "
                     + Handler.class.isAssignableFrom(c));
             if (Handler.class.isAssignableFrom(c))
                 try {
                     HandlerInformation wrapperType = c
                             .getAnnotation(HandlerInformation.class);
                     TypeCheckerInterface checker = null;
 
                     if (wrapperType != null) {
                         if (wrapperType.value().length == 1
                                 && TypeCheckerInterface.class
                                 .isAssignableFrom(wrapperType.value()[0]))
                             checker = (TypeCheckerInterfacewrapperType
                                     .value()[0].newInstance();
                         else
                             checker = new TypeChecker(wrapperType.value());
                     }
 
                     if (checker != null) {
                         @SuppressWarnings("unchecked")
                         Class<? extends Handlerc2 = (Class<? extends Handler>) c;
                         
                                 .add(new Pair<Class<? extends Handler>, TypeCheckerInterface>(
                                         c2checker));
                         .debug("Adding wrapper " + c + " with checker "
                                 + checker);
                     }
                 } catch (Exception e) {
                     .debug("Cannot check object " + c.getName() + ": "
                             + e);
                 }
         }
     }

    
Get a handler for a given object member

Parameters:
object The object
member The member
annotationHandler The annotation
Returns:
A handler
Throws:
InvalidHolderException If the assigned handler cannot handle the object type
 
     static Handler getHandler(Object objectAccessibleObject member,
                               Class<? extends HandlerannotationHandler,
                               Class<? extends ValueChecker>[] checkers)
             throws InvalidHolderException {
 
         // The member is a field
         if (member instanceof Field) {
             final Field field = (Fieldmember;
             return getHandler(object, (Fieldmemberfield.getGenericType(),
                    new AnnotatedElementAnnotationMap(field.getType()),
                    annotationHandlercheckers);
        }
        // The member is a method
        if (member instanceof Method)
            return getCallableHandler(objectnullnew CallableMethod((Methodmember));
        throw new RuntimeException("Cannnot process member of type "
                + member.getClass());
    }


    
Get the handler for a callable

Parameters:
object The object that contains the method or the object that contain the field
field The field
callable The method that should be called
Returns:
The handler
Throws:
InvalidHolderException
    private static Handler getCallableHandler(Object objectField fieldCallable callable)
            throws InvalidHolderException {
        try {
            // Construct the handler
            Type[] parameters = callable.getGenericParameterTypes();
            Annotation[][] pAnnotations = callable.getParameterAnnotations();
            final int length = parameters.length;
            final Handler[] handlers = new Handler[length];
            final ObjectHolder<?>[] holders = new ObjectHolder[length];
            log(."Processing callable %s (%d arguments)"callable,
                    length);
            // Parse every callable argument
            for (int i = 0; i < lengthi++) {
                final ListAnnotationMap a = new ListAnnotationMap(
                        pAnnotations[i]);
                final Argument pa = a.getAnnotation(Argument.class);
                holders[i] = new ObjectHolder<Object>();
                log(.,
                        "Searching a handler for the %dth argument with annotation %s, and type %s",
                        i + 1, paparameters[i]);
                // Set the handler
                handlers[i] = getHandler(holders[i],
                        holders[i].getValueField(), parameters[i], a,
                        pa != null ? pa.handler() : Handler.class,
                        pa != null ? pa.checkers() : null);
            }
            // --- Setting the overall handler
            ArgumentRegexp regexp = callable.getAnnotation(ArgumentRegexp.class);
            return new CallableHandler(objectfieldcallablehandlersholders,
                    regexp != null ? regexp.value() : null);
        } catch (RuntimeException e) {
            throw e;
        } catch (Throwable e) {
            throw new InvalidHolderException(e);
        }
    }

    
Get the class of the type

Parameters:
type A given type
Returns:
The class
    static Class<?> getTypeClass(Type type) {
        if (type instanceof Class<?>)
            return (Class<?>) type;
        if (type instanceof ParameterizedType)
            return (Class<?>) ((ParameterizedTypetype).getRawType();
        throw new RuntimeException();
    }

    
Get the handler for an object member (either a method or a field)

Parameters:
object The object containing the field
field The field
fieldType The field type
annotationHandler The handler declared for the field (if any)
checkers The checkers for this handler
Returns:
The handler object If a handler object has been given
Throws:
InvalidHolderException If we did not find any holder
    static Handler getHandler(Object objectField fieldType fieldType,
                              AnnotationMap annotations,
                              Class<? extends HandlerannotationHandler,
                              Class<? extends ValueChecker>[] checkers)
            throws InvalidHolderException {
        log(."Finding a handler for %s (type %s)"fieldfieldType);
        Handler handler = null;
        // --- Try to find a handler class from field class annotations
        // Get the type of field
        Class<?> fieldClass = getTypeClass(fieldType);
        Class<? extends HandlerhandlerClass = null;
        if (!annotationHandler.equals(Handler.class))
            handlerClass = annotationHandler;
        else if (annotations.getAnnotation(ArgumentHandler.class) != null)
            handlerClass = annotations.getAnnotation(ArgumentHandler.class)
                    .value();
        // If we have a designated handler
        if (handlerClass != null) {
            try {
                Constructor<? extends Handlerconstructor = handlerClass
                        .getConstructor(new Class[]{Object.classField.class});
                handler = constructor
                        .newInstance(new Object[]{objectfield});
            } catch (SecurityException e) {
                throw new InvalidHolderException(
                        "Security exception while searching for wrapper constructor of "
                                + annotationHandlere);
            } catch (NoSuchMethodException e) {
                throw new InvalidHolderException(
                        "No valid constructor for wrapper " + annotationHandler
                                + " for field " + fielde);
            } catch (Exception e) {
                throw new InvalidHolderException(
                        "Error while constructing wrapper " + annotationHandler
                                + " for field " + fielde);
            }
        } else {
            if (Handler.class.isAssignableFrom(fieldClass)) {
                try {
                    handler = (Handlerfield.get(object);
                } catch (Exception e) {
                    throw new InvalidHolderException(e);
                }
            } else {
                // --- Try to see if there is a method with @ArgumentProcessor
                // annotation
                for (Method method : fieldClass.getDeclaredMethods()) {
                    final ArgumentProcessor argProcessorAnt = method
                            .getAnnotation(ArgumentProcessor.class);
                    if (argProcessorAnt != null) {
                        try {
                            // --- Setting the overall handler
                            boolean accessible = field.isAccessible();
                            if (!accessible)
                                field.setAccessible(true);
                            Object fieldObject = field.get(object);
                            if (!accessible)
                                field.setAccessible(false);
                            handler = getCallableHandler(fieldObjectnullnew CallableMethod(method)
                            );
                        } catch (RuntimeException e) {
                            throw e;
                        } catch (Throwable e) {
                            throw new InvalidHolderException(e);
                        }
                    }
                }
                // --- Otherwise, we try to find a holder
                if (handler == null) {
                    if (Enum.class.isAssignableFrom(fieldClass)) {
                        EnumHandler enumWrapper = new EnumHandler(objectfield);
                        handler = enumWrapper;
                    } else {
                        // Search through the handlers
                        handler = getHandler(fieldTypeobjectfieldfieldClass);
                    }
                }
                // Check for constructors
                if (handler == null) {
                    for (Constructor<?> constructor : fieldClass.getConstructors()) {
                        if (constructor.getAnnotation(ArgumentConstructor.class) != null) {
                            handler = getCallableHandler(objectfieldnew CallableConstructor(constructor));
                            break;
                        }
                    }
                }
            }
        }
        if (handler == null)
            throw new InvalidHolderException(String.format(
                    "Cannot construct holder for type of: %s"fieldType));
        // --- Set the checkers
        if (checkers != null)
            for (Class<? extends ValueCheckerchecker : checkers)
                try {
                    log(."Adding checker of class %s"checker);
                    handler.add(checker.newInstance());
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                }
        .debug("Found handler " + handler.getClass().getName() + " for "
                + fieldType + " / " + field.getName());
        return handler;
    }

    
Search for a registered handler for a given value

Parameters:
type The type of the object
field The field (in the case of an object)
fieldClass Case of creation
Returns:
A handler
Throws:
InvalidHolderException If an handler cannot be found
    private static Handler getHandler(Type typeObject objectField field,
                                      Class<?> fieldClassthrows InvalidHolderException {
        .debug("Searching a handler for type " + type);
        for (Pair<Class<? extends Handler>, TypeCheckerInterfacew : ) {
            // Get the annotation
            .debug("Checking compatibility of " + w);
            if (w.getSecond().isCompatible(type)) {
                try {
                    Constructor<? extends Handlerconstructor = w.getFirst()
                            .getConstructor(
                                    new Class<?>[]{Object.classField.class,
                                            Class.class});
                    return constructor.newInstance(objectfieldfieldClass);
                } catch (Exception e) {
                }
                try {
                    Constructor<? extends Handlerconstructor = w
                            .getFirst()
                            .getConstructor(
                                    new Class<?>[]{Object.classField.class});
                    return constructor.newInstance(objectfield);
                } catch (Exception e) {
                    throw new InvalidHolderException(
                            "Cannot create a new instance of handler %s"e,
                            w.getFirst());
                }
            }
        }
        return null;
    }
    // --- Generic interface for Method and Constructor
    public interface Callable {
        public abstract Type[] getGenericParameterTypes();
        public abstract Annotation[][] getParameterAnnotations();
        public <T extends Annotation> T getAnnotation(Class<T> annotationClass);
        boolean isAccessible();
        void setAccessible(boolean b);
    }
    static public class CallableMethod implements Callable {
        Method method;
        public CallableMethod(Method method) {
            this. = method;
        }
        @Override
        public Type[] getGenericParameterTypes() {
            return .getGenericParameterTypes();
        }
        @Override
        public Annotation[][] getParameterAnnotations() {
            return .getParameterAnnotations();
        }
        @Override
        public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
            return .getAnnotation(annotationClass);
        }
        @Override
        public boolean isAccessible() {
            return .isAccessible();
        }
        @Override
        public void setAccessible(boolean b) {
            .setAccessible(b);
        }
        public Object invoke(Object objectObject[] objectsthrows InvocationTargetExceptionIllegalAccessException {
            return .invoke(objectobjects);
        }
    }
    static public class CallableConstructor implements Callable {
        Constructor<?> constructor;
        public CallableConstructor(Constructor<?> constructor) {
            this. = constructor;
        }
        @Override
        public Type[] getGenericParameterTypes() {
            return .getGenericParameterTypes();
        }
        @Override
        public Annotation[][] getParameterAnnotations() {
            return .getParameterAnnotations();
        }
        @Override
        public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
            return .getAnnotation(annotationClass);
        }
        @Override
        public boolean isAccessible() {
            return .isAccessible();
        }
        @Override
        public void setAccessible(boolean b) {
            .setAccessible(b);
        }
            return .newInstance(objects);
        }
    }
New to GrepCode? Check out our FAQ X