Example usage for java.lang Class getAnnotations

List of usage examples for java.lang Class getAnnotations

Introduction

In this page you can find the example usage for java.lang Class getAnnotations.

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadCommandHandlers() throws ThinklabException {

    String ipack = this.getClass().getPackage().getName() + ".commands";

    for (Class<?> cls : MiscUtilities.findSubclasses(ICommandHandler.class, ipack, getClassLoader())) {

        /*/*from w w w  .  jav  a2 s. c  om*/
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        /*
         * lookup implemented concept
         */
        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation instanceof ThinklabCommand) {

                String name = ((ThinklabCommand) annotation).name();
                String description = ((ThinklabCommand) annotation).description();

                CommandDeclaration declaration = new CommandDeclaration(name, description);

                String retType = ((ThinklabCommand) annotation).returnType();

                if (!retType.equals(""))
                    declaration.setReturnType(KnowledgeManager.get().requireConcept(retType));

                String[] aNames = ((ThinklabCommand) annotation).argumentNames().split(",");
                String[] aTypes = ((ThinklabCommand) annotation).argumentTypes().split(",");
                String[] aDesc = ((ThinklabCommand) annotation).argumentDescriptions().split(",");

                for (int i = 0; i < aNames.length; i++) {
                    if (!aNames[i].isEmpty())
                        declaration.addMandatoryArgument(aNames[i], aDesc[i], aTypes[i]);
                }

                String[] oaNames = ((ThinklabCommand) annotation).optionalArgumentNames().split(",");
                String[] oaTypes = ((ThinklabCommand) annotation).optionalArgumentTypes().split(",");
                String[] oaDesc = ((ThinklabCommand) annotation).optionalArgumentDescriptions().split(",");
                String[] oaDefs = ((ThinklabCommand) annotation).optionalArgumentDefaultValues().split(",");

                for (int i = 0; i < oaNames.length; i++) {
                    if (!oaNames[i].isEmpty())
                        declaration.addOptionalArgument(oaNames[i], oaDesc[i], oaTypes[i], oaDefs[i]);
                }

                String[] oNames = ((ThinklabCommand) annotation).optionNames().split(",");
                String[] olNames = ((ThinklabCommand) annotation).optionLongNames().split(",");
                String[] oaLabel = ((ThinklabCommand) annotation).optionArgumentLabels().split(",");
                String[] oTypes = ((ThinklabCommand) annotation).optionTypes().split(",");
                String[] oDesc = ((ThinklabCommand) annotation).optionDescriptions().split(",");

                for (int i = 0; i < oNames.length; i++) {
                    if (!oNames[i].isEmpty())
                        declaration.addOption(oNames[i], olNames[i],
                                (oaLabel[i].equals("") ? null : oaLabel[i]), oDesc[i], oTypes[i]);
                }

                try {
                    CommandManager.get().registerCommand(declaration, (ICommandHandler) cls.newInstance());
                } catch (Exception e) {
                    throw new ThinklabValidationException(e);
                }

                break;
            }
        }
    }

}

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadInstanceImplementationConstructors() throws ThinklabPluginException {

    String ipack = this.getClass().getPackage().getName() + ".implementations";

    for (Class<?> cls : MiscUtilities.findSubclasses(IInstanceImplementation.class, ipack, getClassLoader())) {

        String concept = null;//from  w ww .  ja v  a2s  . c  o m

        /*
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        /*
         * lookup implemented concept
         */
        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation instanceof InstanceImplementation) {
                concept = ((InstanceImplementation) annotation).concept();
            }
        }

        if (concept != null) {

            String[] cc = concept.split(",");

            for (String ccc : cc) {
                logger().info("registering class " + cls + " as implementation for instances of type " + ccc);
                KnowledgeManager.get().registerInstanceImplementationClass(ccc, cls);
            }
        }
    }
}

From source file:com.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * false?/*  w  w  w. j a  va 2 s. com*/
 * 
 * @param controllerClazz
 *            
 * @param actionMethod
 *            ?
 * @return
 */
protected final boolean checkRequiredAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> requiredAnnotations = getRequiredAnnotationClasses();
    if (requiredAnnotations == null || requiredAnnotations.size() == 0) {
        return true;
    }
    for (Class<? extends Annotation> requiredAnnotation : requiredAnnotations) {
        if (requiredAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(requiredAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
        }
    }
    return false;
}

From source file:org.integratedmodelling.thinklab.plugin.ThinklabPlugin.java

protected void loadLiteralValidators() throws ThinklabException {

    String ipack = this.getClass().getPackage().getName() + ".literals";

    for (Class<?> cls : MiscUtilities.findSubclasses(ParsedLiteralValue.class, ipack, getClassLoader())) {

        String concept = null;//from w  ww  .j  a v  a  2s . c o m
        String xsd = null;

        /*
         * lookup annotation, ensure we can use the class
         */
        if (cls.isInterface() || Modifier.isAbstract(cls.getModifiers()))
            continue;

        /*
         * lookup implemented concept
         */
        for (Annotation annotation : cls.getAnnotations()) {
            if (annotation instanceof LiteralImplementation) {
                concept = ((LiteralImplementation) annotation).concept();
                xsd = ((LiteralImplementation) annotation).xsd();
            }
        }

        if (concept != null) {

            logger().info("registering class " + cls + " as implementation for literals of type " + concept);

            KnowledgeManager.get().registerLiteralImplementationClass(concept, cls);
            if (!xsd.equals(""))

                logger().info("registering XSD type mapping: " + xsd + " -> " + concept);
            KnowledgeManager.get().registerXSDTypeMapping(xsd, concept);
        }

    }

}

From source file:org.cleandroid.core.di.DependencyManager.java

