Example usage for java.lang Byte TYPE

List of usage examples for java.lang Byte TYPE

Introduction

In this page you can find the example usage for java.lang Byte TYPE.

Prototype

Class TYPE

To view the source code for java.lang Byte TYPE.

Click Source Link

Document

The Class instance representing the primitive type byte .

Usage

From source file:org.apache.hadoop.hbase.security.access.HbaseObjectWritableFor96Migration.java

/**
 * Read a {@link Writable}, {@link String}, primitive type, or an array of
 * the preceding./*from  w w w  .java 2 s  .co m*/
 * @param in
 * @param objectWritable
 * @param conf
 * @return the object
 * @throws IOException
 */
@SuppressWarnings("unchecked")
static Object readObject(DataInput in, HbaseObjectWritableFor96Migration objectWritable, Configuration conf)
        throws IOException {
    Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
    Object instance;
    if (declaredClass.isPrimitive()) { // primitive types
        if (declaredClass == Boolean.TYPE) { // boolean
            instance = Boolean.valueOf(in.readBoolean());
        } else if (declaredClass == Character.TYPE) { // char
            instance = Character.valueOf(in.readChar());
        } else if (declaredClass == Byte.TYPE) { // byte
            instance = Byte.valueOf(in.readByte());
        } else if (declaredClass == Short.TYPE) { // short
            instance = Short.valueOf(in.readShort());
        } else if (declaredClass == Integer.TYPE) { // int
            instance = Integer.valueOf(in.readInt());
        } else if (declaredClass == Long.TYPE) { // long
            instance = Long.valueOf(in.readLong());
        } else if (declaredClass == Float.TYPE) { // float
            instance = Float.valueOf(in.readFloat());
        } else if (declaredClass == Double.TYPE) { // double
            instance = Double.valueOf(in.readDouble());
        } else if (declaredClass == Void.TYPE) { // void
            instance = null;
        } else {
            throw new IllegalArgumentException("Not a primitive: " + declaredClass);
        }
    } else if (declaredClass.isArray()) { // array
        if (declaredClass.equals(byte[].class)) {
            instance = Bytes.readByteArray(in);
        } else {
            int length = in.readInt();
            instance = Array.newInstance(declaredClass.getComponentType(), length);
            for (int i = 0; i < length; i++) {
                Array.set(instance, i, readObject(in, conf));
            }
        }
    } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE
        Class<?> componentType = readClass(conf, in);
        int length = in.readInt();
        instance = Array.newInstance(componentType, length);
        for (int i = 0; i < length; i++) {
            Array.set(instance, i, readObject(in, conf));
        }
    } else if (List.class.isAssignableFrom(declaredClass)) { // List
        int length = in.readInt();
        instance = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ((ArrayList) instance).add(readObject(in, conf));
        }
    } else if (declaredClass == String.class) { // String
        instance = Text.readString(in);
    } else if (declaredClass.isEnum()) { // enum
        instance = Enum.valueOf((Class<? extends Enum>) declaredClass, Text.readString(in));
    } else if (declaredClass == Message.class) {
        String className = Text.readString(in);
        try {
            declaredClass = getClassByName(conf, className);
            instance = tryInstantiateProtobuf(declaredClass, in);
        } catch (ClassNotFoundException e) {
            LOG.error("Can't find class " + className, e);
            throw new IOException("Can't find class " + className, e);
        }
    } else if (Scan.class.isAssignableFrom(declaredClass)) {
        int length = in.readInt();
        byte[] scanBytes = new byte[length];
        in.readFully(scanBytes);
        ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder();
        instance = ProtobufUtil.toScan(scanProto.mergeFrom(scanBytes).build());
    } else { // Writable or Serializable
        Class instanceClass = null;
        int b = (byte) WritableUtils.readVInt(in);
        if (b == NOT_ENCODED) {
            String className = Text.readString(in);
            try {
                instanceClass = getClassByName(conf, className);
            } catch (ClassNotFoundException e) {
                LOG.error("Can't find class " + className, e);
                throw new IOException("Can't find class " + className, e);
            }
        } else {
            instanceClass = CODE_TO_CLASS.get(b);
        }
        if (Writable.class.isAssignableFrom(instanceClass)) {
            Writable writable = WritableFactories.newInstance(instanceClass, conf);
            try {
                writable.readFields(in);
            } catch (Exception e) {
                LOG.error("Error in readFields", e);
                throw new IOException("Error in readFields", e);
            }
            instance = writable;
            if (instanceClass == NullInstance.class) { // null
                declaredClass = ((NullInstance) instance).declaredClass;
                instance = null;
            }
        } else {
            int length = in.readInt();
            byte[] objectBytes = new byte[length];
            in.readFully(objectBytes);
            ByteArrayInputStream bis = null;
            ObjectInputStream ois = null;
            try {
                bis = new ByteArrayInputStream(objectBytes);
                ois = new ObjectInputStream(bis);
                instance = ois.readObject();
            } catch (ClassNotFoundException e) {
                LOG.error("Class not found when attempting to deserialize object", e);
                throw new IOException("Class not found when attempting to " + "deserialize object", e);
            } finally {
                if (bis != null)
                    bis.close();
                if (ois != null)
                    ois.close();
            }
        }
    }
    if (objectWritable != null) { // store values
        objectWritable.declaredClass = declaredClass;
        objectWritable.instance = instance;
    }
    return instance;
}

