Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

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

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:mondrian.olap.Util.java

/**
 * Copies the specified array.// w  ww  .ja  v  a  2s  .c o m
 *
 * @param original the array to be copied
 * @param newLength the length of the copy to be returned
 * @param newType the class of the copy to be returned
 * @return a copy of the original array, truncated or padded with nulls
 *     to obtain the specified length
 */
public static <T, U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
    @SuppressWarnings({ "unchecked", "RedundantCast" })
    T[] copy = ((Object) newType == (Object) Object[].class) ? (T[]) new Object[newLength]
            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
    //noinspection SuspiciousSystemArraycopy
    System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));
    return copy;
}

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

public void compute(String name) throws org.xml.sax.SAXException {
    if (LOG.isTraceEnabled()) {
        String trace = MessageFormat.format(resourceBundle.getString("unmarshalHandler.log.trace.endElement"),
                new Object[] { name });
        LOG.trace(trace);// w w w  . ja va 2  s  .co  m
    }

    // -- If we are skipping elements that have appeared in the XML but for
    // -- which we have no mapping, decrease the ignore depth counter and
    // return
    if (_unmarshalHandler.getStrictElementHandler().skipEndElement()) {
        return;
    }

    // -- Do delagation if necessary
    if (_unmarshalHandler.getAnyNodeHandler().hasAnyUnmarshaller()) {
        _unmarshalHandler.getAnyNodeHandler().endElement(name);
        // we are back to the starting node
        if (_unmarshalHandler.getAnyNodeHandler().isStartingNode()) {
            _unmarshalHandler.setAnyNode(_unmarshalHandler.getAnyNodeHandler().getStartingNode());
        } else
            return;
    }

    if (_unmarshalHandler.getStateStack().isEmpty()) {
        String err = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.missing.startElement"), new Object[] { name });
        throw new SAXException(err);
    }

    // -- * Begin Namespace Handling
    // -- XXX Note: This code will change when we update the XML event API

    int idx = name.indexOf(':');
    if (idx >= 0) {
        name = name.substring(idx + 1);
    }
    // -- * End Namespace Handling

    UnmarshalState state = _unmarshalHandler.getStateStack().removeLastState();

    // -- make sure we have the correct closing tag
    XMLFieldDescriptor descriptor = state.getFieldDescriptor();

    if (!state.getElementName().equals(name)) {

        // maybe there is still a container to end
        if (descriptor.isContainer()) {
            _unmarshalHandler.getStateStack().pushState(state);
            // -- check for possible characters added to
            // -- the container's state that should
            // -- really belong to the parent state
            StringBuffer tmpBuffer = null;
            if (state.getBuffer() != null) {
                if (!UnmarshalHandler.isWhitespace(state.getBuffer())) {
                    if (state.getClassDescriptor().getContentDescriptor() == null) {
                        tmpBuffer = state.getBuffer();
                        state.setBuffer(null);
                    }
                }
            }
            // -- end container
            _unmarshalHandler.endElement(state.getElementName());

            if (tmpBuffer != null) {
                state = _unmarshalHandler.getStateStack().getLastState();
                if (state.getBuffer() == null)
                    state.setBuffer(tmpBuffer);
                else
                    state.getBuffer().append(tmpBuffer.toString());
            }
            _unmarshalHandler.endElement(name);
            return;
        }
        String err = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.different.endElement.expected"),
                new Object[] { state.getElementName(), name });
        throw new SAXException(err);
    }

    // -- clean up current Object
    Class<?> type = state.getType();

    if (type == null) {
        if (!state.isWrapper()) {
            // -- this message will only show up if debug
            // -- is turned on...how should we handle this case?
            // -- should it be a fatal error?
            String info = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.info.no.Descriptor.found"),
                    new Object[] { state.getElementName() });
            LOG.info(info);
        }

        // -- handle possible location text content
        // -- TODO: cleanup location path support.
        // -- the following code needs to be improved as
        // -- for searching descriptors in this manner can
        // -- be slow
        StringBuffer tmpBuffer = null;
        if (state.getBuffer() != null) {
            if (!UnmarshalHandler.isWhitespace(state.getBuffer())) {
                tmpBuffer = state.getBuffer();
                state.setBuffer(null);
            }
        }
        if (tmpBuffer != null) {
            UnmarshalState targetState = state;
            String locPath = targetState.getElementName();
            while ((targetState = targetState.getParent()) != null) {
                if ((targetState.isWrapper()) || (targetState.getClassDescriptor() == null)) {
                    locPath = targetState.getElementName() + "/" + locPath;
                    continue;
                }

                XMLFieldDescriptor tmpDesc = targetState.getClassDescriptor().getContentDescriptor();
                if (tmpDesc != null && locPath.equals(tmpDesc.getLocationPath())) {
                    if (targetState.getBuffer() == null)
                        targetState.setBuffer(tmpBuffer);
                    else
                        targetState.getBuffer().append(tmpBuffer.toString());
                }
            }
        }

        // -- remove current namespace scoping
        _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
        return;
    }

    // -- check for special cases
    boolean byteArray = false;
    if (type.isArray()) {
        byteArray = (type.getComponentType() == Byte.TYPE);
    }

    // -- If we don't have an instance object and the Class type
    // -- is not a primitive or a byte[] we must simply return
    if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) {
        // -- remove current namespace scoping
        _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
        return;
    }

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

    if (state.isPrimitiveOrImmutable()) {

        String str = null;

        if (state.getBuffer() != null) {
            str = state.getBuffer().toString();
            state.getBuffer().setLength(0);
        }

        if (type == String.class && !((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
            if (str != null)
                state.setObject(str);
            else if (state.isNil()) {
                state.setObject(null);
            } else {
                state.setObject("");
            }
        }
        // -- special handling for byte[]
        else if (byteArray && !descriptor.isDerivedFromXSList()) {
            if (str == null)
                state.setObject(new byte[0]);
            else {
                state.setObject(_unmarshalHandler.decodeBinaryData(descriptor, str));
            }
        } else if (state.getConstructorArguments() != null) {
            state.setObject(_unmarshalHandler.createInstance(state.getType(), state.getConstructorArguments()));
        } else if (descriptor.isMultivalued() && descriptor.getSchemaType() != null
                && descriptor.getSchemaType().equals("list")
                && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
            StringTokenizer attrValueTokenizer = new StringTokenizer(str);
            List<Object> primitives = new ArrayList<Object>();
            while (attrValueTokenizer.hasMoreTokens()) {
                String tokenValue = attrValueTokenizer.nextToken();
                if (MarshalFramework.isPrimitive(descriptor.getFieldType())) {
                    primitives.add(
                            _unmarshalHandler.toPrimitiveObject(type, tokenValue, state.getFieldDescriptor()));
                } else {
                    Class<?> valueType = descriptor.getFieldType();
                    // -- handle base64/hexBinary
                    if (valueType.isArray() && (valueType.getComponentType() == Byte.TYPE)) {
                        primitives.add(_unmarshalHandler.decodeBinaryData(descriptor, tokenValue));
                    }
                }

            }
            state.setObject(primitives);
        } else {
            if (state.isNil()) {
                state.setObject(null);
            } else {
                state.setObject(_unmarshalHandler.toPrimitiveObject(type, str, state.getFieldDescriptor()));
            }
        }
    } else if (ArrayHandler.class.isAssignableFrom(state.getType())) {
        state.setObject(((ArrayHandler) state.getObject()).getObject());
        state.setType(state.getObject().getClass());

    }

    // -- check for character content
    if ((state.getBuffer() != null) && (state.getBuffer().length() > 0)
            && (state.getClassDescriptor() != null)) {
        XMLFieldDescriptor cdesc = state.getClassDescriptor().getContentDescriptor();
        if (cdesc != null) {
            Object value = state.getBuffer().toString();
            if (MarshalFramework.isPrimitive(cdesc.getFieldType()))
                value = _unmarshalHandler.toPrimitiveObject(cdesc.getFieldType(), (String) value,
                        state.getFieldDescriptor());
            else {
                Class<?> valueType = cdesc.getFieldType();
                // -- handle base64/hexBinary
                if (valueType.isArray() && (valueType.getComponentType() == Byte.TYPE)) {
                    value = _unmarshalHandler.decodeBinaryData(descriptor, (String) value);
                }
            }

            try {
                FieldHandler handler = cdesc.getHandler();
                boolean addObject = true;
                if (_unmarshalHandler.isReuseObjects()) {
                    // -- check to see if we need to
                    // -- add the object or not
                    Object tmp = handler.getValue(state.getObject());
                    if (tmp != null) {
                        // -- Do not add object if values
                        // -- are equal
                        addObject = (!tmp.equals(value));
                    }
                }
                if (addObject)
                    handler.setValue(state.getObject(), value);
            } catch (java.lang.IllegalStateException ise) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.unable.add.text"),
                        new Object[] { descriptor.getXMLName(), ise.toString() });
                throw new SAXException(err, ise);
            }
        }
        // -- Handle references
        else if (descriptor.isReference()) {
            UnmarshalState pState = _unmarshalHandler.getStateStack().getLastState();
            _unmarshalHandler.processIDREF(state.getBuffer().toString(), descriptor, pState.getObject());
            _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
            return;
        } else {
            // -- check for non-whitespace...and report error
            if (!UnmarshalHandler.isWhitespace(state.getBuffer())) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.illegal.text"),
                        new Object[] { name, state.getBuffer() });
                throw new SAXException(err);
            }
        }
    }

    // -- We're finished processing the object, so notify the
    // -- Listener (if any).
    Object stateObject = state.getObject();
    Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject();
    _unmarshalHandler.getDelegateUnmarshalListener().unmarshalled(stateObject, parentObject);

    // -- if we are at root....just validate and we are done
    if (_unmarshalHandler.getStateStack().isEmpty()) {
        if (_unmarshalHandler.isValidating()) {
            ValidationException first = null;
            ValidationException last = null;

            // -- check unresolved references
            if (_unmarshalHandler.getResolveTable() != null
                    && !_unmarshalHandler.getInternalContext().getLenientIdValidation()) {
                Enumeration enumeration = _unmarshalHandler.getResolveTable().keys();
                while (enumeration.hasMoreElements()) {
                    Object ref = enumeration.nextElement();
                    // if
                    // (ref.toString().startsWith(MapItem.class.getName()))
                    // continue;
                    String msg = "unable to resolve reference: " + ref;
                    if (first == null) {
                        first = new ValidationException(msg);
                        last = first;
                    } else {
                        last.setNext(new ValidationException(msg));
                        last = last.getNext();
                    }
                }
            }
            try {
                Validator validator = new Validator();
                ValidationContext context = new ValidationContext();
                context.setInternalContext(_unmarshalHandler.getInternalContext());
                validator.validate(state.getObject(), context);
                if (!_unmarshalHandler.getInternalContext().getLenientIdValidation()) {
                    validator.checkUnresolvedIdrefs(context);
                }
                context.cleanup();
            } catch (ValidationException vEx) {
                if (first == null)
                    first = vEx;
                else
                    last.setNext(vEx);
            }
            if (first != null) {
                throw new SAXException(first);
            }
        }
        return;
    }

    // -- Add object to parent if necessary

    if (descriptor.isIncremental()) {
        // -- remove current namespace scoping
        _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
        return; // -- already added
    }

    Object val = state.getObject();

    // --special code for AnyNode handling
    if (_unmarshalHandler.getAnyNode() != null) {
        val = _unmarshalHandler.getAnyNode();
        _unmarshalHandler.setAnyNode(null);
    }

    // -- save fieldState
    UnmarshalState fieldState = state;

    // -- have we seen this object before?
    boolean firstOccurance = false;

    // -- get target object
    state = _unmarshalHandler.getStateStack().getLastState();
    if (state.isWrapper()) {
        state = fieldState.getTargetState();
    }

    // -- check to see if we have already read in
    // -- an element of this type.
    // -- (Q: if we have a container, do we possibly need to
    // -- also check the container's multivalued status?)
    if (!descriptor.isMultivalued()) {

        if (state.isUsed(descriptor)) {

            String location = name;
            while (!_unmarshalHandler.getStateStack().isEmpty()) {
                UnmarshalState tmpState = _unmarshalHandler.getStateStack().removeLastState();
                if (!tmpState.isWrapper()) {
                    if (tmpState.getFieldDescriptor().isContainer())
                        continue;
                }
                location = state.getElementName() + "/" + location;
            }

            String err = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.error.element.occurs.more.than.once"),
                    new Object[] { name, state.getType().getName(), location });

            ValidationException vx = new ValidationException(err);

            throw new SAXException(vx);
        }
        state.markAsUsed(descriptor);
        // -- if this is the identity then save id
        if (state.getClassDescriptor().getIdentity() == descriptor) {
            state.setKey(val);
        }
    } else {
        // -- check occurance of descriptor
        if (!state.isUsed(descriptor)) {
            firstOccurance = true;
        }

        // -- record usage of descriptor
        state.markAsUsed(descriptor);
    }

    try {
        FieldHandler handler = descriptor.getHandler();
        // check if the value is a QName that needs to
        // be resolved (ns:value -> {URI}value)
        String valueType = descriptor.getSchemaType();
        if ((valueType != null) && (valueType.equals(MarshalFramework.QNAME_NAME))) {
            val = _unmarshalHandler.getNamespaceHandling().resolveNamespace(val);
        }

        boolean addObject = true;
        if (_unmarshalHandler.isReuseObjects() && fieldState.isPrimitiveOrImmutable()) {
            // -- check to see if we need to
            // -- add the object or not
            Object tmp = handler.getValue(state.getObject());
            if (tmp != null) {
                // -- Do not add object if values
                // -- are equal
                addObject = (!tmp.equals(val));
            }
        }

        // -- special handling for mapped objects
        if (descriptor.isMapped()) {
            if (!(val instanceof MapItem)) {
                MapItem mapItem = new MapItem(fieldState.getKey(), val);
                val = mapItem;
            } else {
                // -- make sure value exists (could be a reference)
                MapItem mapItem = (MapItem) val;
                if (mapItem.getValue() == null) {
                    // -- save for later...
                    addObject = false;
                    _unmarshalHandler.addReference(mapItem.toString(), state.getObject(), descriptor);
                }
            }
        }

        if (addObject) {
            // -- clear any collections if necessary
            if (firstOccurance && _unmarshalHandler.isClearCollections()) {
                handler.resetValue(state.getObject());
            }

            if (descriptor.isMultivalued() && descriptor.getSchemaType() != null
                    && descriptor.getSchemaType().equals("list")
                    && ((XMLFieldDescriptorImpl) descriptor).isDerivedFromXSList()) {
                List<Object> values = (List<Object>) val;
                for (Object value : values) {
                    // -- finally set the value!!
                    handler.setValue(state.getObject(), value);

                    // If there is a parent for this object, pass along
                    // a notification that we've finished adding a child
                    _unmarshalHandler.getDelegateUnmarshalListener().fieldAdded(descriptor.getFieldName(),
                            state.getObject(), fieldState.getObject());
                }
            } else {

                // -- finally set the value!!
                handler.setValue(state.getObject(), val);

                // If there is a parent for this object, pass along
                // a notification that we've finished adding a child
                _unmarshalHandler.getDelegateUnmarshalListener().fieldAdded(descriptor.getFieldName(),
                        state.getObject(), fieldState.getObject());
            }
        }

    }
    /*
     * catch(java.lang.reflect.InvocationTargetException itx) {
     * 
     * Throwable toss = itx.getTargetException(); if (toss == null) toss = itx;
     * 
     * String err = "unable to add '" + name + "' to <"; err += state.descriptor.getXMLName(); err
     * += "> due to the following exception: " + toss; throw new SAXException(err); }
     */
    catch (Exception ex) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        pw.flush();
        String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.add.element"),
                new Object[] { name, state.getFieldDescriptor().getXMLName(), sw.toString() });
        throw new SAXException(err, ex);
    }

    // -- remove current namespace scoping
    _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();

    // remove additional (artifical aka container) state introduced for
    // single-valued (iow maxOccurs="1") choices.
    if (state.getFieldDescriptor().isContainer() && state.getClassDescriptor().isChoice()
            && !state.getFieldDescriptor().isMultivalued()) {
        _unmarshalHandler.endElement(state.getElementName());
    }

}