public static Object getDependencyFromAnnotation(Annotation annotation, Object context, Class<?> varClass) {

    View contentView = null;//from   w  ww . jav  a  2s.c om
    Context elementContext = null;

    if (Activity.class.isAssignableFrom(context.getClass())) {
        contentView = ((Activity) context).findViewById(android.R.id.content);
        elementContext = (Context) context;
    }

    else if (Fragment.class.isAssignableFrom(context.getClass())) {
        contentView = ((Fragment) context).getView();
        elementContext = ((Fragment) context).getActivity();
    } else if (org.cleandroid.core.support.v4.Fragment.class.isAssignableFrom(context.getClass())) {
        contentView = ((org.cleandroid.core.support.v4.Fragment) context).getView();
        elementContext = ((org.cleandroid.core.support.v4.Fragment) context).getActivity();
    }

    else if (Dialog.class.isAssignableFrom(context.getClass())) {
        contentView = ((Dialog) context).findViewById(android.R.id.content);
        elementContext = ((Dialog) context).getContext();
        if (elementContext == null)
            elementContext = ((Dialog) context).getOwnerActivity();
    }

    if (CView.class.isInstance(annotation) && contentView != null) {
        int vid = ((CView) annotation).value();
        return contentView.findViewById(vid);
    } else if (CFragment.class.isInstance(annotation)) {
        CFragment cfa = (CFragment) annotation;
        if (Fragment.class.isAssignableFrom(varClass)) {
            if (cfa.id() != Integer.MIN_VALUE)
                return ((Activity) context).getFragmentManager().findFragmentById(cfa.id());
            else if (!cfa.tag().isEmpty())
                return ((Activity) context).getFragmentManager().findFragmentByTag(cfa.tag());
        } else if (org.cleandroid.core.support.v4.Fragment.class.isAssignableFrom(varClass)
                && FragmentActivity.class.isAssignableFrom(context.getClass())) {
            if (cfa.id() != Integer.MIN_VALUE)
                return ((FragmentActivity) context).getSupportFragmentManager().findFragmentById(cfa.id());
            else if (!cfa.tag().isEmpty())
                return ((FragmentActivity) context).getSupportFragmentManager().findFragmentByTag(cfa.tag());

        }

    }

    else if (InputValue.class.isInstance(annotation) && contentView != null) {

        Object rawValue = ViewUtils
                .getViewInputValue(contentView.findViewById(((InputValue) annotation).view()));
        if (TypeUtils.isPrimitiveOrWrapper(varClass))
            return TypeUtils.getTypedValue(String.valueOf(rawValue), varClass);
        return rawValue;
    }

    else if (SystemService.class.isInstance(annotation) && elementContext != null) {
        return elementContext.getSystemService(systemServicesMap.get(varClass));

    }

    else if (Inject.class.isInstance(annotation)) {
        for (Annotation annotation1 : varClass.getAnnotations()) {
            if (App.isDependencyProviderRegistered(annotation1.annotationType())) {
                return App.getDependencyProvider(annotation1.annotationType()).handle(varClass, context);
            }
        }

    }

    else if (ActivityContext.class.isInstance(annotation))
        return elementContext;
    else if (AppContext.class.isInstance(annotation))
        return elementContext.getApplicationContext();

    else if (IntentExtra.class.isInstance(annotation)) {
        if (context instanceof Activity) {
            if (((Activity) context).getIntent().getExtras() != null)
                return ((Activity) context).getIntent().getExtras().get(((IntentExtra) annotation).value());
        }
        return null;
    }

    else if (PersistenceContext.class.isInstance(annotation)) {
        DatasourcesConfig config = (DatasourcesConfig) App.getConfiguration("dbConfig");
        if (config == null)
            throw new RuntimeException("Configuration dbConfig was not found in cleandroid-config.xml");
        return Persistence.getEntityManager(((PersistenceContext) annotation).datasource());
    }

    return null;
}

From source file:org.apache.axis2.jaxws.description.impl.OperationDescriptionImpl.java

private FaultDescription[] createFaultDescriptions() {

    ArrayList<FaultDescription> buildFaultList = new ArrayList<FaultDescription>();

    if (!isDBC()) {
        // get exceptions this method "throws"
        Class[] webFaultClasses = seiMethod.getExceptionTypes();

        for (Class wfClass : webFaultClasses) {
            // according to JAXWS 3.7, the @WebFault annotation is only used for customizations,
            // so we'll add all declared exceptions
            WebFault wfanno = null;
            for (Annotation anno : wfClass.getAnnotations()) {
                if (anno.annotationType() == WebFault.class) {
                    wfanno = (WebFault) anno;
                }// ww w . jav a2s.co  m
            }
            buildFaultList.add(new FaultDescriptionImpl(wfClass, wfanno, this));
        }
    } else {
        // TODO do I care about methodComposite like the paramDescription does?
        //Call FaultDescriptionImpl for all non-generic exceptions...Need to check a
        // a couple of things
        // 1. If this is a generic exception, ignore it
        // 2. If this is not a generic exception, then find it in the DBC Map
        //       If not found in map, then throw not found exception
        //3. Pass the validated WebFault dbc and possibly the classImpl dbc to FaultDescription
        //4. Possibly set AxisOperation.setFaultMessages array...or something like that

        String[] webFaultClassNames = methodComposite.getExceptions();

        HashMap<String, DescriptionBuilderComposite> dbcMap = getEndpointInterfaceDescriptionImpl()
                .getEndpointDescriptionImpl().getServiceDescriptionImpl().getDBCMap();

        if (webFaultClassNames != null) {
            for (String wfClassName : webFaultClassNames) {
                //   Try to find this exception class in the dbc list. If we can't find it
                //  then just assume that its a generic exception.

                DescriptionBuilderComposite faultDBC = dbcMap.get(wfClassName);

                if (faultDBC != null) {
                    // JAXWS 3.7 does not require @WebFault annotation
                    // We found a valid exception composite thats annotated
                    buildFaultList.add(new FaultDescriptionImpl(faultDBC, this));
                }

            }
        }
    }

    return buildFaultList.toArray(new FaultDescription[0]);
}

From source file:org.openecomp.sdnc.sli.aai.AAIDeclarations.java

