Example usage for org.apache.commons.lang ClassUtils primitiveToWrapper

List of usage examples for org.apache.commons.lang ClassUtils primitiveToWrapper

Introduction

In this page you can find the example usage for org.apache.commons.lang ClassUtils primitiveToWrapper.

Prototype

public static Class<?> primitiveToWrapper(Class<?> cls) 

Source Link

Document

Converts the specified primitive Class object to its corresponding wrapper Class object.

NOTE: From v2.2, this method handles Void.TYPE, returning Void.TYPE.

Usage

From source file:com.bstek.dorado.data.entity.EntityUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T toEntity(Object object, DataType dataType) throws Exception {
    if (isSimpleValue(object)) {
        return (T) object;
    }//from  w w w  . j  a v  a 2  s . c  om

    // Expression
    if (object instanceof Expression) {
        object = ((Expression) object).evaluate();
    }

    Class<?> cl = object.getClass();
    if (object instanceof Collection) {
        Collection<?> entities = (Collection<?>) object;
        if (entities instanceof EntityCollection<?>) {
            DataType currentDataType = getDataType(entities);
            if (currentDataType != dataType && dataType != null) {
                ((EntityCollection<?>) entities).setDataType((AggregationDataType) dataType);
            }
            return (T) object;
        }
    } else {
        EntityEnhancer entityEnhancer = getEntityEnhancer(object);
        if (entityEnhancer != null) {
            DataType currentDataType = entityEnhancer.getDataType();
            if (currentDataType != dataType && dataType != null) {
                entityEnhancer.setDataType((EntityDataType) dataType);
            }
            return (T) object;
        }
    }

    boolean useProxy = true;
    if (dataType == null) {
        dataType = getDataType(cl);
    }

    if (dataType != null) {
        Class<?> matchType = dataType.getMatchType();
        if (matchType != null) {
            boolean matching = false;
            if (matchType.isPrimitive()) {
                matching = ClassUtils.primitiveToWrapper(matchType).equals(cl);
            } else {
                matching = matchType.isAssignableFrom(cl);
            }
            if (!matching) {
                if (dataType instanceof EntityDataType) {
                    DataType realDataType = getDataType(cl);
                    if (realDataType instanceof EntityDataType) {
                        matching = true;
                        useProxy = false;
                    }
                } else if (dataType instanceof AggregationDataType) {
                    DataType realDataType = getDataType(cl);
                    if (realDataType instanceof AggregationDataType) {
                        matching = true;
                    }
                }

                if (!matching) {
                    throw new IllegalArgumentException(
                            "Result type mismatch. expect [" + matchType + "] but [" + cl + "].");
                }
            }
        }
    }

    if (object instanceof Collection) {
        // Collection???
        AggregationDataType AggregationDataType = (AggregationDataType) dataType;
        if (object instanceof List) {
            object = new EntityList((List) object, AggregationDataType);
        } else if (object instanceof Set) {
            object = new EntitySet((Set) object, AggregationDataType);
        } else {
            throw new IllegalArgumentException("Unsupported result type [" + cl.getName() + "].");
        }
    } else if (object.getClass().isArray()) {
        Class type = object.getClass();
        if (isSimpleType(type.getComponentType())) {
            return (T) object;
        } else {
            // ??java.util.List
            logger.warn("Dorado converted a " + object.getClass() + " to " + List.class + " automatically.");

            List list = CollectionUtils.arrayToList(object);
            object = new EntityList(list, (AggregationDataType) dataType);
        }
    } else {
        // TODO Entity????
        // Entity???
        EntityDataType entityDataType = (EntityDataType) dataType;
        if (!(entityDataType instanceof CustomEntityDataType)) {
            if (useProxy) {
                // ????
                if (object instanceof EnhanceableEntity) {
                    EnhanceableEntity enhanceableEntity = (EnhanceableEntity) object;
                    if (enhanceableEntity.getEntityEnhancer() == null) {
                        EntityEnhancer entityEnhancer;
                        if (object instanceof Map) {
                            entityEnhancer = new EnhanceableMapEntityEnhancer(entityDataType);
                        } else {
                            entityEnhancer = new EnhanceableBeanEntityEnhancer(entityDataType,
                                    object.getClass());
                        }
                        enhanceableEntity.setEntityEnhancer(entityEnhancer);
                    }
                    return (T) object;
                } else {
                    MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(entityDataType,
                            object.getClass(), object);
                    object = ProxyBeanUtils.proxyBean(object, mis);
                }
            } else {
                // ????
                Class<?> creationType = entityDataType.getCreationType();
                if (creationType == null) {
                    creationType = entityDataType.getMatchType();
                }

                Map map;
                if (object instanceof Map) {
                    map = (Map) object;
                } else {
                    map = BeanMap.create(object);
                }

                if (creationType == null) {
                    Record record = new Record(map);
                    record.setEntityEnhancer(new EnhanceableMapEntityEnhancer(entityDataType));
                    object = record;
                } else {
                    MethodInterceptor[] mis = getMethodInterceptorFactory().createInterceptors(entityDataType,
                            creationType, null);
                    object = ProxyBeanUtils.createBean(creationType, mis);
                    setValues(object, map);
                }
            }
        } else {
            object = ((CustomEntityDataType) entityDataType).toMap(object);
        }
    }
    return (T) object;
}