From source file:javadz.beanutils.ConvertUtilsBean.java

/**
 * Register the converters for primitive types.
 * </p>//from  w w w . j  a v a2  s . c om
 * This method registers the following converters:
 * <ul>
 *     <li><code>Boolean.TYPE</code> - {@link BooleanConverter}</li>
 *     <li><code>Byte.TYPE</code> - {@link ByteConverter}</li>
 *     <li><code>Character.TYPE</code> - {@link CharacterConverter}</li>
 *     <li><code>Double.TYPE</code> - {@link DoubleConverter}</li>
 *     <li><code>Float.TYPE</code> - {@link FloatConverter}</li>
 *     <li><code>Integer.TYPE</code> - {@link IntegerConverter}</li>
 *     <li><code>Long.TYPE</code> - {@link LongConverter}</li>
 *     <li><code>Short.TYPE</code> - {@link ShortConverter}</li>
 * </ul>
 * @param throwException <code>true</code> if the converters should
 * throw an exception when a conversion error occurs, otherwise <code>
 * <code>false</code> if a default value should be used.
 */
private void registerPrimitives(boolean throwException) {
    register(Boolean.TYPE, throwException ? new BooleanConverter() : new BooleanConverter(Boolean.FALSE));
    register(Byte.TYPE, throwException ? new ByteConverter() : new ByteConverter(ZERO));
    register(Character.TYPE, throwException ? new CharacterConverter() : new CharacterConverter(SPACE));
    register(Double.TYPE, throwException ? new DoubleConverter() : new DoubleConverter(ZERO));
    register(Float.TYPE, throwException ? new FloatConverter() : new FloatConverter(ZERO));
    register(Integer.TYPE, throwException ? new IntegerConverter() : new IntegerConverter(ZERO));
    register(Long.TYPE, throwException ? new LongConverter() : new LongConverter(ZERO));
    register(Short.TYPE, throwException ? new ShortConverter() : new ShortConverter(ZERO));
}

From source file:org.springframework.oxm.jaxb.Jaxb2Marshaller.java

@Override
public boolean supports(Type genericType) {
    if (genericType instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) genericType;
        if (JAXBElement.class == parameterizedType.getRawType()
                && parameterizedType.getActualTypeArguments().length == 1) {
            Type typeArgument = parameterizedType.getActualTypeArguments()[0];
            if (typeArgument instanceof Class) {
                Class<?> classArgument = (Class<?>) typeArgument;
                return (((classArgument.isArray() && Byte.TYPE == classArgument.getComponentType()))
                        || isPrimitiveWrapper(classArgument) || isStandardClass(classArgument)
                        || supportsInternal(classArgument, false));
            } else if (typeArgument instanceof GenericArrayType) {
                GenericArrayType arrayType = (GenericArrayType) typeArgument;
                return (Byte.TYPE == arrayType.getGenericComponentType());
            }/*ww w.  j  a v a  2 s  .c  om*/
        }
    } else if (genericType instanceof Class) {
        Class<?> clazz = (Class<?>) genericType;
        return supportsInternal(clazz, this.checkForXmlRootElement);
    }
    return false;
}

From source file:org.apache.struts.action.DynaActionForm.java

/**
 * <p>Indicates if an object of the source class is assignable to the
 * destination class.</p>//from ww w  .  j a v a2 s . co  m
 *
 * @param dest   Destination class
 * @param source Source class
 * @return <code>true</code> if the source is assignable to the
 *         destination; <code>false</code> otherwise.
 */
protected boolean isDynaAssignable(Class dest, Class source) {
    if (dest.isAssignableFrom(source) || ((dest == Boolean.TYPE) && (source == Boolean.class))
            || ((dest == Byte.TYPE) && (source == Byte.class))
            || ((dest == Character.TYPE) && (source == Character.class))
            || ((dest == Double.TYPE) && (source == Double.class))
            || ((dest == Float.TYPE) && (source == Float.class))
            || ((dest == Integer.TYPE) && (source == Integer.class))
            || ((dest == Long.TYPE) && (source == Long.class))
            || ((dest == Short.TYPE) && (source == Short.class))) {
        return (true);
    } else {
        return (false);
    }
}

From source file:com.sun.faces.config.ManagedBeanFactory.java

/**
 * <li><p> Call the property getter, if it exists.</p></li>
 * <p/>/*from w  w w. j  a va2  s.  c o m*/
 * <li><p>If the getter returns null or doesn't exist, create a
 * java.util.ArrayList(), otherwise use the returned Object (an array or
 * a java.util.List).</p></li>
 * <p/>
 * <li><p>If a List was returned or created in step 2), add all
 * elements defined by nested &lt;value&gt; elements in the order
 * they are listed, converting values defined by nested
 * &lt;value&gt; elements to the type defined by
 * &lt;value-class&gt;. If a &lt;value-class&gt; is not defined, use
 * the value as-is (i.e., as a java.lang.String). Add null for each
 * &lt;null-value&gt; element.</p></li>
 * <p/>
 * <li><p> If an array was returned in step 2), create a
 * java.util.ArrayList and copy all elements from the returned array to
 * the new List, auto-boxing elements of a primitive type. Add all
 * elements defined by nested &lt;value&gt; elements as described in step
 * 3).</p></li>
 * <p/>
 * <li><p> If a new java.util.List was created in step 2) and the
 * property is of type List, set the property by calling the setter
 * method, or log an error if there is no setter method.</p></li>
 * <p/>
 * <li><p> If a new java.util.List was created in step 4), convert
 * the * List to array of the same type as the property and set the
 * property by * calling the setter method, or log an error if there
 * is no setter * method.</p></li>
 */