private QueryStatus newModelSave(String resource, boolean force, String key, Map<String, String> parms,
        String prefix, SvcLogicContext ctx) {
    getLogger().debug("Executing newModelSave for resource : " + resource);
    HashMap<String, String> nameValues = keyToHashMap(key, ctx);

    try {/*from  w ww.  jav a2s  . c  o m*/
        ArrayList<String> subResources = new ArrayList<String>();
        Set<String> set = parms.keySet();
        Map<String, Method> setters = new HashMap<String, Method>();
        Map<String, Method> getters = new HashMap<String, Method>();

        // 1. find class
        AAIRequest request = AAIRequest.createRequest(resource, nameValues);
        Class<? extends AAIDatum> resourceClass = request.getModelClass();
        getLogger().debug(resourceClass.getName());
        AAIDatum instance = resourceClass.newInstance();

        {
            Annotation[] annotations = resourceClass.getAnnotations();
            for (Annotation annotation : annotations) {
                Class<? extends Annotation> anotationType = annotation.annotationType();
                String annotationName = anotationType.getName();
                //               if("com.fasterxml.jackson.annotation.JsonPropertyOrder".equals(annotationName)){

                // 2. find string property setters and getters for the lists
                if ("javax.xml.bind.annotation.XmlType".equals(annotationName)) {
                    XmlType order = (XmlType) annotation;
                    String[] values = order.propOrder();
                    for (String value : values) {
                        String id = camelCaseToDashedString(value);
                        Field field = resourceClass.getDeclaredField(value);
                        Class<?> type = field.getType();
                        Method setter = null;
                        try {
                            setter = resourceClass.getMethod("set" + StringUtils.capitalize(value), type);
                            if (type.getName().startsWith("java.lang") || "boolean".equals(type.getName())
                                    || "long".equals(type.getName())) {
                                try {
                                    setter.setAccessible(true);
                                    Object arglist[] = new Object[1];
                                    arglist[0] = parms.get(id);

                                    if (arglist[0] != null) {
                                        if (!type.getName().equals("java.lang.String")) {
                                            //                                 getLogger().debug(String.format("Processing %s with parameter %s", types[0].getName(), value));
                                            if ("boolean".equals(type.getName())) {
                                                arglist[0] = valueOf(Boolean.class, parms.get(id));
                                            } else if ("long".equals(type.getName())) {
                                                arglist[0] = valueOf(Long.class, parms.get(id));
                                            } else {
                                                arglist[0] = valueOf(type, parms.get(id));
                                            }
                                        }
                                        Object o = setter.invoke(instance, arglist);
                                    }
                                    set.remove(id);

                                } catch (Exception x) {
                                    Throwable cause = x.getCause();
                                    getLogger().warn("Failed process for " + resourceClass.getName(), x);
                                }
                            } else if (type.getName().equals("java.util.List")) {
                                List<String> newValues = new ArrayList<String>();
                                String length = id + "_length";
                                if (!parms.isEmpty() && parms.containsKey(length)) {
                                    String tmp = parms.get(length).toString();
                                    int count = Integer.valueOf(tmp);
                                    for (int i = 0; i < count; i++) {
                                        String tmpValue = parms.get(String.format("%s[%d]", id, i));
                                        newValues.add(tmpValue);
                                    }
                                    if (!newValues.isEmpty()) {
                                        Object o = setter.invoke(instance, newValues);
                                    }
                                }
                                set.remove(id);
                            } else {
                                setters.put(id, setter);
                            }
                        } catch (Exception exc) {

                        }

                        Method getter = null;
                        try {
                            getter = resourceClass.getMethod("get" + StringUtils.capitalize(value));
                            if (!type.getName().equals("java.lang.String")) {
                                getters.put(id, getter);
                            }
                        } catch (Exception exc) {

                        }

                    }
                    subResources.addAll(Arrays.asList(values));
                }
            }
        }

        // remove getters that have matching setter
        for (String setKey : setters.keySet()) {
            if (getters.containsKey(setKey)) {
                getters.remove(setKey);
            }
        }

        Set<String> relationshipKeys = new TreeSet<String>();
        Set<String> vlansKeys = new TreeSet<String>();
        Set<String> metadataKeys = new TreeSet<String>();

        for (String attribute : set) {
            String value = parms.get(attribute);
            if (attribute.startsWith("relationship-list")) {
                relationshipKeys.add(attribute);
            } else if (attribute.startsWith("vlans")) {
                vlansKeys.add(attribute);
            } else if (attribute.startsWith("metadata")) {
                metadataKeys.add(attribute);
            }
        }
        // 3. find list property getters
        for (String attribute : set) {
            String value = parms.get(attribute);
            Method method = getters.get(attribute);
            if (method != null) {
                try {
                    method.setAccessible(true);
                    Object arglist[] = new Object[0];
                    //                  arglist[0] = value;
                    Class<?>[] types = method.getParameterTypes();
                    if (types.length == 0) {
                        Object o = method.invoke(instance, arglist);
                        if (o instanceof ArrayList) {
                            ArrayList<String> values = (ArrayList<String>) o;
                            //                        getLogger().debug(String.format("Processing %s with parameter %s", types[0].getName(), value));
                            value = value.replace("[", "").replace("]", "");
                            List<String> items = Arrays.asList(value.split("\\s*,\\s*"));
                            for (String s : items) {
                                values.add(s.trim());
                            }
                        }
                    }
                } catch (Exception x) {
                    Throwable cause = x.getCause();
                    getLogger().warn("Failed process for " + resourceClass.getName(), x);
                }
            }
        }
        // 4. Process Relationships
        // add relationship list
        if ((subResources.contains("relationship-list") || subResources.contains("relationshipList"))
                && !relationshipKeys.isEmpty()) {
            RelationshipList relationshipList = null;
            Object obj = null;
            Method getRelationshipListMethod = resourceClass.getMethod("getRelationshipList");
            if (getRelationshipListMethod != null) {
                try {
                    getRelationshipListMethod.setAccessible(true);
                    obj = getRelationshipListMethod.invoke(instance);
                } catch (InvocationTargetException x) {
                    Throwable cause = x.getCause();
                }
            }
            if (obj != null && obj instanceof RelationshipList) {
                relationshipList = (RelationshipList) obj;
            } else {
                relationshipList = new RelationshipList();
                Method setRelationshipListMethod = resourceClass.getMethod("setRelationshipList",
                        RelationshipList.class);
                if (setRelationshipListMethod != null) {
                    try {
                        setRelationshipListMethod.setAccessible(true);
                        Object arglist[] = new Object[1];
                        arglist[0] = relationshipList;

                        obj = setRelationshipListMethod.invoke(instance, arglist);
                    } catch (InvocationTargetException x) {
                        Throwable cause = x.getCause();
                    }
                }
            }

            List<Relationship> relationships = relationshipList.getRelationship();

            int i = 0;
            while (true) {
                int j = 0;
                String searchKey = "relationship-list.relationship[" + i + "].related-to";
                if (!parms.containsKey(searchKey))
                    break;
                Relationship relationship = new Relationship();
                relationships.add(relationship);

                String relatedTo = parms.get(searchKey);
                relationship.setRelatedTo(relatedTo);

                List<RelationshipData> relData = relationship.getRelationshipData();
                //               if(relData == null) {
                //                  relData = new LinkedList<RelationshipData>();
                //                  relationship.setRelationshipData(relData);
                //               }

                while (true) {
                    String searchRelationshipKey = "relationship-list.relationship[" + i
                            + "].relationship-data[" + j + "].relationship-key";
                    String searchRelationshipValue = "relationship-list.relationship[" + i
                            + "].relationship-data[" + j + "].relationship-value";
                    if (!parms.containsKey(searchRelationshipKey))
                        break;

                    RelationshipData relDatum = new RelationshipData();
                    relDatum.setRelationshipKey(parms.get(searchRelationshipKey));
                    relDatum.setRelationshipValue(parms.get(searchRelationshipValue));
                    relData.add(relDatum);
                    j++;
                }

                i++;
            }
        }

        // 4. vlans
        if (subResources.contains("vlans") && !vlansKeys.isEmpty()) {
            Object obj = null;
            Vlans vlanList = null;
            Method getVLansMethod = resourceClass.getMethod("getVlans");
            if (getVLansMethod != null) {
                try {
                    getVLansMethod.setAccessible(true);
                    obj = getVLansMethod.invoke(instance);
                } catch (InvocationTargetException x) {
                    Throwable cause = x.getCause();
                }
            }
            if (obj != null && obj instanceof Vlans) {
                vlanList = (Vlans) obj;
            } else {
                vlanList = new Vlans();
                Method setVlansMethod = resourceClass.getMethod("setVlans", Vlans.class);
                if (setVlansMethod != null) {
                    try {
                        setVlansMethod.setAccessible(true);
                        Object arglist[] = new Object[1];
                        arglist[0] = vlanList;

                        obj = setVlansMethod.invoke(instance, arglist);
                    } catch (InvocationTargetException x) {
                        Throwable cause = x.getCause();
                    }
                }
            }

            int i = 0;
            while (true) {
                String searchKey = "vlans.vlan[" + i + "].vlan-interface";
                if (!parms.containsKey(searchKey))
                    break;

                String vlanInterface = parms.get("vlans.vlan[" + i + "].vlan-interface");
                String vlanIdInner = parms.get("vlans.vlan[" + i + "].vlan-id-inner");
                String vlanIdOute = parms.get("vlans.vlan[" + i + "].vlan-id-outer");
                String speedValue = parms.get("vlans.vlan[" + i + "].speed-value");
                String speedUnits = parms.get("vlans.vlan[" + i + "].speed-units");

                Vlan vlan = new Vlan();
                vlan.setVlanInterface(vlanInterface);

                if (vlanIdInner != null) {
                    Long iVlanIdInner = Long.parseLong(vlanIdInner);
                    vlan.setVlanIdInner(iVlanIdInner);
                }

                if (vlanIdOute != null) {
                    Long iVlanIdOuter = Long.parseLong(vlanIdOute);
                    vlan.setVlanIdOuter(iVlanIdOuter);
                }

                if (speedValue != null) {
                    vlan.setSpeedValue(speedValue);
                    vlan.setSpeedUnits(speedUnits);
                }

                vlanList.getVlan().add(vlan);
                i++;
            }
        }

        // 5. metadata
        if (subResources.contains("metadata") && !metadataKeys.isEmpty()) {
            Object obj = null;
            Metadata metadataList = null;
            Method getMetadataMethod = resourceClass.getMethod("getMetadata");
            if (getMetadataMethod != null) {
                try {
                    getMetadataMethod.setAccessible(true);
                    obj = getMetadataMethod.invoke(instance);
                } catch (InvocationTargetException x) {
                    Throwable cause = x.getCause();
                }
            }
            if (obj != null && obj instanceof Metadata) {
                metadataList = (Metadata) obj;
            } else {
                metadataList = new Metadata();
                Method setMetadataMethod = resourceClass.getMethod("setMetadata", Metadata.class);
                if (setMetadataMethod != null) {
                    try {
                        setMetadataMethod.setAccessible(true);
                        Object arglist[] = new Object[1];
                        arglist[0] = metadataList;

                        obj = setMetadataMethod.invoke(instance, arglist);
                    } catch (InvocationTargetException x) {
                        Throwable cause = x.getCause();
                    }
                }
            }

            if (metadataList.getMetadatum() == null) {
                //               metadataList.setMetadatum(new ArrayList<Metadatum>());
            }

            // process data
            int i = 0;
            while (true) {
                String metaKey = "metadata.metadatum[" + i + "].meta-key";
                if (!parms.containsKey(metaKey))
                    break;

                String metaValue = parms.get("metadata.metadatum[" + i + "].meta-value");

                Metadatum vlan = new Metadatum();
                vlan.setMetaname(metaKey);
                vlan.setMetaval(metaValue);

                metadataList.getMetadatum().add(vlan);
                i++;
            }

        }

        // 6. Prepare AAI request
        String[] args = request.getArgsList();
        for (String arg : args) {
            String modifiedKey = arg.replaceAll("-", "_");
            if (nameValues.containsKey(modifiedKey)) {
                String argValue = nameValues.get(modifiedKey);
                if (argValue != null)
                    argValue = argValue.trim().replace("'", "").replace("$", "").replace("'", "");
                request.addRequestProperty(arg, argValue);
            }
        }

        request.processRequestPathValues(nameValues);
        request.setRequestObject(instance);
        Object response = getExecutor().post(request);
        if (request.expectsDataFromPUTRequest()) {
            if (response != null && response instanceof String) {
                String rv = response.toString();
                QueryStatus retval = processResponseData(rv, resource, request, prefix, ctx, nameValues, null);
                getLogger().debug("newModelSave - returning " + retval.toString());
                return retval;
            }
        }

    } catch (AAIServiceException exc) {
        ctx.setAttribute(prefix + ".error.message", exc.getMessage());
        int returnCode = exc.getReturnCode();
        if (returnCode >= 300) {
            ctx.setAttribute(prefix + ".error.http.response-code", "" + exc.getReturnCode());
        }

        if (returnCode == 400 || returnCode == 412)
            return QueryStatus.FAILURE;
        else if (returnCode == 404)
            return QueryStatus.NOT_FOUND;
        else {
            getLogger().warn("Failed newModelSave - returning FAILURE", exc);
            return QueryStatus.FAILURE;
        }
    } catch (Exception exc) {
        getLogger().warn("Failed newModelSave - returning FAILURE", exc);
        ctx.setAttribute(prefix + ".error.message", exc.getMessage());
        return QueryStatus.FAILURE;
    }

    getLogger().debug("newModelSave - returning SUCCESS");
    return QueryStatus.SUCCESS;
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("unchecked")
private List<ParameterInfo> createAndDisplayAParameterPanel(
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title,
        final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify,
        final IModelHandler currentModelHandler) {
    final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(),
            unknownFields = new ArrayList<ParameterMetaData>();
    for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) {
        final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName);
        Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        while (true) {
            try {
                final Field field = modelComponentType.getDeclaredField(fieldName);
                final ParameterMetaData datum = new ParameterMetaData();
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                        continue;
                    final Class<? extends Annotation> type = element.annotationType();
                    datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element);
                    datum.banner = (String) type.getMethod("Title").invoke(element);
                    datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element);
                    datum.imageFileName = (String) type.getMethod("Image").invoke(element);
                    datum.layoutOrder = (Double) type.getMethod("Order").invoke(element);
                }/*  w  ww . j  ava 2s .c om*/
                datum.parameter = record;
                if (datum.fieldName.trim().isEmpty())
                    datum.fieldName = parameterName.replaceAll("([A-Z])", " $1");
                metadata.add(datum);
                break;
            } catch (final SecurityException e) {
            } catch (final NoSuchFieldException e) {
            } catch (final IllegalArgumentException e) {
            } catch (final IllegalAccessException e) {
            } catch (final InvocationTargetException e) {
            } catch (final NoSuchMethodException e) {
            }
            modelComponentType = modelComponentType.getSuperclass();
            if (modelComponentType == null) {
                ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields);
                break;
            }
        }
    }
    Collections.sort(metadata);
    for (int i = unknownFields.size() - 1; i >= 0; --i)
        metadata.add(0, unknownFields.get(i));

    // initialize single run form
    final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", "");
    appendMinimumWidthHintToPresentation(formBuilder, 550);

    if (parent == null) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                numberOfTurnsField.grabFocus();
            }
        });

        appendBannerToPresentation(formBuilder, "General Parameters");
        appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation");

        formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField);
        formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored);

        appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox);
        appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT,
                advancedChartsCheckBox);
    }

    appendBannerToPresentation(formBuilder, title);

    final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree
            : findParameterInfoNode(parent, false);

    final List<ParameterInfo> info = new ArrayList<ParameterInfo>();

    // Search for a @ConfigurationComponent annotation
    {
        String headerText = "", imagePath = "";
        final Class<?> parentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        for (final Annotation element : parentType.getAnnotations()) { // Proxies
            if (element.annotationType().getName() != ConfigurationComponent.class.getName())
                continue;
            boolean doBreak = false;
            try {
                try {
                    headerText = (String) element.annotationType().getMethod("Description").invoke(element);
                    if (headerText.startsWith("#")) {
                        headerText = (String) parent.getActualType().getMethod(headerText.substring(1))
                                .invoke(parent.getInstance());
                    }
                    doBreak = true;
                } catch (IllegalArgumentException e) {
                } catch (SecurityException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } catch (final Exception e) {
            }
            try {
                imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element);
                doBreak = true;
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
            if (doBreak)
                break;
        }
        if (!headerText.isEmpty())
            appendHeaderTextToPresentation(formBuilder, headerText);
        if (!imagePath.isEmpty())
            appendImageToPresentation(formBuilder, imagePath);
    }

    if (metadata.isEmpty()) {
        // No fields to display.
        appendTextToPresentation(formBuilder, "No configuration is required for this module.");
    } else {
        for (final ParameterMetaData record : metadata) {
            final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter;

            if (!record.banner.isEmpty())
                appendBannerToPresentation(formBuilder, record.banner);
            if (!record.imageFileName.isEmpty())
                appendImageToPresentation(formBuilder, record.imageFileName);
            appendTextToPresentation(formBuilder, record.verboseDescription);

            final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo);
            if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) {
                //               sgi.setParentValue(parent.getActualType());
            }

            final JComponent field;
            final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true);
            Pair<ParameterInfo, JComponent> userData = null;
            JComponent oldField = null;
            if (oldNode != null) {
                userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject();
                oldField = userData.getSecond();
            }

            if (parameterInfo.isBoolean()) {
                field = new JCheckBox();
                boolean value = oldField != null ? ((JCheckBox) oldField).isSelected()
                        : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue();
                ((JCheckBox) field).setSelected(value);
            } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) {
                Object[] elements = null;
                if (parameterInfo.isEnum()) {
                    final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType();
                    elements = type.getEnumConstants();
                } else {
                    final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo;
                    elements = chooserInfo.getValidStrings();
                }
                final JComboBox list = new JComboBox(elements);

                if (parameterInfo.isEnum()) {
                    final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem()
                            : parameterInfo.getValue();
                    list.setSelectedItem(value);
                } else {
                    final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex()
                            : (Integer) parameterInfo.getValue();
                    list.setSelectedIndex(value);
                }

                field = list;
            } else if (parameterInfo instanceof SubmodelInfo) {
                final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                final Object[] elements = new Object[] { "Loading class information..." };
                final JComboBox list = new JComboBox(elements);
                //            field = list;

                final Object value = oldField != null
                        ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem()
                        : new ClassElement(submodelInfo.getActualType(), null);

                new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute();

                final JButton rightButton = new JButton();
                rightButton.setOpaque(false);
                rightButton.setRolloverEnabled(true);
                rightButton.setIcon(SHOW_SUBMODEL_ICON);
                rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO);
                rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS);
                rightButton.setBorder(null);
                rightButton.setToolTipText("Display submodel parameters");
                rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL);
                rightButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        if (parameterInfo instanceof SubmodelInfo) {
                            SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                            int level = 0;

                            showHideSubparameters(list, submodelInfo);

                            List<String> components = new ArrayList<String>();
                            components.add(submodelInfo.getName());
                            while (submodelInfo.getParent() != null) {
                                submodelInfo = submodelInfo.getParent();
                                components.add(submodelInfo.getName());
                                level++;
                            }
                            Collections.reverse(components);
                            final String[] breadcrumbText = components.toArray(new String[components.size()]);
                            for (int i = 0; i < breadcrumbText.length; ++i)
                                breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1");
                            breadcrumb.setPath(
                                    currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"),
                                    breadcrumbText);
                            Style.apply(breadcrumb, dashboard.getCssStyle());

                            // reset all buttons that are nested deeper than this to default color
                            for (int i = submodelButtons.size() - 1; i >= level; i--) {
                                JButton button = submodelButtons.get(i);
                                button.setIcon(SHOW_SUBMODEL_ICON);
                                submodelButtons.remove(i);
                            }

                            rightButton.setIcon(SHOW_SUBMODEL_ICON_RO);
                            submodelButtons.add(rightButton);
                        }
                    }
                });

                field = new JPanel(new BorderLayout());
                field.add(list, BorderLayout.CENTER);
                field.add(rightButton, BorderLayout.EAST);
            } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) {
                field = new JPanel(new BorderLayout());

                String oldName = "";
                String oldPath = "";
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldName = oldTextField.getText();
                    oldPath = oldTextField.getToolTipText();
                } else if (parameterInfo.getValue() != null) {
                    final File file = (File) parameterInfo.getValue();
                    oldName = file.getName();
                    oldPath = file.getAbsolutePath();
                }

                final JTextField textField = new JTextField(oldName);
                textField.setToolTipText(oldPath);
                textField.setInputVerifier(new InputVerifier() {

                    @Override
                    public boolean verify(final JComponent input) {
                        final JTextField inputField = (JTextField) input;
                        if (inputField.getText() == null || inputField.getText().isEmpty()) {
                            final File file = new File("");
                            inputField.setToolTipText(file.getAbsolutePath());
                            hideError();
                            return true;
                        }

                        final File oldFile = new File(inputField.getToolTipText());
                        if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) {
                            hideError();
                            return true;
                        }

                        inputField.setToolTipText("");
                        final File file = new File(inputField.getText().trim());
                        if (file.exists()) {
                            inputField.setToolTipText(file.getAbsolutePath());
                            inputField.setText(file.getName());
                            hideError();
                            return true;
                        } else {
                            final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                            final Point locationOnScreen = inputField.getLocationOnScreen();
                            final JLabel message = new JLabel("Please specify an existing file!");
                            message.setBorder(new LineBorder(Color.RED, 2, true));
                            if (errorPopup != null)
                                errorPopup.hide();
                            errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10,
                                    locationOnScreen.y - 30);
                            errorPopup.show();
                            return false;
                        }
                    }
                });

                final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT);
                browseButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JFileChooser fileDialog = new JFileChooser(
                                !"".equals(textField.getToolTipText()) ? textField.getToolTipText()
                                        : currentDirectory);
                        if (!"".equals(textField.getToolTipText()))
                            fileDialog.setSelectedFile(new File(textField.getToolTipText()));
                        int dialogResult = fileDialog.showOpenDialog(dashboard);
                        if (dialogResult == JFileChooser.APPROVE_OPTION) {
                            final File selectedFile = fileDialog.getSelectedFile();
                            if (selectedFile != null) {
                                currentDirectory = selectedFile.getAbsoluteFile().getParent();
                                textField.setText(selectedFile.getName());
                                textField.setToolTipText(selectedFile.getAbsolutePath());
                            }
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(browseButton, BorderLayout.EAST);
            } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo;

                field = new JPanel(new BorderLayout());

                String oldValueStr = String.valueOf(parameterInfo.getValue());
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldValueStr = oldTextField.getText();
                }

                final JTextField textField = new JTextField(oldValueStr);

                PercentJSlider tempSlider = null;
                if (intervalInfo.isDoubleInterval())
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(),
                            intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr));
                else
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(),
                            intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr));

                final PercentJSlider slider = tempSlider;
                slider.setMajorTickSpacing(100);
                slider.setMinorTickSpacing(10);
                slider.setPaintTicks(true);
                slider.setPaintLabels(true);
                slider.addChangeListener(new ChangeListener() {
                    public void stateChanged(final ChangeEvent _) {
                        if (slider.hasFocus()) {
                            final String value = intervalInfo.isDoubleInterval()
                                    ? String.valueOf(slider.getDoubleValue())
                                    : String.valueOf(slider.getLongValue());
                            textField.setText(value);
                            slider.setToolTipText(value);
                        }
                    }
                });

                textField.setInputVerifier(new InputVerifier() {
                    public boolean verify(JComponent input) {
                        final JTextField inputField = (JTextField) input;

                        try {
                            hideError();
                            final String valueStr = inputField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else
                                    showError(
                                            "Please specify a value between " + intervalInfo.getIntervalMin()
                                                    + " and " + intervalInfo.getIntervalMax() + ".",
                                            inputField);
                                return false;
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else {
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", inputField);
                                    return false;
                                }
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, inputField);
                            return false;
                        }

                    }
                });

                textField.getDocument().addDocumentListener(new DocumentListener() {
                    //               private Popup errorPopup;

                    public void removeUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void insertUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void changedUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    private void textFieldChanged() {
                        if (!textField.hasFocus()) {
                            hideError();
                            return;
                        }

                        try {
                            hideError();
                            final String valueStr = textField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify a value between " + intervalInfo.getIntervalMin()
                                            + " and " + intervalInfo.getIntervalMax() + ".", textField);
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", textField);
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, textField);
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(slider, BorderLayout.SOUTH);
            } else {
                final Object value = oldField != null ? ((JTextField) oldField).getText()
                        : parameterInfo.getValue();
                field = new JTextField(value.toString());
                ((JTextField) field).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        wizard.clickDefaultButton();
                    }
                });
            }

            final JLabel parameterLabel = new JLabel(record.fieldName);

            final String description = parameterInfo.getDescription();
            if (description != null && !description.isEmpty()) {
                parameterLabel.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance();

                        final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel,
                                description, dashboard.getCssStyle());

                        parameterDescriptionPopup.show();
                    }

                });
            }

            if (oldNode != null)
                userData.setSecond(field);
            else {
                final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo,
                        field);
                final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair);
                parentNode.add(newNode);
            }

            if (field instanceof JCheckBox) {
                parameterLabel
                        .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">"
                                + parameterLabel.getText() + "</div></html>");
                formBuilder.append(parameterLabel, field);

                //            appendCheckBoxFieldToPresentation(
                //               formBuilder, parameterLabel.getText(), (JCheckBox) field);
            } else {
                formBuilder.append(parameterLabel, field);
                final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel);
                constraints.vAlign = CellConstraints.TOP;
                constraints.insets = new Insets(5, 0, 0, 0);
                formBuilder.getLayout().setConstraints(parameterLabel, constraints);
            }

            // prepare the parameterInfo for the param sweeps
            parameterInfo.setRuns(0);
            parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF);
            parameterInfo.setValue(batchParameterInfo.getDefaultValue());
            info.add(parameterInfo);
        }
    }
    appendVerticalSpaceToPresentation(formBuilder);

    final JPanel panel = formBuilder.getPanel();
    singleRunParametersPanel.add(panel);

    if (singleRunParametersPanel.getComponentCount() > 1) {
        panel.setBorder(
                BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
                        BorderFactory.createEmptyBorder(0, 5, 0, 5)));
    } else {
        panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    }

    Style.apply(panel, dashboard.getCssStyle());

    return info;
}