From source file:com.agimatec.validation.jsr303.Jsr303MetaBeanFactory.java

/** implements spec chapter 3.5.3. ConstraintValidator resolution algorithm. */
private Type determineTargetedType(Class owner, AccessStrategy access) {
    // if the constraint declaration is hosted on a class or an interface,
    // the targeted type is the class or the interface.
    if (access == null)
        return owner;
    Type type = access.getJavaType();
    if (type == null)
        return Object.class;
    if (type instanceof Class)
        type = ClassUtils.primitiveToWrapper((Class) type);
    return type;/*ww  w.  j a  v a  2s.  c o m*/
}

From source file:com.evolveum.midpoint.web.component.prism.PrismValuePanel.java

private Panel createTypedInputComponent(String id) {
    //        ValueWrapper valueWrapper = model.getObject();
    //        ItemWrapper itemWrapper =
    final Item item = model.getObject().getItem().getItem();

    Panel panel = null;/*from   w w w .  j av  a2s.c  o m*/
    if (item instanceof PrismProperty) {
        final PrismProperty property = (PrismProperty) item;
        PrismPropertyDefinition definition = property.getDefinition();
        QName valueType = definition.getTypeName();

        final String baseExpression = "value.value"; //pointing to prism property real value

        //fixing MID-1230, will be improved with some kind of annotation or something like that
        //now it works only in description
        if (ObjectType.F_DESCRIPTION.equals(definition.getName())) {
            return new TextAreaPanel(id, new PropertyModel(model, baseExpression));
        }

        // the same for requester and approver comments in workflows [mederly] - this is really ugly, as it is specific to each approval form
        if (AssignmentCreationApprovalFormType.F_REQUESTER_COMMENT.equals(definition.getName())
                || AssignmentCreationApprovalFormType.F_COMMENT.equals(definition.getName())) {
            return new TextAreaPanel(id, new PropertyModel(model, baseExpression));
        }

        if (ActivationType.F_ADMINISTRATIVE_STATUS.equals(definition.getName())) {
            return WebMiscUtil.createEnumPanel(ActivationStatusType.class, id,
                    new PropertyModel<ActivationStatusType>(model, baseExpression), this);
        } else if (ActivationType.F_LOCKOUT_STATUS.equals(definition.getName())) {
            return WebMiscUtil.createEnumPanel(LockoutStatusType.class, id,
                    new PropertyModel<LockoutStatusType>(model, baseExpression), this);
        } else {
            // nothing to do
        }

        if (DOMUtil.XSD_DATETIME.equals(valueType)) {
            panel = new DatePanel(id, new PropertyModel<XMLGregorianCalendar>(model, baseExpression));

        } else if (ProtectedStringType.COMPLEX_TYPE.equals(valueType)) {
            panel = new PasswordPanel(id, new PropertyModel<ProtectedStringType>(model, baseExpression),
                    model.getObject().isReadonly());

        } else if (DOMUtil.XSD_BOOLEAN.equals(valueType)) {
            panel = new TriStateComboPanel(id, new PropertyModel<Boolean>(model, baseExpression));

        } else if (SchemaConstants.T_POLY_STRING_TYPE.equals(valueType)) {
            InputPanel inputPanel;
            PrismPropertyDefinition def = property.getDefinition();

            if (def.getValueEnumerationRef() != null) {
                PrismReferenceValue valueEnumerationRef = def.getValueEnumerationRef();
                String lookupTableUid = valueEnumerationRef.getOid();
                Task task = pageBase.createSimpleTask("loadLookupTable");
                OperationResult result = task.getResult();

                Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(
                        LookupTableType.F_ROW, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
                final PrismObject<LookupTableType> lookupTable = WebModelUtils.loadObject(LookupTableType.class,
                        lookupTableUid, options, pageBase, task, result);

                inputPanel = new AutoCompleteTextPanel<String>(id, new LookupPropertyModel<String>(model,
                        baseExpression + ".orig", lookupTable.asObjectable()), String.class) {

                    @Override
                    public Iterator<String> getIterator(String input) {
                        return prepareAutoCompleteList(input, lookupTable).iterator();
                    }
                };

            } else {

                inputPanel = new TextPanel<>(id, new PropertyModel<String>(model, baseExpression + ".orig"),
                        String.class);
            }

            if (ObjectType.F_NAME.equals(def.getName()) || UserType.F_FULL_NAME.equals(def.getName())) {
                inputPanel.getBaseFormComponent().setRequired(true);
            }
            panel = inputPanel;

        } else if (DOMUtil.XSD_BASE64BINARY.equals(valueType)) {
            panel = new UploadDownloadPanel(id, model.getObject().isReadonly()) {

                @Override
                public InputStream getStream() {
                    return new ByteArrayInputStream(
                            (byte[]) ((PrismPropertyValue) model.getObject().getValue()).getValue());
                    //                      return super.getStream();
                }

                @Override
                public void updateValue(byte[] file) {
                    ((PrismPropertyValue) model.getObject().getValue()).setValue(file);
                }

                @Override
                public void uploadFilePerformed(AjaxRequestTarget target) {
                    super.uploadFilePerformed(target);
                    target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                }

                @Override
                public void removeFilePerformed(AjaxRequestTarget target) {
                    super.removeFilePerformed(target);
                    target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                }

                @Override
                public void uploadFileFailed(AjaxRequestTarget target) {
                    super.uploadFileFailed(target);
                    target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                    target.add(((PageBase) getPage()).getFeedbackPanel());
                }
            };

        } else if (ObjectDeltaType.COMPLEX_TYPE.equals(valueType)) {
            panel = new ModificationsPanel(id, new AbstractReadOnlyModel<DeltaDto>() {
                @Override
                public DeltaDto getObject() {
                    if (model.getObject() == null || model.getObject().getValue() == null
                            || ((PrismPropertyValue) model.getObject().getValue()).getValue() == null) {
                        return null;
                    }
                    PrismContext prismContext = ((PageBase) getPage()).getPrismContext();
                    ObjectDeltaType objectDeltaType = (ObjectDeltaType) ((PrismPropertyValue) model.getObject()
                            .getValue()).getValue();
                    try {
                        ObjectDelta delta = DeltaConvertor.createObjectDelta(objectDeltaType, prismContext);
                        return new DeltaDto(delta);
                    } catch (SchemaException e) {
                        throw new IllegalStateException("Couldn't convert object delta: " + objectDeltaType);
                    }

                }
            });
        } else {
            Class type = XsdTypeMapper.getXsdToJavaMapping(valueType);
            if (type != null && type.isPrimitive()) {
                type = ClassUtils.primitiveToWrapper(type);

            }

            if (isEnum(property)) {
                return WebMiscUtil.createEnumPanel(definition, id, new PropertyModel<>(model, baseExpression),
                        this);
            }
            //                  // default QName validation is a bit weird, so let's treat QNames as strings [TODO finish this - at the parsing side]
            //                  if (type == QName.class) {
            //                      type = String.class;
            //                  }

            PrismPropertyDefinition def = property.getDefinition();

            if (def.getValueEnumerationRef() != null) {
                PrismReferenceValue valueEnumerationRef = def.getValueEnumerationRef();
                String lookupTableUid = valueEnumerationRef.getOid();
                Task task = pageBase.createSimpleTask("loadLookupTable");
                OperationResult result = task.getResult();

                Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(
                        LookupTableType.F_ROW, GetOperationOptions.createRetrieve(RetrieveOption.INCLUDE));
                final PrismObject<LookupTableType> lookupTable = WebModelUtils.loadObject(LookupTableType.class,
                        lookupTableUid, options, pageBase, task, result);

                panel = new AutoCompleteTextPanel<String>(id, new LookupPropertyModel<String>(model,
                        baseExpression, lookupTable == null ? null : lookupTable.asObjectable()), type) {

                    @Override
                    public Iterator<String> getIterator(String input) {
                        return prepareAutoCompleteList(input, lookupTable).iterator();
                    }

                    @Override
                    public void checkInputValue(AutoCompleteTextField input, AjaxRequestTarget target,
                            LookupPropertyModel model) {
                        Iterator<String> lookupTableValuesIterator = prepareAutoCompleteList("", lookupTable)
                                .iterator();

                        String value = input.getInput();
                        boolean isValueExist = false;
                        if (value != null) {
                            if (value.trim().equals("")) {
                                isValueExist = true;
                            } else {
                                while (lookupTableValuesIterator.hasNext()) {
                                    String lookupTableValue = lookupTableValuesIterator.next();
                                    if (value.trim().equals(lookupTableValue)) {
                                        isValueExist = true;
                                        break;
                                    }
                                }
                            }
                        }
                        if (isValueExist) {
                            input.setModelValue(new String[] { value });
                            target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                        } else {
                            input.error(
                                    "Entered value doesn't match any of available values and will not be saved.");
                            target.add(PrismValuePanel.this.get(ID_FEEDBACK));
                        }
                    }
                };

            } else {
                panel = new TextPanel<>(id, new PropertyModel<String>(model, baseExpression), type);
            }
        }
    } else if (item instanceof PrismReference) {
        //           ((PrismReferenceDefinition) item.getDefinition()).
        Class typeFromName = null;
        PrismContext prismContext = item.getPrismContext();
        if (prismContext == null) {
            prismContext = pageBase.getPrismContext();
        }
        QName targetTypeName = ((PrismReferenceDefinition) item.getDefinition()).getTargetTypeName();
        if (targetTypeName != null && prismContext != null) {
            typeFromName = prismContext.getSchemaRegistry().determineCompileTimeClass(targetTypeName);
        }
        final Class typeClass = typeFromName != null ? typeFromName
                : (item.getDefinition().getTypeClassIfKnown() != null
                        ? item.getDefinition().getTypeClassIfKnown()
                        : FocusType.class);
        panel = new ValueChoosePanel(id, new PropertyModel<>(model, "value"), item.getValues(), false,
                typeClass);

    } else if (item instanceof PrismContainer<?>) {
        ItemWrapper itemWrapper = model.getObject().getItem();
        final PrismContainer container = (PrismContainer) item;
        PrismContainerDefinition definition = container.getDefinition();
        QName valueType = definition.getTypeName();

        if (ShadowAssociationType.COMPLEX_TYPE.equals(valueType)) {

            PrismContext prismContext = item.getPrismContext();
            if (prismContext == null) {
                prismContext = pageBase.getPrismContext();
            }

            ShadowType shadowType = ((ShadowType) itemWrapper.getContainer().getObject().getObject()
                    .asObjectable());
            PrismObject<ResourceType> resource = shadowType.getResource().asPrismObject();
            // HACK. The revive should not be here. Revive is no good. The next use of the resource will
            // cause parsing of resource schema. We need some centralized place to maintain live cached copies
            // of resources.
            try {
                resource.revive(prismContext);
            } catch (SchemaException e) {
                throw new SystemException(e.getMessage(), e);
            }
            RefinedResourceSchema refinedSchema;
            CompositeRefinedObjectClassDefinition rOcDef;
            try {
                refinedSchema = RefinedResourceSchema.getRefinedSchema(resource);
                rOcDef = refinedSchema.determineCompositeObjectClassDefinition(shadowType.asPrismObject());
            } catch (SchemaException e) {
                throw new SystemException(e.getMessage(), e);
            }
            RefinedAssociationDefinition assocDef = rOcDef.findAssociation(itemWrapper.getName());
            RefinedObjectClassDefinition assocTarget = assocDef.getAssociationTarget();

            ObjectQuery query = getAssociationsSearchQuery(prismContext, resource, assocTarget.getTypeName(),
                    assocTarget.getKind(), assocTarget.getIntent());

            List values = item.getValues();
            return new AssociationValueChoosePanel(id, model, values, false, ShadowType.class, query);
        }
    }

    return panel;
}

From source file:nl.strohalm.cyclos.utils.ClassHelper.java

/**
 * Returns if the given object is an instance of the specified class, handling primitives as objects
 */// w  ww  . j a  v a2  s .co m
public static boolean isInstance(Class<?> clazz, final Object object) {
    if (clazz.isPrimitive()) {
        clazz = ClassUtils.primitiveToWrapper(clazz);
    }
    return clazz.isInstance(object);
}

From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convert(Class toType, Object value) {
    if ("".equals(value)) {
        value = null;//from   ww  w. j av  a2  s.  co  m
    }
    // If we do not want a collection, but the value is one, use the first value
    if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray())
            && (value.getClass().isArray() || value instanceof Collection)) {
        final Iterator it = IteratorUtils.getIterator(value);
        if (!it.hasNext()) {
            value = null;
        } else {
            value = it.next();
        }
    }

    // Check for null values
    if (value == null) {
        if (toType.isPrimitive()) {
            // On primitives, use the default value
            if (toType == Boolean.TYPE) {
                value = Boolean.FALSE;
            } else if (toType == Character.TYPE) {
                value = '\0';
            } else {
                value = 0;
            }
        } else {
            // For objects, return null
            return null;
        }
    }

    // Check if the value is already of the expected type
    if (toType.isInstance(value)) {
        return value;
    }

    // If the class is primitive, use the wrapper, so we have an easier work of testing instances
    if (toType.isPrimitive()) {
        toType = ClassUtils.primitiveToWrapper(toType);
    }

    // Convert to well-known types
    if (String.class.isAssignableFrom(toType)) {
        if (value instanceof Entity) {
            final Long entityId = ((Entity) value).getId();
            return entityId == null ? null : entityId.toString();
        }
        return value.toString();
    } else if (Number.class.isAssignableFrom(toType)) {
        if (!(value instanceof Number)) {
            if (value instanceof String) {
                value = new BigDecimal((String) value);
            } else if (value instanceof Date) {
                value = ((Date) value).getTime();
            } else if (value instanceof Calendar) {
                value = ((Calendar) value).getTimeInMillis();
            } else if (value instanceof Entity) {
                value = ((Entity) value).getId();
                if (value == null) {
                    return null;
                }
            } else {
                throw new ConversionException("Invalid number: " + value);
            }
        }
        final Number number = (Number) value;
        if (Byte.class.isAssignableFrom(toType)) {
            return number.byteValue();
        } else if (Short.class.isAssignableFrom(toType)) {
            return number.shortValue();
        } else if (Integer.class.isAssignableFrom(toType)) {
            return number.intValue();
        } else if (Long.class.isAssignableFrom(toType)) {
            return number.longValue();
        } else if (Float.class.isAssignableFrom(toType)) {
            return number.floatValue();
        } else if (Double.class.isAssignableFrom(toType)) {
            return number.doubleValue();
        } else if (BigInteger.class.isAssignableFrom(toType)) {
            return new BigInteger(number.toString());
        } else if (BigDecimal.class.isAssignableFrom(toType)) {
            return new BigDecimal(number.toString());
        }
    } else if (Boolean.class.isAssignableFrom(toType)) {
        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if ("on".equalsIgnoreCase(value.toString())) {
            return true;
        } else {
            return Boolean.parseBoolean(value.toString());
        }
    } else if (Character.class.isAssignableFrom(toType)) {
        final String str = value.toString();
        return (str.length() == 0) ? null : str.charAt(0);
    } else if (Calendar.class.isAssignableFrom(toType)) {
        if (value instanceof Date) {
            final Calendar cal = new GregorianCalendar();
            cal.setTime((Date) value);
            return cal;
        }
    } else if (Date.class.isAssignableFrom(toType)) {
        if (value instanceof Calendar) {
            final long millis = ((Calendar) value).getTimeInMillis();
            try {
                return ConstructorUtils.invokeConstructor(toType, millis);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    } else if (Enum.class.isAssignableFrom(toType)) {
        Object ret;
        try {
            ret = Enum.valueOf(toType, value.toString());
        } catch (final Exception e) {
            ret = null;
        }
        if (ret == null) {
            Object[] possible;
            try {
                possible = (Object[]) toType.getMethod("values").invoke(null);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Couldn't invoke the 'values' method for enum " + toType.getName());
            }
            if (StringValuedEnum.class.isAssignableFrom(toType)) {
                final String test = coerce(String.class, value);
                for (final Object item : possible) {
                    if (((StringValuedEnum) item).getValue().equals(test)) {
                        ret = item;
                        break;
                    }
                }
            } else if (IntValuedEnum.class.isAssignableFrom(toType)) {
                final int test = coerce(Integer.TYPE, value);
                for (final Object item : possible) {
                    if (((IntValuedEnum) item).getValue() == test) {
                        ret = item;
                        break;
                    }
                }
            } else {
                throw new ConversionException("Invalid enum: " + value);
            }
        }
        return ret;
    } else if (Entity.class.isAssignableFrom(toType)) {
        final Long id = coerce(Long.class, value);
        return EntityHelper.reference(toType, id);
    } else if (Locale.class.isAssignableFrom(toType)) {
        return LocaleConverter.instance().valueOf(value.toString());
    } else if (Collection.class.isAssignableFrom(toType)) {
        final Collection collection = (Collection) ClassHelper.instantiate(toType);
        final Iterator iterator = IteratorUtils.getIterator(value);
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
        return collection;
    } else if (toType.isArray()) {
        final Collection collection = coerceCollection(toType.getComponentType(), value);
        final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size());
        return collection.toArray(array);
    }

    // We don't know how to convert the value
    throw new ConversionException("Cannot coerce value to: " + toType.getName());
}