private void setArrayOrListPropertiesIntoBean(Object bean, ManagedPropertyBean property) throws Exception {
    Object result = null;
    boolean getterIsNull = true, getterIsArray = false;
    List valuesForBean = null;
    Class valueType = java.lang.String.class, propertyType = null;

    String propertyName = property.getPropertyName();

    try {
        // see if there is a getter
        result = PropertyUtils.getProperty(bean, propertyName);
        getterIsNull = (null == result) ? true : false;

        propertyType = PropertyUtils.getPropertyType(bean, propertyName);
        getterIsArray = propertyType.isArray();

    } catch (NoSuchMethodException nsme) {
        // it's valid to not have a getter.
    }

    // the property has to be either a List or Array
    if (!getterIsArray) {
        if (null != propertyType && !java.util.List.class.isAssignableFrom(propertyType)) {
            throw new FacesException(
                    Util.getExceptionMessageString(Util.MANAGED_BEAN_CANNOT_SET_LIST_ARRAY_PROPERTY_ID,
                            new Object[] { propertyName, managedBean.getManagedBeanName() }));
        }
    }

    //
    // Deal with the possibility of the getter returning existing
    // values.
    //

    // if the getter returned non-null
    if (!getterIsNull) {
        // if what it returned was an array
        if (getterIsArray) {
            valuesForBean = new ArrayList();
            for (int i = 0, len = Array.getLength(result); i < len; i++) {
                // add the existing values
                valuesForBean.add(Array.get(result, i));
            }
        } else {
            // if what it returned was not a List
            if (!(result instanceof List)) {
                // throw an exception                    
                throw new FacesException(
                        Util.getExceptionMessageString(Util.MANAGED_BEAN_EXISTING_VALUE_NOT_LIST_ID,
                                new Object[] { propertyName, managedBean.getManagedBeanName() }));
            }
            valuesForBean = (List) result;
        }
    } else {

        // getter returned null
        result = valuesForBean = new ArrayList();
    }

    // at this point valuesForBean contains the existing values from
    // the bean, or no values if the bean had no values.  In any
    // case, we can proceed to add values from the config file.
    valueType = copyListEntriesFromConfigToList(property.getListEntries(), valuesForBean);

    // at this point valuesForBean has the values to be set into the
    // bean.

    if (getterIsArray) {
        // convert back to Array
        result = Array.newInstance(valueType, valuesForBean.size());
        for (int i = 0, len = valuesForBean.size(); i < len; i++) {
            if (valueType == Boolean.TYPE) {
                Array.setBoolean(result, i, ((Boolean) valuesForBean.get(i)).booleanValue());
            } else if (valueType == Byte.TYPE) {
                Array.setByte(result, i, ((Byte) valuesForBean.get(i)).byteValue());
            } else if (valueType == Double.TYPE) {
                Array.setDouble(result, i, ((Double) valuesForBean.get(i)).doubleValue());
            } else if (valueType == Float.TYPE) {
                Array.setFloat(result, i, ((Float) valuesForBean.get(i)).floatValue());
            } else if (valueType == Integer.TYPE) {
                Array.setInt(result, i, ((Integer) valuesForBean.get(i)).intValue());
            } else if (valueType == Character.TYPE) {
                Array.setChar(result, i, ((Character) valuesForBean.get(i)).charValue());
            } else if (valueType == Short.TYPE) {
                Array.setShort(result, i, ((Short) valuesForBean.get(i)).shortValue());
            } else if (valueType == Long.TYPE) {
                Array.setLong(result, i, ((Long) valuesForBean.get(i)).longValue());
            } else {
                Array.set(result, i, valuesForBean.get(i));
            }
        }
    } else {
        result = valuesForBean;
    }

    if (getterIsNull || getterIsArray) {
        PropertyUtils.setProperty(bean, propertyName, result);
    }

}

From source file:ResultSetIterator.java

/**
 * ResultSet.getObject() returns an Integer object for an INT column.  The
 * setter method for the property might take an Integer or a primitive int.
 * This method returns true if the value can be successfully passed into
 * the setter method.  Remember, Method.invoke() handles the unwrapping
 * of Integer into an int.//from   www  .  j a va2 s  . c o  m
 * 
 * @param value The value to be passed into the setter method.
 * @param type The setter's parameter type.
 * @return boolean True if the value is compatible.
 */
private boolean isCompatibleType(Object value, Class type) {
    // Do object check first, then primitives
    if (value == null || type.isInstance(value)) {
        return true;

    } else if (type.equals(Integer.TYPE) && Integer.class.isInstance(value)) {
        return true;

    } else if (type.equals(Long.TYPE) && Long.class.isInstance(value)) {
        return true;

    } else if (type.equals(Double.TYPE) && Double.class.isInstance(value)) {
        return true;

    } else if (type.equals(Float.TYPE) && Float.class.isInstance(value)) {
        return true;

    } else if (type.equals(Short.TYPE) && Short.class.isInstance(value)) {
        return true;

    } else if (type.equals(Byte.TYPE) && Byte.class.isInstance(value)) {
        return true;

    } else if (type.equals(Character.TYPE) && Character.class.isInstance(value)) {
        return true;

    } else if (type.equals(Boolean.TYPE) && Boolean.class.isInstance(value)) {
        return true;

    } else {
        return false;
    }

}