From source file:me.rojo8399.placeholderapi.impl.utils.TypeUtils.java

@SuppressWarnings("unchecked")
public static <T> Optional<T> tryCast(Object val, final Class<T> expected) {
    if (val == null) {
        return Optional.empty();
    }/*from  www.j  av  a 2s. c  o m*/
    if (expected == null) {
        throw new IllegalArgumentException("Must provide an expected class!");
    }
    if (val instanceof BaseValue<?> && !BaseValue.class.isAssignableFrom(expected)) {
        return tryCast(((BaseValue<?>) val).get(), expected);
    }
    if (val instanceof Supplier) {
        Supplier<?> fun = (Supplier<?>) val;
        return tryCast(fun.get(), expected);
    }
    if (Text.class.isAssignableFrom(expected)) {
        if (val instanceof Text) {
            return TypeUtils.tryOptional(() -> expected.cast(val));
        } else {
            if (val instanceof ItemStack) {
                return TypeUtils.tryOptional(() -> expected.cast(TextUtils.ofItem((ItemStack) val)));
            }
            if (val instanceof Instant) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(PlaceholderAPIPlugin.getInstance().formatter()
                                .format(LocalDateTime.ofInstant((Instant) val, ZoneId.systemDefault())))));
            }
            if (val instanceof Duration) {
                String dur = formatDuration((Duration) val);
                return TypeUtils
                        .tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(dur)));
            }
            if (val instanceof LocalDateTime) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(
                        PlaceholderAPIPlugin.getInstance().formatter().format((LocalDateTime) val))));
            }
            if (val instanceof CommandSource) {
                return TypeUtils.tryOptional(() -> expected.cast(TextSerializers.FORMATTING_CODE
                        .deserialize(String.valueOf(((CommandSource) val).getName()))));
            }
            if (val.getClass().isArray()) {
                List<Text> l2 = unboxPrimitiveArray(val).stream()
                        .map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            if (val instanceof Iterable) {
                Iterable<?> l = (Iterable<?>) val;
                // should be safe cause we already checked assignability
                @SuppressWarnings("serial")
                final List<Text> l2 = new ArrayList<Object>() {
                    {
                        for (Object o : l) {
                            add(o);
                        }
                    }
                }.stream().map(o -> tryCast(o, (Class<? extends Text>) expected)).flatMap(unmapOptional())
                        .collect(Collectors.toList());
                return TypeUtils.tryOptional(() -> expected.cast(Text.joinWith(Text.of(", "), l2)));
            }
            return TypeUtils.tryOptional(
                    () -> expected.cast(TextSerializers.FORMATTING_CODE.deserialize(String.valueOf(val))));
        }
    }
    if (val instanceof String) {
        if (String.class.isAssignableFrom(expected)) {
            return tryOptional(() -> expected.cast(val));
        }
        if (expected.isArray() && String.class.isAssignableFrom(expected.getComponentType())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(new String[] { v }));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(x));
        }
        if (List.class.isAssignableFrom(expected)
                && String.class.isAssignableFrom(expected.getTypeParameters()[0].getGenericDeclaration())) {
            String v = (String) val;
            if (v.isEmpty()) {
                return Optional.empty();
            }
            if (!v.contains("_")) {
                return tryOptional(() -> expected.cast(Collections.singletonList(v)));
            }
            String[] x = v.split("_");
            if (x.length == 0) {
                return Optional.empty();
            }
            boolean ne = false;
            for (String s : x) {
                ne = ne || !s.isEmpty();
            }
            if (!ne) {
                return Optional.empty();
            }
            return tryOptional(() -> expected.cast(Arrays.asList(x)));
        }
        Optional<T> opt = tryOptional(() -> convertPrimitive((String) val, expected));
        if (opt.isPresent()) {
            return opt;
        }
        opt = deserializers.entrySet().stream()
                .filter(e -> e.getKey().isSubtypeOf(expected) || e.getKey().getRawType().equals(expected))
                .map(Map.Entry::getValue).map(f -> tryOptional(() -> f.apply((String) val)))
                .flatMap(unmapOptional()).findAny().flatMap(o -> tryOptional(() -> expected.cast(o)));
        if (opt.isPresent()) {
            return opt;
        }
        try {
            // should theoretically match any string -> object conversions, such as deser

            // for now im filtering against method names as well just to avoid issues where
            // expected result is not obtained due to weird methods, might change in future
            Method method = Arrays.stream(expected.getDeclaredMethods())
                    .filter(m -> Modifier.isStatic(m.getModifiers()) && Modifier.isPublic(m.getModifiers()))
                    .filter(m -> Arrays.stream(m.getParameterTypes()).anyMatch(c -> c.equals(String.class)))
                    .filter(m -> m.getReturnType().equals(expected) || m.getReturnType().equals(Optional.class))
                    .filter(m -> STRING_TO_VAL_PATTERN.matcher(m.getName()).find()).findAny().get(); // error if no
            Object valout = method.invoke(null, (String) val);
            if (valout == null) {
                return Optional.empty();
            }
            if (expected.isInstance(valout)) {
                // Register a new deserializer once we confirm it works. Should prevent
                // extremely long parsing from happening multiple times.
                final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                    try {
                        return expected.cast(mh.invokeExact((String) val));
                    } catch (Throwable e1) {
                        throw new RuntimeException(e1);
                    }
                });
                return tryOptional(() -> expected.cast(valout));
            }
            if (valout instanceof Optional) {
                Optional<?> valopt = (Optional<?>) valout;
                if (!valopt.isPresent()) {
                    return Optional.empty();
                }
                Object v = valopt.get();
                if (expected.isInstance(v)) {
                    // Register a new deserializer once we confirm it works. Should prevent
                    // extremely long parsing from happening multiple times.
                    final MethodHandle mh = MethodHandles.publicLookup().unreflect(method);
                    PlaceholderServiceImpl.get().registerTypeDeserializer(TypeToken.of(expected), str -> {
                        try {
                            Optional<?> optx = (Optional<?>) mh.invokeExact((String) val);
                            return expected.cast(optx.get());
                        } catch (Throwable e1) {
                            throw new RuntimeException(e1);
                        }
                    });
                    return tryOptional(() -> expected.cast(v));
                } else {
                    return Optional.empty();
                }
            }
            return Optional.empty();
        } catch (Exception e) {
            // fires if no method found, if invoke throws, if something else goes wrong
            return Optional.empty();
        }
    }
    return TypeUtils.tryOptional(() -> expected.cast(val));
}