From source file:org.apache.camel.maven.AbstractApiMethodGeneratorMojo.java

public static String getResultDeclaration(Class<?> resultType) {
    if (resultType.isPrimitive()) {
        return ClassUtils.primitiveToWrapper(resultType).getSimpleName();
    } else {//from   ww  w.j a v  a2s. co m
        return getCanonicalName(resultType);
    }
}

From source file:org.apache.camel.maven.AbstractApiMethodGeneratorMojo.java

public String getCanonicalName(ApiMethodParser.Argument argument) throws MojoExecutionException {

    // replace primitives with wrapper classes
    final Class<?> type = argument.getType();
    if (type.isPrimitive()) {
        return getCanonicalName(ClassUtils.primitiveToWrapper(type));
    }/*from  w  w w  .  j ava 2 s  .c  o m*/

    // get default name prefix
    String canonicalName = getCanonicalName(type);

    final String typeArgs = argument.getTypeArgs();
    if (typeArgs != null) {

        // add generic type arguments
        StringBuilder parameterizedType = new StringBuilder(canonicalName);
        parameterizedType.append('<');

        // Note: its ok to split, since we don't support parsing nested type arguments
        final String[] argTypes = typeArgs.split(",");
        boolean ignore = false;
        final int nTypes = argTypes.length;
        int i = 0;
        for (String argType : argTypes) {

            // try loading as is first
            try {
                parameterizedType.append(getCanonicalName(getProjectClassLoader().loadClass(argType)));
            } catch (ClassNotFoundException e) {

                // try loading with default java.lang package prefix
                try {
                    if (log.isDebugEnabled()) {
                        log.debug("Could not load " + argType + ", trying to load java.lang." + argType);
                    }
                    parameterizedType.append(
                            getCanonicalName(getProjectClassLoader().loadClass("java.lang." + argType)));
                } catch (ClassNotFoundException e1) {
                    log.warn("Ignoring type parameters <" + typeArgs + "> for argument " + argument.getName()
                            + ", unable to load parametric type argument " + argType, e1);
                    ignore = true;
                }
            }

            if (ignore) {
                // give up
                break;
            } else if (++i < nTypes) {
                parameterizedType.append(",");
            }
        }

        if (!ignore) {
            parameterizedType.append('>');
            canonicalName = parameterizedType.toString();
        }
    }

    return canonicalName;
}