From source file:org.apache.bval.jsr.AnnotationConstraintBuilder.java

/** build attributes, payload, groups from 'annotation' */
@Privileged/*from w  w  w  .  j  av  a2  s. c  o m*/
private void buildFromAnnotation() {
    if (constraintValidation.getAnnotation() == null) {
        return;
    }
    final Class<? extends Annotation> annotationType = constraintValidation.getAnnotation().annotationType();

    boolean foundPayload = false;
    boolean foundGroups = false;
    Method validationAppliesTo = null;
    boolean foundMessage = false;

    for (final Method method : AnnotationProxyBuilder.findMethods(annotationType)) {
        // groups + payload must also appear in attributes (also
        // checked by TCK-Tests)
        if (method.getParameterTypes().length == 0) {
            try {
                final String name = method.getName();
                if (ConstraintAnnotationAttributes.PAYLOAD.getAttributeName().equals(name)) {
                    buildPayload(method);
                    foundPayload = true;
                } else if (ConstraintAnnotationAttributes.GROUPS.getAttributeName().equals(name)) {
                    buildGroups(method);
                    foundGroups = true;
                } else if (ConstraintAnnotationAttributes.VALIDATION_APPLIES_TO.getAttributeName()
                        .equals(name)) {
                    buildValidationAppliesTo(method);
                    validationAppliesTo = method;
                } else if (name.startsWith("valid")) {
                    throw new ConstraintDefinitionException(
                            "constraints parameters can't start with valid: " + name);
                } else {
                    if (ConstraintAnnotationAttributes.MESSAGE.getAttributeName().equals(name)) {
                        foundMessage = true;
                        if (!TypeUtils.isAssignable(method.getReturnType(),
                                ConstraintAnnotationAttributes.MESSAGE.getType())) {
                            throw new ConstraintDefinitionException("Return type for message() must be of type "
                                    + ConstraintAnnotationAttributes.MESSAGE.getType());
                        }
                    }
                    constraintValidation.getAttributes().put(name,
                            method.invoke(constraintValidation.getAnnotation()));
                }
            } catch (final ConstraintDefinitionException cde) {
                throw cde;
            } catch (final Exception e) { // do nothing
                log.log(Level.WARNING,
                        String.format("Error processing annotation: %s ", constraintValidation.getAnnotation()),
                        e);
            }
        }
    }

    if (!foundMessage) {
        throw new ConstraintDefinitionException(
                "Annotation " + annotationType.getName() + " has no message method");
    }
    if (!foundPayload) {
        throw new ConstraintDefinitionException(
                "Annotation " + annotationType.getName() + " has no payload method");
    }
    if (!foundGroups) {
        throw new ConstraintDefinitionException(
                "Annotation " + annotationType.getName() + " has no groups method");
    }
    if (validationAppliesTo != null
            && !ConstraintTarget.IMPLICIT.equals(validationAppliesTo.getDefaultValue())) {
        throw new ConstraintDefinitionException("validationAppliesTo default value should be IMPLICIT");
    }

    // valid validationAppliesTo
    final Constraint annotation = annotationType.getAnnotation(Constraint.class);
    if (annotation == null) {
        return;
    }

    final Pair validationTarget = computeValidationTarget(annotation.validatedBy());
    for (final Annotation a : annotationType.getAnnotations()) {
        final Class<? extends Annotation> aClass = a.annotationType();
        if (aClass.getName().startsWith("java.lang.annotation.")) {
            continue;
        }

        final Constraint inheritedConstraint = aClass.getAnnotation(Constraint.class);
        if (inheritedConstraint != null && !aClass.getName().startsWith("javax.validation.constraints.")) {
            final Pair validationTargetInherited = computeValidationTarget(inheritedConstraint.validatedBy());
            if ((validationTarget.a > 0 && validationTargetInherited.b > 0 && validationTarget.b == 0)
                    || (validationTarget.b > 0 && validationTargetInherited.a > 0 && validationTarget.a == 0)) {
                throw new ConstraintDefinitionException("Parent and child constraint have different targets");
            }
        }
    }
}