From source file:org.apache.axis2.jaxws.utility.ConvertUtils.java

/**
 * Utility function to convert an Object to some desired Class.
 * <p/>//from  w w  w  .j  a v a2 s .c o  m
 * Normally this is used for T[] to List<T> processing. Other conversions are also done (i.e.
 * HashMap <->Hashtable, etc.)
 * <p/>
 * Use the isConvertable() method to determine if conversion is possible. Note that any changes
 * to convert() must also be accompanied by similar changes to isConvertable()
 *
 * @param arg       the array to convert
 * @param destClass the actual class we want
 * @return object of destClass if conversion possible, otherwise returns arg
 */
public static Object convert(Object arg, Class destClass) throws WebServiceException {
    if (destClass == null) {
        return arg;
    }

    if (arg != null && destClass.isAssignableFrom(arg.getClass())) {
        return arg;
    }

    if (log.isDebugEnabled()) {
        String clsName = "null";
        if (arg != null)
            clsName = arg.getClass().getName();
        log.debug("Converting an object of type " + clsName + " to an object of type " + destClass.getName());
    }

    // Convert between Calendar and Date
    if (arg instanceof Calendar && destClass == Date.class) {
        return ((Calendar) arg).getTime();
    }

    // Convert between HashMap and Hashtable
    if (arg instanceof HashMap && destClass == Hashtable.class) {
        return new Hashtable((HashMap) arg);
    }

    if (arg instanceof InputStream && destClass == byte[].class) {

        try {
            InputStream is = (InputStream) arg;
            return getBytesFromStream(is);
        } catch (IOException e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    if (arg instanceof Source && destClass == byte[].class) {
        try {
            if (arg instanceof StreamSource) {
                InputStream is = ((StreamSource) arg).getInputStream();
                if (is != null) {
                    return getBytesFromStream(is);
                }
            }
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            Result result = new StreamResult(out);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.transform((Source) arg, result);
            byte[] bytes = out.toByteArray();
            return bytes;

        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    if (arg instanceof DataHandler) {
        try {
            InputStream is = ((DataHandler) arg).getInputStream();
            if (destClass == Image.class) {
                return ImageIO.read(is);
            } else if (destClass == Source.class) {
                return new StreamSource(is);
            }
            byte[] bytes = getBytesFromStream(is);
            return convert(bytes, destClass);
        } catch (Exception e) {
            throw ExceptionFactory.makeWebServiceException(e);
        }
    }

    if (arg instanceof byte[] && destClass == String.class) {
        return new String((byte[]) arg);
    }

    // If the destination is an array and the source
    // is a suitable component, return an array with 
    // the single item.
    /* REVIEW do we need to support atomic to array conversion ?
    if (arg != null &&
    destClass.isArray() &&
    !destClass.getComponentType().equals(Object.class) &&
    destClass.getComponentType().isAssignableFrom(arg.getClass())) {
    Object array = 
        Array.newInstance(destClass.getComponentType(), 1);
    Array.set(array, 0, arg);
    return array;
    }
    */

    // Return if no conversion is available
    if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))) {
        return arg;
    }

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

    // The arg may be an array or List 
    Object destValue = null;
    int length = 0;
    if (arg.getClass().isArray()) {
        length = Array.getLength(arg);
    } else {
        length = ((Collection) arg).size();
    }

    try {
        if (destClass.isArray()) {
            if (destClass.getComponentType().isPrimitive()) {

                Object array = Array.newInstance(destClass.getComponentType(), length);
                // Assign array elements
                if (arg.getClass().isArray()) {
                    for (int i = 0; i < length; i++) {
                        Array.set(array, i, Array.get(arg, i));
                    }
                } else {
                    int idx = 0;
                    for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                        Array.set(array, idx++, i.next());
                    }
                }
                destValue = array;

            } else {
                Object[] array;
                try {
                    array = (Object[]) Array.newInstance(destClass.getComponentType(), length);
                } catch (Exception e) {
                    return arg;
                }

                // Use convert to assign array elements.
                if (arg.getClass().isArray()) {
                    for (int i = 0; i < length; i++) {
                        array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                    }
                } else {
                    int idx = 0;
                    for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                        array[idx++] = convert(i.next(), destClass.getComponentType());
                    }
                }
                destValue = array;
            }
        } else if (Collection.class.isAssignableFrom(destClass)) {
            Collection newList = null;
            try {
                // if we are trying to create an interface, build something
                // that implements the interface
                if (destClass == Collection.class || destClass == List.class) {
                    newList = new ArrayList();
                } else if (destClass == Set.class) {
                    newList = new HashSet();
                } else {
                    newList = (Collection) destClass.newInstance();
                }
            } catch (Exception e) {
                // No FFDC code needed
                // Couldn't build one for some reason... so forget it.
                return arg;
            }

            if (arg.getClass().isArray()) {
                for (int j = 0; j < length; j++) {
                    newList.add(Array.get(arg, j));
                }
            } else {
                for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) {
                    newList.add(j.next());
                }
            }
            destValue = newList;
        } else {
            destValue = arg;
        }
    } catch (Throwable t) {
        throw ExceptionFactory.makeWebServiceException(
                Messages.getMessage("convertUtils", arg.getClass().toString(), destClass.toString()), t);
    }

    return destValue;
}