From source file:org.exolab.castor.xml.StartElementProcessor.java

public void compute(String name, String namespace, AttributeSet atts) throws SAXException {

    UnmarshalState state = null;//from ww w .  j ava2 s .c o m
    String xmlSpace = null;

    // -- handle special atts
    if (atts != null) {
        // -- xml:space
        xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE, Namespaces.XML_NAMESPACE);
        if (xmlSpace == null) {
            xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE_WITH_PREFIX, "");
        }
    }

    if (_unmarshalHandler.getStateStack().isEmpty()) {
        // -- Initialize since this is the first element
        _unmarshalHandler.processFirstElement(name, namespace, atts, xmlSpace);
        return;
    } // --rootElement

    // -- get MarshalDescriptor for the given element
    UnmarshalState parentState = _unmarshalHandler.getStateStack().getLastState();

    // Test if we can accept the field in the parentState
    // in case the parentState fieldDesc is a container
    // -- This following logic tests to see if we are in a
    // -- container and we need to close out the container
    // -- before proceeding:
    boolean canAccept = false;
    while ((parentState.getFieldDescriptor() != null)
            && (parentState.getFieldDescriptor().isContainer() && !canAccept)) {
        XMLClassDescriptor tempClassDesc = parentState.getClassDescriptor();

        // -- Find ClassDescriptor for Parent
        if (tempClassDesc == null) {
            tempClassDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor();
            if (tempClassDesc == null)
                tempClassDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass());
        }

        canAccept = tempClassDesc.canAccept(name, namespace, parentState.getObject());

        if (!canAccept) {
            // -- Does container class even handle this field?
            if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) {
                if (!parentState.getFieldDescriptor().isMultivalued()) {
                    String error = MessageFormat.format(
                            resourceBundle.getString("unmarshalHandler.error.container.full"),
                            new Object[] { tempClassDesc.getJavaClass().getName(), name });
                    ValidationException vx = new ValidationException(error);
                    throw new SAXException(vx);
                }
            }
            _unmarshalHandler.endElement(parentState.getElementName());
            parentState = _unmarshalHandler.getStateStack().getLastState();
        }
        tempClassDesc = null;
    }

    // -- create new state object
    state = new UnmarshalState();
    state.setElementName(name);
    state.setParent(parentState);

    if (xmlSpace != null) {
        state.setWhitespacePreserving(UnmarshalHandler.PRESERVE.equals(xmlSpace));
    } else {
        state.setWhitespacePreserving(parentState.isWhitespacePreserving());
    }

    _unmarshalHandler.getStateStack().pushState(state);

    // -- make sure we should proceed
    if (parentState.getObject() == null) {
        if (!parentState.isWrapper()) {
            return;
        }
    }

    Class cls = null;

    // -- Find ClassDescriptor for Parent
    XMLClassDescriptor classDesc = parentState.getClassDescriptor();
    if (classDesc == null) {
        classDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor();
        if (classDesc == null)
            classDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass());
    } else {
        // classDesc.resetElementCount();
    }

    // ----------------------------------------------------/
    // - Find FieldDescriptor associated with the element -/
    // ----------------------------------------------------/

    // -- A reference to the FieldDescriptor associated
    // -- the the "current" element
    XMLFieldDescriptor descriptor = null;

    // -- inherited class descriptor
    // -- (only needed if descriptor cannot be found directly)
    XMLClassDescriptor cdInherited = null;

    // -- loop through stack and find correct descriptor
    // int pIdx = _stateInfo.size() - 2; //-- index of parentState
    UnmarshalState targetState = parentState;
    String path = "";
    int count = 0;
    boolean isWrapper = false;
    XMLClassDescriptor oldClassDesc = classDesc;
    while (descriptor == null) {

        // -- NOTE (kv 20050228):
        // -- we need to clean this code up, I made this
        // -- fix to make sure the correct descriptor which
        // -- matches the location path is used
        if (path.length() > 0) {
            String tmpName = path + "/" + name;
            descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element);
        }
        // -- End Patch

        if (descriptor == null) {
            descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element);
        }

        // -- Namespace patch, should be moved to XMLClassDescriptor, but
        // -- this is the least intrusive patch at the moment. kv - 20030423
        if ((descriptor != null) && (!descriptor.isContainer())) {
            if (StringUtils.isNotEmpty(namespace)) {
                if (!MarshalFramework.namespaceEquals(namespace, descriptor.getNameSpaceURI())) {
                    // -- if descriptor namespace is not null, then we must
                    // -- have a namespace match, so set descriptor to null,
                    // -- or if descriptor is not a wildcard we can also
                    // -- set to null.
                    if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) {
                        descriptor = null;
                    }

                }
            }
        }
        // -- end namespace patch

        /*
         * If descriptor is null, we need to handle possible inheritence, which might not be described
         * in the current ClassDescriptor. This can be a slow process...for speed use the match
         * attribute of the xml element in the mapping file. This logic might not be completely
         * necessary, and perhaps we should remove it.
         */
        // handle multiple level locations (where count > 0) (CASTOR-1039)
        // if ((descriptor == null) && (count == 0) &&
        // (!targetState.wrapper)) {
        if ((descriptor == null) && (!targetState.isWrapper())) {
            MarshalFramework.InheritanceMatch[] matches = null;
            try {
                matches = _unmarshalHandler.searchInheritance(name, namespace, classDesc); // TODO:
                                                                                           // Joachim,
                                                                                           // _cdResolver);
            } catch (MarshalException rx) {
                // -- TODO:
            }
            if (matches.length != 0) {
                InheritanceMatch match = null;
                // It may be the case that this class descriptor can
                // appear under multiple parent field descriptors. Look
                // for the first match whose parent file descriptor XML
                // name matches the name of the element we are under
                for (int i = 0; i < matches.length; i++) {
                    if (parentState.getElementName().equals(matches[i].parentFieldDesc.getLocationPath())) {
                        match = matches[i];
                        break;
                    }
                }
                if (match == null)
                    match = matches[0];
                descriptor = match.parentFieldDesc;
                cdInherited = match.inheritedClassDesc;
                break; // -- found
            }
            /* */

            // handle multiple level locations (where count > 0)
            // (CASTOR-1039)
            // isWrapper = (isWrapper || hasFieldsAtLocation(name,
            // classDesc));
            StringBuilder tmpLocation = new StringBuilder();
            if (count > 0) {
                tmpLocation.append(path).append('/');
            }
            tmpLocation.append(name);
            isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(tmpLocation.toString(), classDesc));
        } else if (descriptor != null) {
            String tmpPath = descriptor.getLocationPath();
            if (path.equals(StringUtils.defaultString(tmpPath)))
                break; // -- found
            descriptor = null; // -- not found, try again
        } else {
            isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(path + '/' + name, classDesc));
        }

        // -- Make sure there are more parent classes on stack
        // -- otherwise break, since there is nothing to do
        // if (pIdx == 0) break;
        if (targetState == _unmarshalHandler.getTopState())
            break;

        // -- adjust name and try parent
        if (count == 0)
            path = targetState.getElementName();
        else {
            path = targetState.getElementName() + '/' + path;
        }

        // -- get
        // --pIdx;
        // targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
        targetState = targetState.getParent();
        classDesc = targetState.getClassDescriptor();
        count++;
    }

    if (descriptor != null && _unmarshalHandler.isValidating()
            && !_unmarshalHandler.getInternalContext().getLenientSequenceOrder()) {
        try {
            classDesc.checkDescriptorForCorrectOrderWithinSequence(descriptor, parentState, name);
        } catch (ValidationException e) {
            throw new SAXException(e);
        }
    }

    // -- The field descriptor is still null, we face a problem
    if (descriptor == null) {

        // -- reset classDesc
        classDesc = oldClassDesc;

        // -- isWrapper?
        if (isWrapper) {
            state.setClassDescriptor(new XMLClassDescriptorImpl(ContainerElement.class, name));
            state.setWrapper(true);
            if (LOG.isDebugEnabled()) {
                LOG.debug("wrapper-element: " + name);
            }
            // -- process attributes
            _unmarshalHandler.processWrapperAttributes(atts);
            return;
        }

        String error = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.find.field.descriptor"),
                new Object[] { name, classDesc.getXMLName() });

        // -- unwrap classDesc, if necessary, for the check
        // -- Introspector.introspected done below
        if (classDesc instanceof InternalXMLClassDescriptor) {
            classDesc = ((InternalXMLClassDescriptor) classDesc).getClassDescriptor();
        }

        // -- If we are skipping elements that have appeared in the XML but
        // for
        // -- which we have no mapping, increase the ignore depth counter
        // and return
        boolean lenientElementStrictnessForIntrospection = _unmarshalHandler.getInternalContext()
                .getBooleanProperty(XMLProperties.LENIENT_INTROSPECTED_ELEMENT_STRICTNESS).booleanValue();
        // checks if the element could be skipped
        if (_unmarshalHandler.getStrictElementHandler().skipStartElementIgnoringDepth()) {
            // -- remove the StateInfo we just added
            _unmarshalHandler.getStateStack().removeLastState();
            // drop Namespace instance as well
            _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
            if (LOG.isDebugEnabled()) {
                String debug = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.log.debug.ignore.extra.element"),
                        new Object[] { error });
                LOG.debug(debug);
            }
            return;
        }
        // if we have no field descriptor and
        // the class descriptor was introspected
        // just log it
        else if (lenientElementStrictnessForIntrospection && Introspector.introspected(classDesc)) {
            LOG.warn(error);
            return;
        }
        // -- otherwise report error since we cannot find a suitable
        // -- descriptor
        else {
            throw new SAXException(error);
        }
    } // -- end null descriptor

    // / DEBUG: System.out.println("path: " + path);

    // -- Save targetState (used in endElement)
    if (targetState != parentState) {
        state.setTargetState(targetState);
        parentState = targetState; // -- reassign
    }

    Object object = parentState.getObject();
    // --container support
    if (descriptor.isContainer()) {
        // create a new state to set the container as the object
        // don't save the current state, it will be recreated later

        if (LOG.isDebugEnabled()) {
            LOG.debug("#container: " + descriptor.getFieldName());
        }

        // -- clear current state and re-use for the container
        state.clear();
        // -- inherit whitespace preserving from the parentState
        state.setWhitespacePreserving(parentState.isWhitespacePreserving());
        state.setParent(parentState);

        // here we can hard-code a name or take the field name
        state.setElementName(descriptor.getFieldName());
        state.setFieldDescriptor(descriptor);
        state.setClassDescriptor((XMLClassDescriptor) descriptor.getClassDescriptor());
        Object containerObject = null;

        // 1-- the container is not multivalued (not a collection)
        if (!descriptor.isMultivalued()) {
            // Check if the container object has already been instantiated
            FieldHandler handler = descriptor.getHandler();
            containerObject = handler.getValue(object);
            if (containerObject != null) {
                if (state.getClassDescriptor() != null) {
                    if (state.getClassDescriptor().canAccept(name, namespace, containerObject)) {
                        // remove the descriptor from the used list
                        parentState.markAsNotUsed(descriptor);
                    }
                } else {
                    // remove the descriptor from the used list
                    parentState.markAsNotUsed(descriptor);
                }
            } else {
                containerObject = handler.newInstance(object);
            }

        }
        // 2-- the container is multivalued
        else {
            Class containerClass = descriptor.getFieldType();
            try {
                containerObject = containerClass.newInstance();
            } catch (Exception ex) {
                throw new SAXException(ex);
            }
        }
        state.setObject(containerObject);
        state.setType(containerObject.getClass());

        // we need to recall startElement()
        // so that we can find a more appropriate descriptor in for the
        // given name
        _unmarshalHandler.getNamespaceHandling().createNamespace();
        _unmarshalHandler.startElementProcessing(name, namespace, atts);
        return;
    }
    // --End of the container support

    // -- Find object type and create new Object of that type
    state.setFieldDescriptor(descriptor);

    /*
     * <update> we need to add this code back in, to make sure we have proper access rights.
     * 
     * if (!descriptor.getAccessRights().isWritable()) { if (debug) { buf.setLength(0); buf.append(
     * "The field for element '"); buf.append(name); buf.append("' is read-only.");
     * message(buf.toString()); } return; }
     */

    // -- Find class to instantiate
    // -- check xml names to see if we should look for a more specific
    // -- ClassDescriptor, otherwise just use the one found in the
    // -- descriptor
    classDesc = null;
    if (cdInherited != null)
        classDesc = cdInherited;
    else if (!name.equals(descriptor.getXMLName()))
        classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, null);

    if (classDesc == null)
        classDesc = (XMLClassDescriptor) descriptor.getClassDescriptor();
    FieldHandler handler = descriptor.getHandler();
    boolean useHandler = true;

    try {

        // -- Get Class type...first use ClassDescriptor,
        // -- since it could be more specific than
        // -- the FieldDescriptor
        if (classDesc != null) {
            cls = classDesc.getJavaClass();

            // -- XXXX This is a hack I know...but we
            // -- XXXX can't use the handler if the field
            // -- XXXX types are different
            if (descriptor.getFieldType() != cls) {
                state.setDerived(true);
            }
        } else {
            cls = descriptor.getFieldType();
        }

        // -- This *shouldn't* happen, but a custom implementation
        // -- could return null in the XMLClassDesctiptor#getJavaClass
        // -- or XMLFieldDescriptor#getFieldType. If so, just replace
        // -- with java.lang.Object.class (basically "anyType").
        if (cls == null) {
            cls = java.lang.Object.class;
        }

        // Retrieving the xsi:type attribute, if present
        String currentPackage = _unmarshalHandler.getJavaPackage(parentState.getType());
        String instanceType = _unmarshalHandler.getInstanceType(atts, currentPackage);
        if (instanceType != null) {

            Class instanceClass = null;
            try {

                XMLClassDescriptor instanceDesc = _unmarshalHandler.getClassDescriptor(instanceType,
                        _unmarshalHandler.getClassLoader());

                boolean loadClass = true;

                if (instanceDesc != null) {
                    instanceClass = instanceDesc.getJavaClass();
                    classDesc = instanceDesc;
                    if (instanceClass != null) {
                        loadClass = (!instanceClass.getName().equals(instanceType));
                    }
                }

                if (loadClass) {
                    instanceClass = _unmarshalHandler.loadClass(instanceType, null);
                    // the FieldHandler can be either an XMLFieldHandler
                    // or a FieldHandlerImpl
                    FieldHandler tempHandler = descriptor.getHandler();

                    boolean collection = false;
                    if (tempHandler instanceof FieldHandlerImpl) {
                        collection = ((FieldHandlerImpl) tempHandler).isCollection();
                    } else {
                        collection = Introspector.isCollection(instanceClass);
                    }

                    if ((!collection) && !cls.isAssignableFrom(instanceClass)) {
                        if (!MarshalFramework.isPrimitive(cls)) {
                            String err = MessageFormat.format(
                                    resourceBundle.getString("unmarshalHandler.error.not.subclass"),
                                    new Object[] { instanceClass.getName(), cls.getName() });
                            throw new SAXException(err);
                        }
                    }
                }
                cls = instanceClass;
                useHandler = false;
            } catch (Exception ex) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"),
                        new Object[] { instanceType, ex.getMessage() });
                throw new SAXException(err, ex);
            }

        }

        // -- Handle ArrayHandler
        if (cls == Object.class) {
            if (parentState.getObject() instanceof ArrayHandler)
                cls = ((ArrayHandler) parentState.getObject()).componentType();
        }

        // -- Handle support for "Any" type

        if (cls == Object.class) {
            Class pClass = parentState.getType();
            ClassLoader loader = pClass.getClassLoader();
            // -- first look for a descriptor based
            // -- on the XML name
            classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, loader);
            // -- if null, create classname, and try resolving
            String cname = null;
            if (classDesc == null) {
                // -- create class name
                cname = _unmarshalHandler.getJavaNaming().toJavaClassName(name);
                classDesc = _unmarshalHandler.getClassDescriptor(cname, loader);
            }
            // -- if still null, try using parents package
            if (classDesc == null) {
                // -- use parent to get package information
                String pkg = pClass.getName();
                int idx = pkg.lastIndexOf('.');
                if (idx > 0) {
                    pkg = pkg.substring(0, idx + 1);
                    cname = pkg + cname;
                    classDesc = _unmarshalHandler.getClassDescriptor(cname, loader);
                }
            }

            if (classDesc != null) {
                cls = classDesc.getJavaClass();
                useHandler = false;
            } else {
                // we are dealing with an AnyNode
                state.setObject(_unmarshalHandler.getAnyNodeHandler().commonStartElement(name, namespace,
                        state.isWhitespacePreserving()));
                state.setType(cls);
                return;
            }
        }

        boolean byteArray = false;
        if (cls.isArray())
            byteArray = (cls.getComponentType() == Byte.TYPE);

        // -- check for immutable
        if (MarshalFramework.isPrimitive(cls) || descriptor.isImmutable() || byteArray) {
            state.setObject(null);
            state.setPrimitiveOrImmutable(true);
            // -- handle immutable types, such as java.util.Locale
            if (descriptor.isImmutable()) {
                if (classDesc == null)
                    classDesc = _unmarshalHandler.getClassDescriptor(cls);
                state.setClassDescriptor(classDesc);
                Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                if (args != null && args.size() > 0) {
                    state.setConstructorArguments(args);
                }
            }
        } else {
            if (classDesc == null)
                classDesc = _unmarshalHandler.getClassDescriptor(cls);

            // -- XXXX should remove this test once we can
            // -- XXXX come up with a better solution
            if ((!state.isDerived()) && useHandler) {

                boolean create = true;
                if (_unmarshalHandler.isReuseObjects()) {
                    state.setObject(handler.getValue(parentState.getObject()));
                    create = (state.getObject() == null);
                }
                if (create) {
                    Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                    if ((args.getValues() != null) && (args.getValues().length > 0)) {
                        if (handler instanceof ExtendedFieldHandler) {
                            ExtendedFieldHandler efh = (ExtendedFieldHandler) handler;
                            state.setObject(efh.newInstance(parentState.getObject(), args.getValues()));
                        } else {
                            String err = resourceBundle
                                    .getString("unmarshalHandler.error.constructor.arguments");
                            throw new SAXException(err);
                        }
                    } else {
                        state.setObject(handler.newInstance(parentState.getObject()));
                    }
                }
            }
            // -- reassign class in case there is a conflict
            // -- between descriptor#getFieldType and
            // -- handler#newInstance...I should hope not, but
            // -- who knows
            if (state.getObject() != null) {
                cls = state.getObject().getClass();
                if (classDesc != null) {
                    if (classDesc.getJavaClass() != cls) {
                        classDesc = null;
                    }
                }
            } else {
                try {
                    if (cls.isArray()) {
                        state.setObject(new ArrayHandler(cls.getComponentType()));
                        cls = ArrayHandler.class;
                    } else {
                        Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                        state.setObject(_unmarshalHandler.createInstance(cls, args));
                        // state.object = _class.newInstance();
                    }
                } catch (java.lang.Exception ex) {
                    String err = MessageFormat.format(
                            resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"),
                            new Object[] { _unmarshalHandler.className(cls), ex.getMessage() });
                    throw new SAXException(err, ex);
                }
            }
        }
        state.setType(cls);
    } catch (java.lang.IllegalStateException ise) {
        LOG.error(ise.toString());
        throw new SAXException(ise);
    }

    // -- At this point we should have a new object, unless
    // -- we are dealing with a primitive type, or a special
    // -- case such as byte[]
    if (classDesc == null) {
        classDesc = _unmarshalHandler.getClassDescriptor(cls);
    }
    state.setClassDescriptor(classDesc);

    if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) {
        String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.unmarshal"),
                new Object[] { name, _unmarshalHandler.className(cls) });
        throw new SAXException(err);
    }

    // -- assign object, if incremental

    if (descriptor.isIncremental()) {
        if (LOG.isDebugEnabled()) {
            String debug = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.debug.process.incrementally"),
                    new Object[] { name });
            LOG.debug(debug);
        }
        try {
            handler.setValue(parentState.getObject(), state.getObject());
        } catch (java.lang.IllegalStateException ise) {
            String err = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.error.unable.add.element"),
                    new Object[] { name, parentState.getFieldDescriptor().getXMLName(), ise.getMessage() });
            throw new SAXException(err, ise);
        }
    }

    if (state.getObject() != null) {
        // --The object has just been initialized
        // --notify the listener
        Object stateObject = state.getObject();
        Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject();
        _unmarshalHandler.getDelegateUnmarshalListener().initialized(stateObject, parentObject);
        _unmarshalHandler.processAttributes(atts, classDesc);
        _unmarshalHandler.getDelegateUnmarshalListener().attributesProcessed(stateObject, parentObject);
        _unmarshalHandler.getNamespaceHandling().processNamespaces(classDesc,
                _unmarshalHandler.getStateStack().getLastState().getObject());
    } else if ((state.getType() != null) && (!state.isPrimitiveOrImmutable())) {
        if (atts != null) {
            _unmarshalHandler.processWrapperAttributes(atts);
            String warn = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.warn.process.attribute.as.location"),
                    new Object[] { name });
            LOG.warn(warn);
        }
    } else {
        // -- check for special attributes, such as xsi:nil
        if (atts != null) {
            String nil = atts.getValue(MarshalFramework.NIL_ATTR, MarshalFramework.XSI_NAMESPACE);
            state.setNil("true".equals(nil));
            _unmarshalHandler.processWrapperAttributes(atts);
        }
    }
}