From source file:ca.oson.json.Oson.java

<T> T newInstance(Map<String, Object> map, Class<T> valueType) {
    InstanceCreator creator = getTypeAdapter(valueType);

    if (creator != null) {
        return (T) creator.createInstance(valueType);
    }//from w w w .  j  av a 2 s  .  c om

    T obj = null;

    if (valueType != null) {
        obj = (T) getDefaultValue(valueType);
        if (obj != null) {
            return obj;
        }
    }

    if (map == null) {
        return null;
    }

    // @JsonTypeInfo(use = JsonTypeInfo.Id.MINIMAL_CLASS, include = As.PROPERTY, property = "@class")
    //@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "@class")
    String JsonClassType = null;

    if (valueType != null) {
        if (getAnnotationSupport()) {
            for (Annotation annotation : valueType.getAnnotations()) {
                if (annotation instanceof JsonTypeInfo) {
                    JsonTypeInfo jsonTypeInfo = (JsonTypeInfo) annotation;
                    JsonTypeInfo.Id use = jsonTypeInfo.use();
                    JsonTypeInfo.As as = jsonTypeInfo.include();
                    if ((use == JsonTypeInfo.Id.MINIMAL_CLASS || use == JsonTypeInfo.Id.CLASS)
                            && as == As.PROPERTY) {
                        JsonClassType = jsonTypeInfo.property();
                    }
                }
            }
        }
    }
    if (JsonClassType == null) {
        JsonClassType = getJsonClassType();
    }

    String className = null;
    if (map.containsKey(JsonClassType)) {
        className = map.get(JsonClassType).toString();
    }

    Class<T> classType = getClassType(className);

    //  && (valueType == null || valueType.isAssignableFrom(classType) || Map.class.isAssignableFrom(valueType))
    if (classType != null) {
        valueType = classType;
    }

    if (valueType == null) {
        return (T) map; // or null, which is better?
    }

    Constructor<?>[] constructors = null;

    Class implClass = null;
    if (valueType.isInterface() || Modifier.isAbstract(valueType.getModifiers())) {
        implClass = DeSerializerUtil.implementingClass(valueType.getName());
    }

    if (implClass != null) {
        constructors = implClass.getDeclaredConstructors();
    } else {
        constructors = valueType.getDeclaredConstructors();//.getConstructors();
    }

    Object singleMapValue = null;
    Class singleMapValueType = null;
    if (map.size() == 1) {
        singleMapValue = map.get(valueType.getName());

        if (singleMapValue != null) {
            singleMapValueType = singleMapValue.getClass();

            if (singleMapValueType == String.class) {
                singleMapValue = StringUtil.unquote(singleMapValue.toString(), isEscapeHtml());
            }

            try {
                if (valueType == Locale.class) {
                    Constructor constructor = null;
                    String[] parts = ((String) singleMapValue).split("_");
                    if (parts.length == 1) {
                        constructor = valueType.getConstructor(String.class);
                        constructor.setAccessible(true);
                        obj = (T) constructor.newInstance(singleMapValue);
                    } else if (parts.length == 2) {
                        constructor = valueType.getConstructor(String.class, String.class);
                        constructor.setAccessible(true);
                        obj = (T) constructor.newInstance(parts);
                    } else if (parts.length == 3) {
                        constructor = valueType.getConstructor(String.class, String.class, String.class);
                        constructor.setAccessible(true);
                        obj = (T) constructor.newInstance(parts);
                    }

                    if (obj != null) {
                        return obj;
                    }
                }
            } catch (Exception e) {
            }

            Map<Class, Constructor> cmaps = new HashMap<>();
            for (Constructor constructor : constructors) {
                //Class[] parameterTypes = constructor.getParameterTypes();

                int parameterCount = constructor.getParameterCount();
                if (parameterCount == 1) {

                    Class[] types = constructor.getParameterTypes();

                    cmaps.put(types[0], constructor);
                }
            }

            if (cmaps.size() > 0) {
                Constructor constructor = null;

                if ((cmaps.containsKey(Boolean.class) || cmaps.containsKey(boolean.class))
                        && BooleanUtil.isBoolean(singleMapValue.toString())) {
                    constructor = cmaps.get(Boolean.class);
                    if (constructor == null) {
                        constructor = cmaps.get(boolean.class);
                    }
                    if (constructor != null) {
                        try {
                            constructor.setAccessible(true);
                            obj = (T) constructor
                                    .newInstance(BooleanUtil.string2Boolean(singleMapValue.toString()));

                            if (obj != null) {
                                return obj;
                            }
                        } catch (Exception e) {
                        }
                    }

                } else if (StringUtil.isNumeric(singleMapValue.toString())) {

                    Class[] classes = new Class[] { int.class, Integer.class, long.class, Long.class,
                            double.class, Double.class, Byte.class, byte.class, Short.class, short.class,
                            Float.class, float.class, BigDecimal.class, BigInteger.class, AtomicInteger.class,
                            AtomicLong.class, Number.class };

                    for (Class cls : classes) {
                        constructor = cmaps.get(cls);

                        if (constructor != null) {
                            try {
                                obj = (T) constructor.newInstance(NumberUtil.getNumber(singleMapValue, cls));

                                if (obj != null) {
                                    return obj;
                                }
                            } catch (Exception e) {
                            }
                        }
                    }

                } else if (StringUtil.isArrayOrList(singleMapValue.toString())
                        || singleMapValue.getClass().isArray()
                        || Collection.class.isAssignableFrom(singleMapValue.getClass())) {
                    for (Entry<Class, Constructor> entry : cmaps.entrySet()) {
                        Class cls = entry.getKey();
                        constructor = entry.getValue();

                        if (cls.isArray() || Collection.class.isAssignableFrom(cls)) {
                            Object listObject = null;
                            if (singleMapValue instanceof String) {
                                JSONArray objArray = new JSONArray(singleMapValue.toString());
                                listObject = (List) fromJsonMap(objArray);
                            } else {
                                listObject = singleMapValue;
                            }

                            FieldData objectDTO = new FieldData(listObject, cls, true);
                            listObject = json2Object(objectDTO);
                            if (listObject != null) {
                                try {
                                    obj = (T) constructor.newInstance(listObject);
                                    if (obj != null) {
                                        return obj;
                                    }
                                } catch (Exception e) {
                                }
                            }
                        }

                    }

                }

                for (Entry<Class, Constructor> entry : cmaps.entrySet()) {
                    Class cls = entry.getKey();
                    constructor = entry.getValue();
                    try {
                        obj = (T) constructor.newInstance(singleMapValue);
                        if (obj != null) {
                            return obj;
                        }
                    } catch (Exception e) {
                    }
                }

            }

        }
    }

    if (implClass != null) {
        valueType = implClass;
    }

    try {
        obj = valueType.newInstance();

        if (obj != null) {
            return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
        }

    } catch (InstantiationException | IllegalAccessException e) {
        //e.printStackTrace();
    }

    ///*
    for (Constructor constructor : constructors) {
        //Class[] parameterTypes = constructor.getParameterTypes();

        int parameterCount = constructor.getParameterCount();
        if (parameterCount > 0) {
            constructor.setAccessible(true);

            Annotation[] annotations = constructor.getDeclaredAnnotations(); // getAnnotations();

            for (Annotation annotation : annotations) {
                boolean isJsonCreator = false;
                if (annotation instanceof JsonCreator) {
                    isJsonCreator = true;
                } else if (annotation instanceof ca.oson.json.annotation.FieldMapper) {
                    ca.oson.json.annotation.FieldMapper fieldMapper = (ca.oson.json.annotation.FieldMapper) annotation;

                    if (fieldMapper.jsonCreator() == BOOLEAN.TRUE) {
                        isJsonCreator = true;
                    }
                }

                if (isJsonCreator) {
                    Parameter[] parameters = constructor.getParameters();
                    String[] parameterNames = ObjectUtil.getParameterNames(parameters);

                    //parameterCount = parameters.length;
                    Object[] parameterValues = new Object[parameterCount];
                    int i = 0;
                    for (String parameterName : parameterNames) {
                        parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                parameters[i].getType());
                        i++;
                    }

                    try {
                        obj = (T) constructor.newInstance(parameterValues);

                        if (obj != null) {
                            return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                        }

                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        //e.printStackTrace();
                    }
                }
            }

        } else {
            try {
                constructor.setAccessible(true);
                obj = (T) constructor.newInstance();

                if (obj != null) {
                    return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                }

            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                //e.printStackTrace();
            }

        }
    }
    //*/

    // try again
    for (Constructor constructor : constructors) {
        int parameterCount = constructor.getParameterCount();
        if (parameterCount > 0) {
            constructor.setAccessible(true);

            try {
                List<String> parameterNames = ObjectUtil.getParameterNames(constructor);

                if (parameterNames != null && parameterNames.size() > 0) {
                    Class[] parameterTypes = constructor.getParameterTypes();

                    int length = parameterTypes.length;
                    if (length == parameterNames.size()) {
                        Object[] parameterValues = new Object[length];
                        Object parameterValue;
                        for (int i = 0; i < length; i++) {
                            parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i),
                                    parameterTypes[i]);
                        }

                        try {
                            obj = (T) constructor.newInstance(parameterValues);
                            if (obj != null) {
                                return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                            }

                        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                                | InvocationTargetException e) {
                            //e.printStackTrace();
                        }

                    }
                }

            } catch (IOException e1) {
                // e1.printStackTrace();
            }
        }
    }

    // try more
    for (Constructor constructor : constructors) {
        int parameterCount = constructor.getParameterCount();
        if (parameterCount > 0) {
            constructor.setAccessible(true);

            Class[] parameterTypes = constructor.getParameterTypes();
            List<String> parameterNames;
            try {
                parameterNames = ObjectUtil.getParameterNames(constructor);

                if (parameterNames != null) {
                    int length = parameterTypes.length;

                    if (length > parameterNames.size()) {
                        length = parameterNames.size();
                    }

                    Object[] parameterValues = new Object[length];
                    for (int i = 0; i < length; i++) {
                        parameterValues[i] = getParameterValue(map, valueType, parameterNames.get(i),
                                parameterTypes[i]);
                    }

                    obj = (T) constructor.newInstance(parameterValues);
                    if (obj != null) {
                        return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                    }
                }

            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException | IOException e) {
                //e.printStackTrace();
            }
        }
    }

    // try more
    try {
        Method[] methods = valueType.getMethods(); // .getMethod("getInstance", null);

        List<Method> methodList = new ArrayList<>();

        if (methods != null) {
            for (Method method : methods) {
                String methodName = method.getName();

                if (methodName.equals("getInstance") || methodName.equals("newInstance")
                        || methodName.equals("createInstance") || methodName.equals("factory")) {
                    Class returnType = method.getReturnType();

                    if (valueType.isAssignableFrom(returnType) && Modifier.isStatic(method.getModifiers())) {
                        int parameterCount = method.getParameterCount();
                        if (parameterCount == 0) {
                            try {
                                obj = ObjectUtil.getMethodValue(null, method);
                                if (obj != null) {
                                    return setSingleMapValue(obj, valueType, singleMapValue,
                                            singleMapValueType);
                                }

                            } catch (IllegalArgumentException e) {
                                // TODO Auto-generated catch block
                                //e.printStackTrace();
                            }

                        } else {
                            methodList.add(method);
                        }

                    }
                }
            }

            for (Method method : methodList) {
                try {
                    int parameterCount = method.getParameterCount();
                    Object[] parameterValues = new Object[parameterCount];
                    Object parameterValue;
                    int i = 0;
                    Class[] parameterTypes = method.getParameterTypes();

                    String[] parameterNames = ObjectUtil.getParameterNames(method);

                    if (parameterCount == 1 && valueType != null && singleMapValue != null
                            && singleMapValueType != null) {

                        if (ObjectUtil.isSameDataType(parameterTypes[0], singleMapValueType)) {
                            try {
                                obj = ObjectUtil.getMethodValue(null, method, singleMapValue);
                                if (obj != null) {
                                    return obj;
                                }

                            } catch (IllegalArgumentException ex) {
                                //ex.printStackTrace();
                            }

                        }

                    } else if (parameterNames != null && parameterNames.length == parameterCount) {
                        for (String parameterName : ObjectUtil.getParameterNames(method)) {
                            parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                    parameterTypes[i]);
                            i++;
                        }

                    } else {
                        // try annotation
                        Parameter[] parameters = method.getParameters();
                        parameterNames = ObjectUtil.getParameterNames(parameters);
                        parameterCount = parameters.length;
                        parameterValues = new Object[parameterCount];
                        i = 0;
                        for (String parameterName : parameterNames) {
                            parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                    parameterTypes[i]);
                            i++;
                        }
                    }

                    obj = ObjectUtil.getMethodValue(null, method, parameterValues);

                    if (obj != null) {
                        return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                    }

                } catch (IOException | IllegalArgumentException e) {
                    //e.printStackTrace();
                }
            }

        }

    } catch (SecurityException e) {
        // e.printStackTrace();
    }

    // try all static methods, if the return type is correct, get it as the final object
    Method[] methods = valueType.getDeclaredMethods();
    for (Method method : methods) {
        if (Modifier.isStatic(method.getModifiers())) {
            Class returnType = method.getReturnType();

            if (valueType.isAssignableFrom(returnType)) {
                try {
                    Object[] parameterValues = null;

                    int parameterCount = method.getParameterCount();
                    if (parameterCount > 0) {
                        if (parameterCount == 1 && map.size() == 1 && singleMapValue != null
                                && singleMapValueType != null) {
                            if (ObjectUtil.isSameDataType(method.getParameterTypes()[0], singleMapValueType)) {
                                obj = ObjectUtil.getMethodValue(null, method, singleMapValueType);
                                if (obj != null) {
                                    return obj;
                                }
                            }
                        }

                        parameterValues = new Object[parameterCount];
                        Object parameterValue;
                        int i = 0;
                        Class[] parameterTypes = method.getParameterTypes();

                        String[] parameterNames = ObjectUtil.getParameterNames(method);
                        if (parameterNames != null && parameterNames.length == parameterCount) {
                            for (String parameterName : ObjectUtil.getParameterNames(method)) {
                                parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                        parameterTypes[i]);
                                i++;
                            }

                        } else {
                            // try annotation
                            Parameter[] parameters = method.getParameters();
                            parameterNames = ObjectUtil.getParameterNames(parameters);
                            parameterCount = parameters.length;
                            parameterValues = new Object[parameterCount];
                            i = 0;
                            for (String parameterName : parameterNames) {
                                parameterValues[i] = getParameterValue(map, valueType, parameterName,
                                        parameterTypes[i]);
                                i++;
                            }
                        }
                    }

                    obj = ObjectUtil.getMethodValue(obj, method, parameterValues);
                    if (obj != null) {
                        return setSingleMapValue(obj, valueType, singleMapValue, singleMapValueType);
                    }

                } catch (IOException | IllegalArgumentException e) {
                    //e.printStackTrace();
                }

            }
        }

    }

    return null;
}