From source file:org.gameye.psp.image.utils.TBeanUtilsBean.java

public void copyProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  copyProperty(");
        sb.append(bean);/*from   w w w  . j a v  a2 s .  com*/
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = name.lastIndexOf(PropertyUtils.NESTED_DELIM);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the target property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the target property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        type = descriptor.getPropertyType();
        if (type == null) {
            // Most likely an indexed setter on a POJB only
            if (log.isTraceEnabled()) {
                log.trace("    target type for property '" + propName + "' is null, so skipping ths setter");
            }
            return;
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key);
    }

    // Convert the specified value to the required type and store it
    if (index >= 0) { // Destination must be indexed
        Converter converter = getConvertUtils().lookup(type.getComponentType());
        if (converter != null) {
            log.trace("        USING CONVERTER " + converter);
            value = converter.convert(type, value);
        }
        try {
            getPropertyUtils().setIndexedProperty(target, propName, index, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    } else if (key != null) { // Destination must be mapped
        // Maps do not know what the preferred data type is,
        // so perform no conversions at all
        // FIXME - should we create or support a TypedMap?
        try {
            getPropertyUtils().setMappedProperty(target, propName, key, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    } else { // Destination must be simple
        Converter converter = getConvertUtils().lookup(type);
        if (converter != null) {
            log.trace("        USING CONVERTER " + converter);
            value = converter.convert(type, value);
        }
        try {
            getPropertyUtils().setSimpleProperty(target, propName, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    }

}

From source file:org.broadinstitute.sting.commandline.ArgumentTypeDescriptor.java

@Override
@SuppressWarnings("unchecked")
public Object parse(ParsingEngine parsingEngine, ArgumentSource source, Type fulltype,
        ArgumentMatches matches) {//from   ww w. jav a 2  s  . c o m
    Class type = makeRawTypeIfNecessary(fulltype);
    Type componentType;
    Object result;

    if (Collection.class.isAssignableFrom(type)) {

        // If this is a generic interface, pick a concrete implementation to create and pass back.
        // Because of type erasure, don't worry about creating one of exactly the correct type.
        if (Modifier.isInterface(type.getModifiers()) || Modifier.isAbstract(type.getModifiers())) {
            if (java.util.List.class.isAssignableFrom(type))
                type = ArrayList.class;
            else if (java.util.Queue.class.isAssignableFrom(type))
                type = java.util.ArrayDeque.class;
            else if (java.util.Set.class.isAssignableFrom(type))
                type = java.util.TreeSet.class;
        }

        componentType = getCollectionComponentType(source.field);
        ArgumentTypeDescriptor componentArgumentParser = parsingEngine
                .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));

        Collection collection;
        try {
            collection = (Collection) type.newInstance();
        } catch (InstantiationException e) {
            logger.fatal(
                    "ArgumentParser: InstantiationException: cannot convert field " + source.field.getName());
            throw new ReviewedStingException(
                    "constructFromString:InstantiationException: Failed conversion " + e.getMessage());
        } catch (IllegalAccessException e) {
            logger.fatal(
                    "ArgumentParser: IllegalAccessException: cannot convert field " + source.field.getName());
            throw new ReviewedStingException(
                    "constructFromString:IllegalAccessException: Failed conversion " + e.getMessage());
        }

        for (ArgumentMatch match : matches) {
            for (ArgumentMatch value : match) {
                Object object = componentArgumentParser.parse(parsingEngine, source, componentType,
                        new ArgumentMatches(value));
                collection.add(object);
                // WARNING: Side effect!
                parsingEngine.addTags(object, value.tags);
            }
        }

        result = collection;

    } else if (type.isArray()) {
        componentType = type.getComponentType();
        ArgumentTypeDescriptor componentArgumentParser = parsingEngine
                .selectBestTypeDescriptor(makeRawTypeIfNecessary(componentType));

        // Assemble a collection of individual values used in this computation.
        Collection<ArgumentMatch> values = new ArrayList<ArgumentMatch>();
        for (ArgumentMatch match : matches)
            for (ArgumentMatch value : match)
                values.add(value);

        result = Array.newInstance(makeRawTypeIfNecessary(componentType), values.size());

        int i = 0;
        for (ArgumentMatch value : values) {
            Object object = componentArgumentParser.parse(parsingEngine, source, componentType,
                    new ArgumentMatches(value));
            Array.set(result, i++, object);
            // WARNING: Side effect!
            parsingEngine.addTags(object, value.tags);
        }
    } else
        throw new ReviewedStingException("Unsupported compound argument type: " + type);

    return result;
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorInstanceIcfImpl.java

private QName icfTypeToXsdType(Class<?> type, boolean isConfidential) {
    // For arrays we are only interested in the component type
    if (isMultivaluedType(type)) {
        type = type.getComponentType();
    }/*from  w ww  . j  a v a 2s.  c o m*/
    QName propXsdType = null;
    if (GuardedString.class.equals(type) || (String.class.equals(type) && isConfidential)) {
        // GuardedString is a special case. It is a ICF-specific
        // type
        // implementing Potemkin-like security. Use a temporary
        // "nonsense" type for now, so this will fail in tests and
        // will be fixed later
        //         propXsdType = SchemaConstants.T_PROTECTED_STRING_TYPE;
        propXsdType = ProtectedStringType.COMPLEX_TYPE;
    } else if (GuardedByteArray.class.equals(type) || (Byte.class.equals(type) && isConfidential)) {
        // GuardedString is a special case. It is a ICF-specific
        // type
        // implementing Potemkin-like security. Use a temporary
        // "nonsense" type for now, so this will fail in tests and
        // will be fixed later
        //         propXsdType = SchemaConstants.T_PROTECTED_BYTE_ARRAY_TYPE;
        propXsdType = ProtectedByteArrayType.COMPLEX_TYPE;
    } else {
        propXsdType = XsdTypeMapper.toXsdType(type);
    }
    return propXsdType;
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorInstanceIcfImpl.java

private void transformConnectorConfiguration(ConfigurationProperties configProps,
        PrismContainer<?> configurationPropertiesContainer, String connectorConfNs)
        throws ConfigurationException, SchemaException {

    if (configurationPropertiesContainer == null || configurationPropertiesContainer.getValue() == null) {
        throw new SchemaException("No configuration properties container in " + connectorType);
    }// ww w.  j ava2 s.c  o m

    int numConfingProperties = 0;
    List<QName> wrongNamespaceProperties = new ArrayList<>();

    for (PrismProperty prismProperty : configurationPropertiesContainer.getValue().getProperties()) {
        QName propertyQName = prismProperty.getElementName();

        // All the elements must be in a connector instance
        // namespace.
        if (propertyQName.getNamespaceURI() == null
                || !propertyQName.getNamespaceURI().equals(connectorConfNs)) {
            LOGGER.warn("Found element with a wrong namespace ({}) in {}", propertyQName.getNamespaceURI(),
                    connectorType);
            wrongNamespaceProperties.add(propertyQName);
        } else {

            numConfingProperties++;

            // Local name of the element is the same as the name
            // of ICF configuration property
            String propertyName = propertyQName.getLocalPart();
            ConfigurationProperty property = configProps.getProperty(propertyName);

            if (property == null) {
                throw new ConfigurationException("Unknown configuration property " + propertyName);
            }

            // Check (java) type of ICF configuration property,
            // behave accordingly
            Class<?> type = property.getType();
            if (type.isArray()) {
                property.setValue(convertToIcfArray(prismProperty, type.getComponentType()));
                // property.setValue(prismProperty.getRealValuesArray(type.getComponentType()));
            } else {
                // Single-valued property are easy to convert
                property.setValue(convertToIcfSingle(prismProperty, type));
                // property.setValue(prismProperty.getRealValue(type));
            }
        }
    }
    // empty configuration is OK e.g. when creating a new resource using wizard
    if (numConfingProperties == 0 && !wrongNamespaceProperties.isEmpty()) {
        throw new SchemaException("No configuration properties found. Wrong namespace? (expected: "
                + connectorConfNs + ", present e.g. " + wrongNamespaceProperties.get(0) + ")");
    }
}

From source file:org.enerj.apache.commons.beanutils.BeanUtilsBean.java

/**
 * <p>Copy the specified property value to the specified destination bean,
 * performing any type conversion that is required.  If the specified
 * bean does not have a property of the specified name, or the property
 * is read only on the destination bean, return without
 * doing anything.  If you have custom destination property types, register
 * {@link Converter}s for them by calling the <code>register()</code>
 * method of {@link ConvertUtils}.</p>
 *
 * <p><strong>IMPLEMENTATION RESTRICTIONS</strong>:</p>
 * <ul>/*from   ww w .j  a v  a  2s.  co  m*/
 * <li>Does not support destination properties that are indexed,
 *     but only an indexed setter (as opposed to an array setter)
 *     is available.</li>
 * <li>Does not support destination properties that are mapped,
 *     but only a keyed setter (as opposed to a Map setter)
 *     is available.</li>
 * <li>The desired property type of a mapped setter cannot be
 *     determined (since Maps support any data type), so no conversion
 *     will be performed.</li>
 * </ul>
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void copyProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  copyProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = name.lastIndexOf(PropertyUtils.NESTED_DELIM);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the target property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the target property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        type = descriptor.getPropertyType();
        if (type == null) {
            // Most likely an indexed setter on a POJB only
            if (log.isTraceEnabled()) {
                log.trace("    target type for property '" + propName + "' is null, so skipping ths setter");
            }
            return;
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    target propName=" + propName + ", type=" + type + ", index=" + index + ", key=" + key);
    }

    // Convert the specified value to the required type and store it
    if (index >= 0) { // Destination must be indexed
        Converter converter = getConvertUtils().lookup(type.getComponentType());
        if (converter != null) {
            log.trace("        USING CONVERTER " + converter);
            value = converter.convert(type, value);
        }
        try {
            getPropertyUtils().setIndexedProperty(target, propName, index, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    } else if (key != null) { // Destination must be mapped
        // Maps do not know what the preferred data type is,
        // so perform no conversions at all
        // FIXME - should we create or support a TypedMap?
        try {
            getPropertyUtils().setMappedProperty(target, propName, key, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    } else { // Destination must be simple
        Converter converter = getConvertUtils().lookup(type);
        if (converter != null) {
            log.trace("        USING CONVERTER " + converter);
            value = converter.convert(type, value);
        }
        try {
            getPropertyUtils().setSimpleProperty(target, propName, value);
        } catch (NoSuchMethodException e) {
            throw new InvocationTargetException(e, "Cannot set " + propName);
        }
    }

}