From source file:javadz.beanutils.LazyDynaBean.java

/**
 * Create a new Instance of a 'Primitive' Property.
 * @param name The name of the property//from  w  w  w.j av  a  2 s .c  o m
 * @param type The class of the property
 * @return The new value
 */
protected Object createPrimitiveProperty(String name, Class type) {

    if (type == Boolean.TYPE) {
        return Boolean.FALSE;
    } else if (type == Integer.TYPE) {
        return Integer_ZERO;
    } else if (type == Long.TYPE) {
        return Long_ZERO;
    } else if (type == Double.TYPE) {
        return Double_ZERO;
    } else if (type == Float.TYPE) {
        return Float_ZERO;
    } else if (type == Byte.TYPE) {
        return Byte_ZERO;
    } else if (type == Short.TYPE) {
        return Short_ZERO;
    } else if (type == Character.TYPE) {
        return Character_SPACE;
    } else {
        return null;
    }

}

From source file:com.github.helenusdriver.driver.impl.DataTypeImpl.java

/**
 * Infers the data type for the specified field once it has already been
 * processed for optional and collections.
 *
 * @author paouelle//w w w .jav a  2 s . c  o m
 *
 * @param  field the non-<code>null</code> field to infer the CQL data type for
 * @param  clazz the non-<code>null</code> class for which to infer the CQL
 *         data type for the field
 * @param  types the non-<code>null</code> list where to add the inferred type and
 *         its arguments
 * @param  persisted the persisted annotation to consider for the field
 * @throws IllegalArgumentException if the data type cannot be inferred from
 *         the field
 */