From source file:org.apache.camel.maven.DocumentGeneratorMojo.java

public static List<EndpointInfo> getEndpoints(Class<? extends ApiMethod> apiMethod, ApiMethodHelper<?> helper,
        Class<?> endpointConfig) {
    // get list of valid options
    final Set<String> validOptions = new HashSet<String>();
    for (Field field : endpointConfig.getDeclaredFields()) {
        validOptions.add(field.getName());
    }/* w  ww.j  a v  a 2s .co m*/

    // create method name map
    final Map<String, List<ApiMethod>> methodMap = new TreeMap<String, List<ApiMethod>>();
    for (ApiMethod method : apiMethod.getEnumConstants()) {
        String methodName = method.getName();
        List<ApiMethod> apiMethods = methodMap.get(methodName);
        if (apiMethods == null) {
            apiMethods = new ArrayList<ApiMethod>();
            methodMap.put(methodName, apiMethods);
        }
        apiMethods.add(method);
    }

    // create method name to alias name map
    final Map<String, Set<String>> aliasMap = new TreeMap<String, Set<String>>();
    final Map<String, Set<String>> aliasToMethodMap = helper.getAliases();
    for (Map.Entry<String, Set<String>> entry : aliasToMethodMap.entrySet()) {
        final String alias = entry.getKey();
        for (String method : entry.getValue()) {
            Set<String> aliases = aliasMap.get(method);
            if (aliases == null) {
                aliases = new TreeSet<String>();
                aliasMap.put(method, aliases);
            }
            aliases.add(alias);
        }
    }

    // create options map and return type map
    final Map<String, Set<String>> optionMap = new TreeMap<String, Set<String>>();
    final Map<String, Set<String>> returnType = new TreeMap<String, Set<String>>();
    for (Map.Entry<String, List<ApiMethod>> entry : methodMap.entrySet()) {
        final String name = entry.getKey();
        final List<ApiMethod> apiMethods = entry.getValue();

        // count the number of times, every valid option shows up across methods
        // and also collect return types
        final Map<String, Integer> optionCount = new TreeMap<String, Integer>();
        final TreeSet<String> resultTypes = new TreeSet<String>();
        returnType.put(name, resultTypes);

        for (ApiMethod method : apiMethods) {
            for (String arg : method.getArgNames()) {

                if (validOptions.contains(arg)) {
                    Integer count = optionCount.get(arg);
                    if (count == null) {
                        count = 1;
                    } else {
                        count += 1;
                    }
                    optionCount.put(arg, count);
                }
            }

            // wrap primitive result types
            Class<?> resultType = method.getResultType();
            if (resultType.isPrimitive()) {
                resultType = ClassUtils.primitiveToWrapper(resultType);
            }
            resultTypes.add(getCanonicalName(resultType));
        }

        // collect method options
        final TreeSet<String> options = new TreeSet<String>();
        optionMap.put(name, options);
        final Set<String> mandatory = new TreeSet<String>();

        // generate optional and mandatory lists for overloaded methods
        int nMethods = apiMethods.size();
        for (ApiMethod method : apiMethods) {
            final Set<String> optional = new TreeSet<String>();

            for (String arg : method.getArgNames()) {
                if (validOptions.contains(arg)) {

                    final Integer count = optionCount.get(arg);
                    if (count == nMethods) {
                        mandatory.add(arg);
                    } else {
                        optional.add(arg);
                    }
                }
            }

            if (!optional.isEmpty()) {
                options.add(optional.toString());
            }
        }

        if (!mandatory.isEmpty()) {
            // strip [] from mandatory options
            final String mandatoryOptions = mandatory.toString();
            options.add(mandatoryOptions.substring(1, mandatoryOptions.length() - 1));
        }
    }

    // create endpoint data
    final List<EndpointInfo> infos = new ArrayList<EndpointInfo>();
    for (Map.Entry<String, List<ApiMethod>> methodEntry : methodMap.entrySet()) {
        final String endpoint = methodEntry.getKey();

        // set endpoint name
        EndpointInfo info = new EndpointInfo();
        info.endpoint = endpoint;
        info.aliases = convertSetToString(aliasMap.get(endpoint));
        info.options = convertSetToString(optionMap.get(endpoint));
        final Set<String> resultTypes = returnType.get(endpoint);
        // get rid of void results
        resultTypes.remove("void");
        info.resultTypes = convertSetToString(resultTypes);

        infos.add(info);
    }

    return infos;
}