private static void inferBasicDataTypeFrom(Field field, Class<?> clazz, List<CQLDataType> types,
        Persisted persisted) {
    if (persisted != null) {
        types.add(persisted.as());
    } else if (String.class == clazz) {
        types.add(DataType.TEXT);
    } else if (Integer.class == clazz) {
        types.add(DataType.INT);
    } else if (Long.class == clazz) {
        types.add(DataType.BIGINT);
    } else if (Boolean.class == clazz) {
        types.add(DataType.BOOLEAN);
    } else if (Date.class.isAssignableFrom(clazz)) {
        types.add(DataType.TIMESTAMP);
    } else if (Double.class == clazz) {
        types.add(DataType.DOUBLE);
    } else if (Float.class == clazz) {
        types.add(DataType.FLOAT);
    } else if (UUID.class.isAssignableFrom(clazz)) {
        types.add(DataType.UUID);
    } else if ((clazz.isArray() && (Byte.TYPE == clazz.getComponentType()))
            || ByteBuffer.class.isAssignableFrom(clazz)) {
        types.add(DataType.BLOB);
    } else if (BigDecimal.class.isAssignableFrom(clazz)) {
        types.add(DataType.DECIMAL);
    } else if (BigInteger.class.isAssignableFrom(clazz)) {
        types.add(DataType.VARINT);
    } else if (InetAddress.class.isAssignableFrom(clazz)) {
        types.add(DataType.INET);
    } else if (AtomicLong.class.isAssignableFrom(clazz)) {
        types.add(DataType.COUNTER);
    } else if (clazz.isEnum()) {
        types.add(DataType.ASCII);
    } else if (Class.class == clazz) {
        types.add(DataType.ASCII);
    } else if (Locale.class == clazz) {
        types.add(DataType.ASCII);
    } else if (ZoneId.class.isAssignableFrom(clazz)) {
        types.add(DataType.ASCII);
    } else if (Instant.class == clazz) {
        types.add(DataType.TIMESTAMP);
    } else {
        // check if it is a user-defined type
        try {
            final ClassInfoImpl<?> cinfo = (ClassInfoImpl<?>) StatementBuilder.getClassInfo(clazz);

            org.apache.commons.lang3.Validate.isTrue(cinfo instanceof UDTClassInfoImpl,
                    "unable to infer data type in field: %s", field);
            types.add((UDTClassInfoImpl<?>) cinfo);
        } catch (Exception e) {
            throw new IllegalArgumentException("unable to infer data type in field: " + field, e);
        }
    }
}