From source file:org.apache.sling.models.impl.injectors.ValueMapInjector.java

public Object getValue(@Nonnull Object adaptable, String name, @Nonnull Type type,
        @Nonnull AnnotatedElement element, @Nonnull DisposalCallbackRegistry callbackRegistry) {
    ValueMap map = getValueMap(adaptable);
    if (map == null) {
        return null;
    } else if (type instanceof Class<?>) {
        Class<?> clazz = (Class<?>) type;
        try {//from   w  ww  .  j av a 2  s .  co  m
            return map.get(name, clazz);
        } catch (ClassCastException e) {
            // handle case of primitive/wrapper arrays
            if (clazz.isArray()) {
                Class<?> componentType = clazz.getComponentType();
                if (componentType.isPrimitive()) {
                    Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType);
                    if (wrapper != componentType) {
                        Object wrapperArray = map.get(name, Array.newInstance(wrapper, 0).getClass());
                        if (wrapperArray != null) {
                            return unwrapArray(wrapperArray, componentType);
                        }
                    }
                } else {
                    Class<?> primitiveType = ClassUtils.wrapperToPrimitive(componentType);
                    if (primitiveType != componentType) {
                        Object primitiveArray = map.get(name, Array.newInstance(primitiveType, 0).getClass());
                        if (primitiveArray != null) {
                            return wrapArray(primitiveArray, componentType);
                        }
                    }
                }
            }
            return null;
        }
    } else if (type instanceof ParameterizedType) {
        // list support
        ParameterizedType pType = (ParameterizedType) type;
        if (pType.getActualTypeArguments().length != 1) {
            return null;
        }
        Class<?> collectionType = (Class<?>) pType.getRawType();
        if (!(collectionType.equals(Collection.class) || collectionType.equals(List.class))) {
            return null;
        }

        Class<?> itemType = (Class<?>) pType.getActualTypeArguments()[0];
        Object array = map.get(name, Array.newInstance(itemType, 0).getClass());
        if (array == null) {
            return null;

        }

        return Arrays.asList((Object[]) array);
    } else {
        log.debug("ValueMapInjector doesn't support non-class types {}", type);
        return null;
    }
}

From source file:org.apache.sling.models.impl.ReflectionUtil.java

public static Type mapPrimitiveClasses(Type type) {
    if (type instanceof Class<?>) {
        return ClassUtils.primitiveToWrapper((Class<?>) type);
    } else {/*w ww  .  ja  va2s  .  co m*/
        return type;
    }
}